blob: 8d04ea40cddbc274b00129b38b8ba992c7a7f9c2 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Guido van Rossumd57fd912000-03-10 22:53:23 +000049/* Endianness switches; defaults to little endian */
50
51#ifdef WORDS_BIGENDIAN
52# define BYTEORDER_IS_BIG_ENDIAN
53#else
54# define BYTEORDER_IS_LITTLE_ENDIAN
55#endif
56
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000057/* --- Globals ------------------------------------------------------------
58
59 The globals are initialized by the _PyUnicode_Init() API and should
60 not be used before calling that API.
61
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (!PyUnicode_IS_COMPACT_ASCII(op) \
133 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
135
Victor Stinner03490912011-10-03 23:45:12 +0200136/* true if the Unicode object has an allocated wstr memory block
137 (not shared with other data) */
138#define _PyUnicode_HAS_WSTR_MEMORY(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 (_PyUnicode_WSTR(op) && \
141 (!PyUnicode_IS_READY(op) || \
142 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
143
Victor Stinner910337b2011-10-03 03:20:16 +0200144/* Generic helper macro to convert characters of different types.
145 from_type and to_type have to be valid type names, begin and end
146 are pointers to the source characters which should be of type
147 "from_type *". to is a pointer of type "to_type *" and points to the
148 buffer where the result characters are written to. */
149#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
150 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 to_type *_to = (to_type *) to; \
152 const from_type *_iter = (begin); \
153 const from_type *_end = (end); \
154 Py_ssize_t n = (_end) - (_iter); \
155 const from_type *_unrolled_end = \
156 _iter + (n & ~ (Py_ssize_t) 3); \
157 while (_iter < (_unrolled_end)) { \
158 _to[0] = (to_type) _iter[0]; \
159 _to[1] = (to_type) _iter[1]; \
160 _to[2] = (to_type) _iter[2]; \
161 _to[3] = (to_type) _iter[3]; \
162 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200164 while (_iter < (_end)) \
165 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200166 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200167
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200168/* The Unicode string has been modified: reset the hash */
169#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
170
Walter Dörwald16807132007-05-25 13:52:07 +0000171/* This dictionary holds all interned unicode strings. Note that references
172 to strings in this dictionary are *not* counted in the string's ob_refcnt.
173 When the interned string reaches a refcnt of 0 the string deallocation
174 function will delete the reference from this dictionary.
175
176 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000177 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000178*/
179static PyObject *interned;
180
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000181/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200182static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000183
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200184/* List of static strings. */
185static _Py_Identifier *static_strings;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* Single character Unicode strings in the Latin-1 range are being
188 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200189static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Christian Heimes190d79e2008-01-30 11:58:22 +0000191/* Fast detection of the most frequent whitespace characters */
192const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000193 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000194/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000196/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000197/* case 0x000C: * FORM FEED */
198/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 1, 1, 1, 1, 1, 0, 0,
200 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x001C: * FILE SEPARATOR */
202/* case 0x001D: * GROUP SEPARATOR */
203/* case 0x001E: * RECORD SEPARATOR */
204/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000206/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000207 1, 0, 0, 0, 0, 0, 0, 0,
208 0, 0, 0, 0, 0, 0, 0, 0,
209 0, 0, 0, 0, 0, 0, 0, 0,
210 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000211
Benjamin Peterson14339b62009-01-31 16:36:08 +0000212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000220};
221
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200222/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200223static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200224static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200225static void copy_characters(
226 PyObject *to, Py_ssize_t to_start,
227 PyObject *from, Py_ssize_t from_start,
228 Py_ssize_t how_many);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229
Alexander Belopolsky40018472011-02-26 01:02:56 +0000230static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200231unicode_fromascii(const unsigned char *s, Py_ssize_t size);
232static PyObject *
233_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
234static PyObject *
235_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
236static PyObject *
237_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
238
239static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000240unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000241 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100242 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000243 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static void
246raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300247 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100248 PyObject *unicode,
249 Py_ssize_t startpos, Py_ssize_t endpos,
250 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000251
Christian Heimes190d79e2008-01-30 11:58:22 +0000252/* Same for linebreaks */
253static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000254 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000255/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000256/* 0x000B, * LINE TABULATION */
257/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000258/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000259 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000260 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000261/* 0x001C, * FILE SEPARATOR */
262/* 0x001D, * GROUP SEPARATOR */
263/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000264 0, 0, 0, 0, 1, 1, 1, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000278};
279
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300280/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
281 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000282Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000283PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000285#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000287#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000288 /* This is actually an illegal character, so it should
289 not be passed to unichr. */
290 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291#endif
292}
293
Victor Stinner910337b2011-10-03 03:20:16 +0200294#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200295int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100296_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200297{
298 PyASCIIObject *ascii;
299 unsigned int kind;
300
301 assert(PyUnicode_Check(op));
302
303 ascii = (PyASCIIObject *)op;
304 kind = ascii->state.kind;
305
Victor Stinnera3b334d2011-10-03 13:53:37 +0200306 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200308 assert(ascii->state.ready == 1);
309 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200310 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200311 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200312 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200313
Victor Stinnera41463c2011-10-04 01:05:08 +0200314 if (ascii->state.compact == 1) {
315 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND
317 || kind == PyUnicode_2BYTE_KIND
318 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100322 }
323 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
325
326 data = unicode->data.any;
327 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100328 assert(ascii->length == 0);
329 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert(ascii->state.compact == 0);
331 assert(ascii->state.ascii == 0);
332 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->wstr != NULL);
335 assert(data == NULL);
336 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 }
338 else {
339 assert(kind == PyUnicode_1BYTE_KIND
340 || kind == PyUnicode_2BYTE_KIND
341 || kind == PyUnicode_4BYTE_KIND);
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ready == 1);
344 assert(data != NULL);
345 if (ascii->state.ascii) {
346 assert (compact->utf8 == data);
347 assert (compact->utf8_length == ascii->length);
348 }
349 else
350 assert (compact->utf8 != data);
351 }
352 }
353 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200354 if (
355#if SIZEOF_WCHAR_T == 2
356 kind == PyUnicode_2BYTE_KIND
357#else
358 kind == PyUnicode_4BYTE_KIND
359#endif
360 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200361 {
362 assert(ascii->wstr == data);
363 assert(compact->wstr_length == ascii->length);
364 } else
365 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200366 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200367
368 if (compact->utf8 == NULL)
369 assert(compact->utf8_length == 0);
370 if (ascii->wstr == NULL)
371 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200372 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200373 /* check that the best kind is used */
374 if (check_content && kind != PyUnicode_WCHAR_KIND)
375 {
376 Py_ssize_t i;
377 Py_UCS4 maxchar = 0;
378 void *data = PyUnicode_DATA(ascii);
379 for (i=0; i < ascii->length; i++)
380 {
381 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
382 if (ch > maxchar)
383 maxchar = ch;
384 }
385 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100386 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100388 assert(maxchar <= 255);
389 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 else
391 assert(maxchar < 128);
392 }
Victor Stinner77faf692011-11-20 18:56:05 +0100393 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100395 assert(maxchar <= 0xFFFF);
396 }
397 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100399 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100400 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400402 return 1;
403}
Victor Stinner910337b2011-10-03 03:20:16 +0200404#endif
405
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100406static PyObject*
407unicode_result_wchar(PyObject *unicode)
408{
409#ifndef Py_DEBUG
410 Py_ssize_t len;
411
412 assert(Py_REFCNT(unicode) == 1);
413
414 len = _PyUnicode_WSTR_LENGTH(unicode);
415 if (len == 0) {
416 Py_INCREF(unicode_empty);
417 Py_DECREF(unicode);
418 return unicode_empty;
419 }
420
421 if (len == 1) {
422 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
423 if (ch < 256) {
424 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
425 Py_DECREF(unicode);
426 return latin1_char;
427 }
428 }
429
430 if (_PyUnicode_Ready(unicode) < 0) {
431 Py_XDECREF(unicode);
432 return NULL;
433 }
434#else
435 /* don't make the result ready in debug mode to ensure that the caller
436 makes the string ready before using it */
437 assert(_PyUnicode_CheckConsistency(unicode, 1));
438#endif
439 return unicode;
440}
441
442static PyObject*
443unicode_result_ready(PyObject *unicode)
444{
445 Py_ssize_t length;
446
447 length = PyUnicode_GET_LENGTH(unicode);
448 if (length == 0) {
449 if (unicode != unicode_empty) {
450 Py_INCREF(unicode_empty);
451 Py_DECREF(unicode);
452 }
453 return unicode_empty;
454 }
455
456 if (length == 1) {
457 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
458 if (ch < 256) {
459 PyObject *latin1_char = unicode_latin1[ch];
460 if (latin1_char != NULL) {
461 if (unicode != latin1_char) {
462 Py_INCREF(latin1_char);
463 Py_DECREF(unicode);
464 }
465 return latin1_char;
466 }
467 else {
468 assert(_PyUnicode_CheckConsistency(unicode, 1));
469 Py_INCREF(unicode);
470 unicode_latin1[ch] = unicode;
471 return unicode;
472 }
473 }
474 }
475
476 assert(_PyUnicode_CheckConsistency(unicode, 1));
477 return unicode;
478}
479
480static PyObject*
481unicode_result(PyObject *unicode)
482{
483 assert(_PyUnicode_CHECK(unicode));
484 if (PyUnicode_IS_READY(unicode))
485 return unicode_result_ready(unicode);
486 else
487 return unicode_result_wchar(unicode);
488}
489
Victor Stinner3a50e702011-10-18 21:21:00 +0200490#ifdef HAVE_MBCS
491static OSVERSIONINFOEX winver;
492#endif
493
Thomas Wouters477c8d52006-05-27 19:21:47 +0000494/* --- Bloom Filters ----------------------------------------------------- */
495
496/* stuff to implement simple "bloom filters" for Unicode characters.
497 to keep things simple, we use a single bitmask, using the least 5
498 bits from each unicode characters as the bit index. */
499
500/* the linebreak mask is set up by Unicode_Init below */
501
Antoine Pitrouf068f942010-01-13 14:19:12 +0000502#if LONG_BIT >= 128
503#define BLOOM_WIDTH 128
504#elif LONG_BIT >= 64
505#define BLOOM_WIDTH 64
506#elif LONG_BIT >= 32
507#define BLOOM_WIDTH 32
508#else
509#error "LONG_BIT is smaller than 32"
510#endif
511
Thomas Wouters477c8d52006-05-27 19:21:47 +0000512#define BLOOM_MASK unsigned long
513
514static BLOOM_MASK bloom_linebreak;
515
Antoine Pitrouf068f942010-01-13 14:19:12 +0000516#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
517#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000518
Benjamin Peterson29060642009-01-31 22:14:21 +0000519#define BLOOM_LINEBREAK(ch) \
520 ((ch) < 128U ? ascii_linebreak[(ch)] : \
521 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522
Alexander Belopolsky40018472011-02-26 01:02:56 +0000523Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200524make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525{
526 /* calculate simple bloom-style bitmask for a given unicode string */
527
Antoine Pitrouf068f942010-01-13 14:19:12 +0000528 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529 Py_ssize_t i;
530
531 mask = 0;
532 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200533 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534
535 return mask;
536}
537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200538#define BLOOM_MEMBER(mask, chr, str) \
539 (BLOOM(mask, chr) \
540 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200542/* Compilation of templated routines */
543
544#include "stringlib/asciilib.h"
545#include "stringlib/fastsearch.h"
546#include "stringlib/partition.h"
547#include "stringlib/split.h"
548#include "stringlib/count.h"
549#include "stringlib/find.h"
550#include "stringlib/find_max_char.h"
551#include "stringlib/localeutil.h"
552#include "stringlib/undef.h"
553
554#include "stringlib/ucs1lib.h"
555#include "stringlib/fastsearch.h"
556#include "stringlib/partition.h"
557#include "stringlib/split.h"
558#include "stringlib/count.h"
559#include "stringlib/find.h"
560#include "stringlib/find_max_char.h"
561#include "stringlib/localeutil.h"
562#include "stringlib/undef.h"
563
564#include "stringlib/ucs2lib.h"
565#include "stringlib/fastsearch.h"
566#include "stringlib/partition.h"
567#include "stringlib/split.h"
568#include "stringlib/count.h"
569#include "stringlib/find.h"
570#include "stringlib/find_max_char.h"
571#include "stringlib/localeutil.h"
572#include "stringlib/undef.h"
573
574#include "stringlib/ucs4lib.h"
575#include "stringlib/fastsearch.h"
576#include "stringlib/partition.h"
577#include "stringlib/split.h"
578#include "stringlib/count.h"
579#include "stringlib/find.h"
580#include "stringlib/find_max_char.h"
581#include "stringlib/localeutil.h"
582#include "stringlib/undef.h"
583
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200584#include "stringlib/unicodedefs.h"
585#include "stringlib/fastsearch.h"
586#include "stringlib/count.h"
587#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100588#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200589
Guido van Rossumd57fd912000-03-10 22:53:23 +0000590/* --- Unicode Object ----------------------------------------------------- */
591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200592static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200593fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200594
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200595Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
596 Py_ssize_t size, Py_UCS4 ch,
597 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200598{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200599 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
600
601 switch (kind) {
602 case PyUnicode_1BYTE_KIND:
603 {
604 Py_UCS1 ch1 = (Py_UCS1) ch;
605 if (ch1 == ch)
606 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
607 else
608 return -1;
609 }
610 case PyUnicode_2BYTE_KIND:
611 {
612 Py_UCS2 ch2 = (Py_UCS2) ch;
613 if (ch2 == ch)
614 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
615 else
616 return -1;
617 }
618 case PyUnicode_4BYTE_KIND:
619 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
620 default:
621 assert(0);
622 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200624}
625
Victor Stinnerfe226c02011-10-03 03:52:20 +0200626static PyObject*
627resize_compact(PyObject *unicode, Py_ssize_t length)
628{
629 Py_ssize_t char_size;
630 Py_ssize_t struct_size;
631 Py_ssize_t new_size;
632 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100633 PyObject *new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200634
635 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200636 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200637 if (PyUnicode_IS_COMPACT_ASCII(unicode))
638 struct_size = sizeof(PyASCIIObject);
639 else
640 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200641 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642
Victor Stinnerfe226c02011-10-03 03:52:20 +0200643 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
Victor Stinner84def372011-12-11 20:04:56 +0100644 Py_DECREF(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200645 PyErr_NoMemory();
646 return NULL;
647 }
648 new_size = (struct_size + (length + 1) * char_size);
649
Victor Stinner84def372011-12-11 20:04:56 +0100650 _Py_DEC_REFTOTAL;
651 _Py_ForgetReference(unicode);
652
653 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
654 if (new_unicode == NULL) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200655 PyObject_Del(unicode);
656 PyErr_NoMemory();
657 return NULL;
658 }
Victor Stinner84def372011-12-11 20:04:56 +0100659 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200660 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200663 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200664 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200665 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
666 _PyUnicode_WSTR_LENGTH(unicode) = length;
667 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200668 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
669 length, 0);
670 return unicode;
671}
672
Alexander Belopolsky40018472011-02-26 01:02:56 +0000673static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200674resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000675{
Victor Stinner95663112011-10-04 01:03:50 +0200676 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000679
Victor Stinner95663112011-10-04 01:03:50 +0200680 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681
682 if (PyUnicode_IS_READY(unicode)) {
683 Py_ssize_t char_size;
684 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200685 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200686 void *data;
687
688 data = _PyUnicode_DATA_ANY(unicode);
689 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200690 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200691 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
692 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200693 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
694 {
695 PyObject_DEL(_PyUnicode_UTF8(unicode));
696 _PyUnicode_UTF8(unicode) = NULL;
697 _PyUnicode_UTF8_LENGTH(unicode) = 0;
698 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200699
700 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
701 PyErr_NoMemory();
702 return -1;
703 }
704 new_size = (length + 1) * char_size;
705
706 data = (PyObject *)PyObject_REALLOC(data, new_size);
707 if (data == NULL) {
708 PyErr_NoMemory();
709 return -1;
710 }
711 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200712 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200713 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200714 _PyUnicode_WSTR_LENGTH(unicode) = length;
715 }
716 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200717 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200718 _PyUnicode_UTF8_LENGTH(unicode) = length;
719 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720 _PyUnicode_LENGTH(unicode) = length;
721 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200722 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200723 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200724 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200725 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200726 }
Victor Stinner95663112011-10-04 01:03:50 +0200727 assert(_PyUnicode_WSTR(unicode) != NULL);
728
729 /* check for integer overflow */
730 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
731 PyErr_NoMemory();
732 return -1;
733 }
734 wstr = _PyUnicode_WSTR(unicode);
735 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
736 if (!wstr) {
737 PyErr_NoMemory();
738 return -1;
739 }
740 _PyUnicode_WSTR(unicode) = wstr;
741 _PyUnicode_WSTR(unicode)[length] = 0;
742 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200743 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000744 return 0;
745}
746
Victor Stinnerfe226c02011-10-03 03:52:20 +0200747static PyObject*
748resize_copy(PyObject *unicode, Py_ssize_t length)
749{
750 Py_ssize_t copy_length;
751 if (PyUnicode_IS_COMPACT(unicode)) {
752 PyObject *copy;
753 assert(PyUnicode_IS_READY(unicode));
754
755 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
756 if (copy == NULL)
757 return NULL;
758
759 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200760 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200761 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200762 }
763 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200764 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 assert(_PyUnicode_WSTR(unicode) != NULL);
766 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200767 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768 if (w == NULL)
769 return NULL;
770 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
771 copy_length = Py_MIN(copy_length, length);
772 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
773 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200774 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200775 }
776}
777
Guido van Rossumd57fd912000-03-10 22:53:23 +0000778/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000779 Ux0000 terminated; some code (e.g. new_identifier)
780 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000781
782 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000783 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000784
785*/
786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200787#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200788static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200789#endif
790
Alexander Belopolsky40018472011-02-26 01:02:56 +0000791static PyUnicodeObject *
792_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000793{
794 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200795 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000796
Thomas Wouters477c8d52006-05-27 19:21:47 +0000797 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000798 if (length == 0 && unicode_empty != NULL) {
799 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200800 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000801 }
802
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000803 /* Ensure we won't overflow the size. */
804 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
805 return (PyUnicodeObject *)PyErr_NoMemory();
806 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200807 if (length < 0) {
808 PyErr_SetString(PyExc_SystemError,
809 "Negative size passed to _PyUnicode_New");
810 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000811 }
812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200813#ifdef Py_DEBUG
814 ++unicode_old_new_calls;
815#endif
816
817 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
818 if (unicode == NULL)
819 return NULL;
820 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
821 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
822 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000823 PyErr_NoMemory();
824 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000825 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826
Jeremy Hyltond8082792003-09-16 19:41:39 +0000827 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000828 * the caller fails before initializing str -- unicode_resize()
829 * reads str[0], and the Keep-Alive optimization can keep memory
830 * allocated for str alive across a call to unicode_dealloc(unicode).
831 * We don't want unicode_resize to read uninitialized memory in
832 * that case.
833 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200834 _PyUnicode_WSTR(unicode)[0] = 0;
835 _PyUnicode_WSTR(unicode)[length] = 0;
836 _PyUnicode_WSTR_LENGTH(unicode) = length;
837 _PyUnicode_HASH(unicode) = -1;
838 _PyUnicode_STATE(unicode).interned = 0;
839 _PyUnicode_STATE(unicode).kind = 0;
840 _PyUnicode_STATE(unicode).compact = 0;
841 _PyUnicode_STATE(unicode).ready = 0;
842 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200843 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200844 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200845 _PyUnicode_UTF8(unicode) = NULL;
846 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100847 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000848 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000849
Benjamin Peterson29060642009-01-31 22:14:21 +0000850 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000851 /* XXX UNREF/NEWREF interface should be more symmetrical */
852 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000853 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000854 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000855 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000856}
857
Victor Stinnerf42dc442011-10-02 23:33:16 +0200858static const char*
859unicode_kind_name(PyObject *unicode)
860{
Victor Stinner42dfd712011-10-03 14:41:45 +0200861 /* don't check consistency: unicode_kind_name() is called from
862 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200863 if (!PyUnicode_IS_COMPACT(unicode))
864 {
865 if (!PyUnicode_IS_READY(unicode))
866 return "wstr";
867 switch(PyUnicode_KIND(unicode))
868 {
869 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200870 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200871 return "legacy ascii";
872 else
873 return "legacy latin1";
874 case PyUnicode_2BYTE_KIND:
875 return "legacy UCS2";
876 case PyUnicode_4BYTE_KIND:
877 return "legacy UCS4";
878 default:
879 return "<legacy invalid kind>";
880 }
881 }
882 assert(PyUnicode_IS_READY(unicode));
883 switch(PyUnicode_KIND(unicode))
884 {
885 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200886 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200887 return "ascii";
888 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200889 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200890 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200891 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200892 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 default:
895 return "<invalid compact kind>";
896 }
897}
898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200899#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200900static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200901
902/* Functions wrapping macros for use in debugger */
903char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200904 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905}
906
907void *_PyUnicode_compact_data(void *unicode) {
908 return _PyUnicode_COMPACT_DATA(unicode);
909}
910void *_PyUnicode_data(void *unicode){
911 printf("obj %p\n", unicode);
912 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
913 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
914 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
915 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
916 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
917 return PyUnicode_DATA(unicode);
918}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200919
920void
921_PyUnicode_Dump(PyObject *op)
922{
923 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200924 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
925 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
926 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200927
Victor Stinnera849a4b2011-10-03 12:12:11 +0200928 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200929 {
930 if (ascii->state.ascii)
931 data = (ascii + 1);
932 else
933 data = (compact + 1);
934 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200935 else
936 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200937 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
938
Victor Stinnera849a4b2011-10-03 12:12:11 +0200939 if (ascii->wstr == data)
940 printf("shared ");
941 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200942
Victor Stinnera3b334d2011-10-03 13:53:37 +0200943 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200944 printf(" (%zu), ", compact->wstr_length);
945 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
946 printf("shared ");
947 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200948 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200949 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200950}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200951#endif
952
953PyObject *
954PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
955{
956 PyObject *obj;
957 PyCompactUnicodeObject *unicode;
958 void *data;
959 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200960 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200961 Py_ssize_t char_size;
962 Py_ssize_t struct_size;
963
964 /* Optimization for empty strings */
965 if (size == 0 && unicode_empty != NULL) {
966 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200967 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 }
969
970#ifdef Py_DEBUG
971 ++unicode_new_new_calls;
972#endif
973
Victor Stinner9e9d6892011-10-04 01:02:02 +0200974 is_ascii = 0;
975 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 struct_size = sizeof(PyCompactUnicodeObject);
977 if (maxchar < 128) {
978 kind_state = PyUnicode_1BYTE_KIND;
979 char_size = 1;
980 is_ascii = 1;
981 struct_size = sizeof(PyASCIIObject);
982 }
983 else if (maxchar < 256) {
984 kind_state = PyUnicode_1BYTE_KIND;
985 char_size = 1;
986 }
987 else if (maxchar < 65536) {
988 kind_state = PyUnicode_2BYTE_KIND;
989 char_size = 2;
990 if (sizeof(wchar_t) == 2)
991 is_sharing = 1;
992 }
993 else {
994 kind_state = PyUnicode_4BYTE_KIND;
995 char_size = 4;
996 if (sizeof(wchar_t) == 4)
997 is_sharing = 1;
998 }
999
1000 /* Ensure we won't overflow the size. */
1001 if (size < 0) {
1002 PyErr_SetString(PyExc_SystemError,
1003 "Negative size passed to PyUnicode_New");
1004 return NULL;
1005 }
1006 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1007 return PyErr_NoMemory();
1008
1009 /* Duplicated allocation code from _PyObject_New() instead of a call to
1010 * PyObject_New() so we are able to allocate space for the object and
1011 * it's data buffer.
1012 */
1013 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1014 if (obj == NULL)
1015 return PyErr_NoMemory();
1016 obj = PyObject_INIT(obj, &PyUnicode_Type);
1017 if (obj == NULL)
1018 return NULL;
1019
1020 unicode = (PyCompactUnicodeObject *)obj;
1021 if (is_ascii)
1022 data = ((PyASCIIObject*)obj) + 1;
1023 else
1024 data = unicode + 1;
1025 _PyUnicode_LENGTH(unicode) = size;
1026 _PyUnicode_HASH(unicode) = -1;
1027 _PyUnicode_STATE(unicode).interned = 0;
1028 _PyUnicode_STATE(unicode).kind = kind_state;
1029 _PyUnicode_STATE(unicode).compact = 1;
1030 _PyUnicode_STATE(unicode).ready = 1;
1031 _PyUnicode_STATE(unicode).ascii = is_ascii;
1032 if (is_ascii) {
1033 ((char*)data)[size] = 0;
1034 _PyUnicode_WSTR(unicode) = NULL;
1035 }
1036 else if (kind_state == PyUnicode_1BYTE_KIND) {
1037 ((char*)data)[size] = 0;
1038 _PyUnicode_WSTR(unicode) = NULL;
1039 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001041 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001042 }
1043 else {
1044 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001045 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 if (kind_state == PyUnicode_2BYTE_KIND)
1047 ((Py_UCS2*)data)[size] = 0;
1048 else /* kind_state == PyUnicode_4BYTE_KIND */
1049 ((Py_UCS4*)data)[size] = 0;
1050 if (is_sharing) {
1051 _PyUnicode_WSTR_LENGTH(unicode) = size;
1052 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1053 }
1054 else {
1055 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1056 _PyUnicode_WSTR(unicode) = NULL;
1057 }
1058 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001059 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 return obj;
1061}
1062
1063#if SIZEOF_WCHAR_T == 2
1064/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1065 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001066 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001067
1068 This function assumes that unicode can hold one more code point than wstr
1069 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001070static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001072 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073{
1074 const wchar_t *iter;
1075 Py_UCS4 *ucs4_out;
1076
Victor Stinner910337b2011-10-03 03:20:16 +02001077 assert(unicode != NULL);
1078 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1080 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1081
1082 for (iter = begin; iter < end; ) {
1083 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1084 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001085 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1086 && (iter+1) < end
1087 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001088 {
Victor Stinner551ac952011-11-29 22:58:13 +01001089 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001090 iter += 2;
1091 }
1092 else {
1093 *ucs4_out++ = *iter;
1094 iter++;
1095 }
1096 }
1097 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1098 _PyUnicode_GET_LENGTH(unicode)));
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100}
1101#endif
1102
Victor Stinnercd9950f2011-10-02 00:34:53 +02001103static int
1104_PyUnicode_Dirty(PyObject *unicode)
1105{
Victor Stinner910337b2011-10-03 03:20:16 +02001106 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001107 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001108 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001109 "Cannot modify a string having more than 1 reference");
1110 return -1;
1111 }
1112 _PyUnicode_DIRTY(unicode);
1113 return 0;
1114}
1115
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001116static int
1117_copy_characters(PyObject *to, Py_ssize_t to_start,
1118 PyObject *from, Py_ssize_t from_start,
1119 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001121 unsigned int from_kind, to_kind;
1122 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001123 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001124
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001125 assert(PyUnicode_Check(from));
1126 assert(PyUnicode_Check(to));
1127 assert(PyUnicode_IS_READY(from));
1128 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001130 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1131 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1132 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001133
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001134 if (how_many == 0)
1135 return 0;
1136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001137 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001138 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001140 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001141
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001142#ifdef Py_DEBUG
1143 if (!check_maxchar
1144 && (from_kind > to_kind
1145 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001146 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001147 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1148 Py_UCS4 ch;
1149 Py_ssize_t i;
1150 for (i=0; i < how_many; i++) {
1151 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1152 assert(ch <= to_maxchar);
1153 }
1154 }
1155#endif
1156 fast = (from_kind == to_kind);
1157 if (check_maxchar
1158 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1159 {
1160 /* deny latin1 => ascii */
1161 fast = 0;
1162 }
1163
1164 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001165 Py_MEMCPY((char*)to_data + to_kind * to_start,
1166 (char*)from_data + from_kind * from_start,
1167 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001168 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001169 else if (from_kind == PyUnicode_1BYTE_KIND
1170 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001171 {
1172 _PyUnicode_CONVERT_BYTES(
1173 Py_UCS1, Py_UCS2,
1174 PyUnicode_1BYTE_DATA(from) + from_start,
1175 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1176 PyUnicode_2BYTE_DATA(to) + to_start
1177 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001178 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001179 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001180 && to_kind == PyUnicode_4BYTE_KIND)
1181 {
1182 _PyUnicode_CONVERT_BYTES(
1183 Py_UCS1, Py_UCS4,
1184 PyUnicode_1BYTE_DATA(from) + from_start,
1185 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1186 PyUnicode_4BYTE_DATA(to) + to_start
1187 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001188 }
1189 else if (from_kind == PyUnicode_2BYTE_KIND
1190 && to_kind == PyUnicode_4BYTE_KIND)
1191 {
1192 _PyUnicode_CONVERT_BYTES(
1193 Py_UCS2, Py_UCS4,
1194 PyUnicode_2BYTE_DATA(from) + from_start,
1195 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1196 PyUnicode_4BYTE_DATA(to) + to_start
1197 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001198 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001199 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001200 /* check if max_char(from substring) <= max_char(to) */
1201 if (from_kind > to_kind
1202 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001203 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001204 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 /* slow path to check for character overflow */
1206 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001207 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001208 Py_ssize_t i;
1209
Victor Stinner56c161a2011-10-06 02:47:11 +02001210#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001211 for (i=0; i < how_many; i++) {
1212 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001213 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001214 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1215 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001216#else
1217 if (!check_maxchar) {
1218 for (i=0; i < how_many; i++) {
1219 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1220 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1221 }
1222 }
1223 else {
1224 for (i=0; i < how_many; i++) {
1225 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1226 if (ch > to_maxchar)
1227 return 1;
1228 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1229 }
1230 }
1231#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001232 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001233 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001234 assert(0 && "inconsistent state");
1235 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001236 }
1237 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001238 return 0;
1239}
1240
1241static void
1242copy_characters(PyObject *to, Py_ssize_t to_start,
1243 PyObject *from, Py_ssize_t from_start,
1244 Py_ssize_t how_many)
1245{
1246 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1247}
1248
1249Py_ssize_t
1250PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1251 PyObject *from, Py_ssize_t from_start,
1252 Py_ssize_t how_many)
1253{
1254 int err;
1255
1256 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1257 PyErr_BadInternalCall();
1258 return -1;
1259 }
1260
1261 if (PyUnicode_READY(from))
1262 return -1;
1263 if (PyUnicode_READY(to))
1264 return -1;
1265
1266 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1267 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1268 PyErr_Format(PyExc_SystemError,
1269 "Cannot write %zi characters at %zi "
1270 "in a string of %zi characters",
1271 how_many, to_start, PyUnicode_GET_LENGTH(to));
1272 return -1;
1273 }
1274
1275 if (how_many == 0)
1276 return 0;
1277
1278 if (_PyUnicode_Dirty(to))
1279 return -1;
1280
1281 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1282 if (err) {
1283 PyErr_Format(PyExc_SystemError,
1284 "Cannot copy %s characters "
1285 "into a string of %s characters",
1286 unicode_kind_name(from),
1287 unicode_kind_name(to));
1288 return -1;
1289 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001290 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001291}
1292
Victor Stinner17222162011-09-28 22:15:37 +02001293/* Find the maximum code point and count the number of surrogate pairs so a
1294 correct string length can be computed before converting a string to UCS4.
1295 This function counts single surrogates as a character and not as a pair.
1296
1297 Return 0 on success, or -1 on error. */
1298static int
1299find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1300 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301{
1302 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001303 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304
Victor Stinnerc53be962011-10-02 21:33:54 +02001305 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306 *num_surrogates = 0;
1307 *maxchar = 0;
1308
1309 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001311 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1312 && (iter+1) < end
1313 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001315 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 iter += 2;
1318 }
1319 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001321 {
1322 ch = *iter;
1323 iter++;
1324 }
1325 if (ch > *maxchar) {
1326 *maxchar = ch;
1327 if (*maxchar > MAX_UNICODE) {
1328 PyErr_Format(PyExc_ValueError,
1329 "character U+%x is not in range [U+0000; U+10ffff]",
1330 ch);
1331 return -1;
1332 }
1333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334 }
1335 return 0;
1336}
1337
1338#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001339static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340#endif
1341
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001342int
1343_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344{
1345 wchar_t *end;
1346 Py_UCS4 maxchar = 0;
1347 Py_ssize_t num_surrogates;
1348#if SIZEOF_WCHAR_T == 2
1349 Py_ssize_t length_wo_surrogates;
1350#endif
1351
Georg Brandl7597add2011-10-05 16:36:47 +02001352 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001353 strings were created using _PyObject_New() and where no canonical
1354 representation (the str field) has been set yet aka strings
1355 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001356 assert(_PyUnicode_CHECK(unicode));
1357 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001360 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001361 /* Actually, it should neither be interned nor be anything else: */
1362 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363
1364#ifdef Py_DEBUG
1365 ++unicode_ready_calls;
1366#endif
1367
1368 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001369 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001370 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372
1373 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001374 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1375 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 PyErr_NoMemory();
1377 return -1;
1378 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001379 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 _PyUnicode_WSTR(unicode), end,
1381 PyUnicode_1BYTE_DATA(unicode));
1382 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1383 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1384 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1385 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001386 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001387 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001388 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389 }
1390 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001391 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001392 _PyUnicode_UTF8(unicode) = NULL;
1393 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394 }
1395 PyObject_FREE(_PyUnicode_WSTR(unicode));
1396 _PyUnicode_WSTR(unicode) = NULL;
1397 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1398 }
1399 /* In this case we might have to convert down from 4-byte native
1400 wchar_t to 2-byte unicode. */
1401 else if (maxchar < 65536) {
1402 assert(num_surrogates == 0 &&
1403 "FindMaxCharAndNumSurrogatePairs() messed up");
1404
Victor Stinner506f5922011-09-28 22:34:18 +02001405#if SIZEOF_WCHAR_T == 2
1406 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001407 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001408 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1409 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1410 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001411 _PyUnicode_UTF8(unicode) = NULL;
1412 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001413#else
1414 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001415 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001416 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001417 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001418 PyErr_NoMemory();
1419 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420 }
Victor Stinner506f5922011-09-28 22:34:18 +02001421 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1422 _PyUnicode_WSTR(unicode), end,
1423 PyUnicode_2BYTE_DATA(unicode));
1424 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1425 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1426 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001427 _PyUnicode_UTF8(unicode) = NULL;
1428 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001429 PyObject_FREE(_PyUnicode_WSTR(unicode));
1430 _PyUnicode_WSTR(unicode) = NULL;
1431 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1432#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 }
1434 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1435 else {
1436#if SIZEOF_WCHAR_T == 2
1437 /* in case the native representation is 2-bytes, we need to allocate a
1438 new normalized 4-byte version. */
1439 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001440 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1441 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001442 PyErr_NoMemory();
1443 return -1;
1444 }
1445 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1446 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001447 _PyUnicode_UTF8(unicode) = NULL;
1448 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001449 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1450 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001451 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452 PyObject_FREE(_PyUnicode_WSTR(unicode));
1453 _PyUnicode_WSTR(unicode) = NULL;
1454 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1455#else
1456 assert(num_surrogates == 0);
1457
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001460 _PyUnicode_UTF8(unicode) = NULL;
1461 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1463#endif
1464 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1465 }
1466 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001467 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 return 0;
1469}
1470
Alexander Belopolsky40018472011-02-26 01:02:56 +00001471static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001472unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001473{
Walter Dörwald16807132007-05-25 13:52:07 +00001474 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001475 case SSTATE_NOT_INTERNED:
1476 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001477
Benjamin Peterson29060642009-01-31 22:14:21 +00001478 case SSTATE_INTERNED_MORTAL:
1479 /* revive dead object temporarily for DelItem */
1480 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001481 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001482 Py_FatalError(
1483 "deletion of interned string failed");
1484 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001485
Benjamin Peterson29060642009-01-31 22:14:21 +00001486 case SSTATE_INTERNED_IMMORTAL:
1487 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001488
Benjamin Peterson29060642009-01-31 22:14:21 +00001489 default:
1490 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001491 }
1492
Victor Stinner03490912011-10-03 23:45:12 +02001493 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001494 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001495 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001496 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001497
1498 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001499 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001500 }
1501 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001502 if (_PyUnicode_DATA_ANY(unicode))
1503 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001504 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001505 }
1506}
1507
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001508#ifdef Py_DEBUG
1509static int
1510unicode_is_singleton(PyObject *unicode)
1511{
1512 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1513 if (unicode == unicode_empty)
1514 return 1;
1515 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1516 {
1517 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1518 if (ch < 256 && unicode_latin1[ch] == unicode)
1519 return 1;
1520 }
1521 return 0;
1522}
1523#endif
1524
Alexander Belopolsky40018472011-02-26 01:02:56 +00001525static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001527{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001528 if (Py_REFCNT(unicode) != 1)
1529 return 0;
1530 if (PyUnicode_CHECK_INTERNED(unicode))
1531 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001532#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001533 /* singleton refcount is greater than 1 */
1534 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001535#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 1;
1537}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001538
Victor Stinnerfe226c02011-10-03 03:52:20 +02001539static int
1540unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1541{
1542 PyObject *unicode;
1543 Py_ssize_t old_length;
1544
1545 assert(p_unicode != NULL);
1546 unicode = *p_unicode;
1547
1548 assert(unicode != NULL);
1549 assert(PyUnicode_Check(unicode));
1550 assert(0 <= length);
1551
Victor Stinner910337b2011-10-03 03:20:16 +02001552 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001553 old_length = PyUnicode_WSTR_LENGTH(unicode);
1554 else
1555 old_length = PyUnicode_GET_LENGTH(unicode);
1556 if (old_length == length)
1557 return 0;
1558
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001559 if (length == 0) {
1560 Py_DECREF(*p_unicode);
1561 *p_unicode = unicode_empty;
1562 Py_INCREF(*p_unicode);
1563 return 0;
1564 }
1565
Victor Stinnerfe226c02011-10-03 03:52:20 +02001566 if (!unicode_resizable(unicode)) {
1567 PyObject *copy = resize_copy(unicode, length);
1568 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001569 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001570 Py_DECREF(*p_unicode);
1571 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001572 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001573 }
1574
Victor Stinnerfe226c02011-10-03 03:52:20 +02001575 if (PyUnicode_IS_COMPACT(unicode)) {
1576 *p_unicode = resize_compact(unicode, length);
1577 if (*p_unicode == NULL)
1578 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001579 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001581 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001582 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583}
1584
Alexander Belopolsky40018472011-02-26 01:02:56 +00001585int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001586PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001587{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001588 PyObject *unicode;
1589 if (p_unicode == NULL) {
1590 PyErr_BadInternalCall();
1591 return -1;
1592 }
1593 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001594 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 {
1596 PyErr_BadInternalCall();
1597 return -1;
1598 }
1599 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001600}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001601
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001602static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001603unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001604{
1605 PyObject *result;
1606 assert(PyUnicode_IS_READY(*p_unicode));
1607 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1608 return 0;
1609 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1610 maxchar);
1611 if (result == NULL)
1612 return -1;
1613 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1614 PyUnicode_GET_LENGTH(*p_unicode));
1615 Py_DECREF(*p_unicode);
1616 *p_unicode = result;
1617 return 0;
1618}
1619
1620static int
1621unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1622 Py_UCS4 ch)
1623{
1624 if (unicode_widen(p_unicode, ch) < 0)
1625 return -1;
1626 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1627 PyUnicode_DATA(*p_unicode),
1628 (*pos)++, ch);
1629 return 0;
1630}
1631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632static PyObject*
1633get_latin1_char(unsigned char ch)
1634{
Victor Stinnera464fc12011-10-02 20:39:30 +02001635 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001636 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001637 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638 if (!unicode)
1639 return NULL;
1640 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001641 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 unicode_latin1[ch] = unicode;
1643 }
1644 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001645 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646}
1647
Alexander Belopolsky40018472011-02-26 01:02:56 +00001648PyObject *
1649PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001650{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001651 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652 Py_UCS4 maxchar = 0;
1653 Py_ssize_t num_surrogates;
1654
1655 if (u == NULL)
1656 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001657
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001658 /* If the Unicode data is known at construction time, we can apply
1659 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 /* Optimization for empty strings */
1662 if (size == 0 && unicode_empty != NULL) {
1663 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001664 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001665 }
Tim Petersced69f82003-09-16 20:30:58 +00001666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001667 /* Single character Unicode objects in the Latin-1 range are
1668 shared when using this constructor */
1669 if (size == 1 && *u < 256)
1670 return get_latin1_char((unsigned char)*u);
1671
1672 /* If not empty and not single character, copy the Unicode data
1673 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001674 if (find_maxchar_surrogates(u, u + size,
1675 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001676 return NULL;
1677
Victor Stinner8faf8212011-12-08 22:14:11 +01001678 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001679 if (!unicode)
1680 return NULL;
1681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001682 switch (PyUnicode_KIND(unicode)) {
1683 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001684 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001685 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1686 break;
1687 case PyUnicode_2BYTE_KIND:
1688#if Py_UNICODE_SIZE == 2
1689 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1690#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001691 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1693#endif
1694 break;
1695 case PyUnicode_4BYTE_KIND:
1696#if SIZEOF_WCHAR_T == 2
1697 /* This is the only case which has to process surrogates, thus
1698 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001699 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700#else
1701 assert(num_surrogates == 0);
1702 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1703#endif
1704 break;
1705 default:
1706 assert(0 && "Impossible state");
1707 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001708
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001709 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001710}
1711
Alexander Belopolsky40018472011-02-26 01:02:56 +00001712PyObject *
1713PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001714{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001715 if (size < 0) {
1716 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001717 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001718 return NULL;
1719 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001720 if (u != NULL)
1721 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1722 else
1723 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001724}
1725
Alexander Belopolsky40018472011-02-26 01:02:56 +00001726PyObject *
1727PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001728{
1729 size_t size = strlen(u);
1730 if (size > PY_SSIZE_T_MAX) {
1731 PyErr_SetString(PyExc_OverflowError, "input too long");
1732 return NULL;
1733 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001734 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001735}
1736
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001737PyObject *
1738_PyUnicode_FromId(_Py_Identifier *id)
1739{
1740 if (!id->object) {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001741 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1742 strlen(id->string),
1743 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001744 if (!id->object)
1745 return NULL;
1746 PyUnicode_InternInPlace(&id->object);
1747 assert(!id->next);
1748 id->next = static_strings;
1749 static_strings = id;
1750 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001751 return id->object;
1752}
1753
1754void
1755_PyUnicode_ClearStaticStrings()
1756{
1757 _Py_Identifier *i;
1758 for (i = static_strings; i; i = i->next) {
1759 Py_DECREF(i->object);
1760 i->object = NULL;
1761 i->next = NULL;
1762 }
1763}
1764
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001765/* Internal function, don't check maximum character */
1766
Victor Stinnere57b1c02011-09-28 22:20:48 +02001767static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001768unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001769{
Victor Stinner785938e2011-12-11 20:09:03 +01001770 PyObject *unicode;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001771#ifdef Py_DEBUG
1772 const unsigned char *p;
1773 const unsigned char *end = s + size;
1774 for (p=s; p < end; p++) {
1775 assert(*p < 128);
1776 }
1777#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001778 if (size == 1)
1779 return get_latin1_char(s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01001780 unicode = PyUnicode_New(size, 127);
1781 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001782 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001783 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1784 assert(_PyUnicode_CheckConsistency(unicode, 1));
1785 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001786}
1787
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001788static Py_UCS4
1789kind_maxchar_limit(unsigned int kind)
1790{
1791 switch(kind) {
1792 case PyUnicode_1BYTE_KIND:
1793 return 0x80;
1794 case PyUnicode_2BYTE_KIND:
1795 return 0x100;
1796 case PyUnicode_4BYTE_KIND:
1797 return 0x10000;
1798 default:
1799 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001800 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001801 }
1802}
1803
Victor Stinner702c7342011-10-05 13:50:52 +02001804static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001805_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001806{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001807 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001808 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001809
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001810 if (size == 0) {
1811 Py_INCREF(unicode_empty);
1812 return unicode_empty;
1813 }
1814 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001815 if (size == 1)
1816 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001817
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001818 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001819 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001820 if (!res)
1821 return NULL;
1822 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001823 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001825}
1826
Victor Stinnere57b1c02011-09-28 22:20:48 +02001827static PyObject*
1828_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001829{
1830 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001831 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001832
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001833 if (size == 0) {
1834 Py_INCREF(unicode_empty);
1835 return unicode_empty;
1836 }
1837 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001838 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001839 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001840
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001841 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001842 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001843 if (!res)
1844 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001845 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001846 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001847 else {
1848 _PyUnicode_CONVERT_BYTES(
1849 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1850 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001851 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001852 return res;
1853}
1854
Victor Stinnere57b1c02011-09-28 22:20:48 +02001855static PyObject*
1856_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857{
1858 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001859 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001860
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861 if (size == 0) {
1862 Py_INCREF(unicode_empty);
1863 return unicode_empty;
1864 }
1865 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001866 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001867 return get_latin1_char((unsigned char)u[0]);
1868
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001869 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001870 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001871 if (!res)
1872 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001873 if (max_char < 256)
1874 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1875 PyUnicode_1BYTE_DATA(res));
1876 else if (max_char < 0x10000)
1877 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1878 PyUnicode_2BYTE_DATA(res));
1879 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001880 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001881 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001882 return res;
1883}
1884
1885PyObject*
1886PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1887{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001888 if (size < 0) {
1889 PyErr_SetString(PyExc_ValueError, "size must be positive");
1890 return NULL;
1891 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001892 switch(kind) {
1893 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001894 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001895 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001896 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001898 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001899 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001900 PyErr_SetString(PyExc_SystemError, "invalid kind");
1901 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001902 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903}
1904
Victor Stinner25a4b292011-10-06 12:31:55 +02001905/* Ensure that a string uses the most efficient storage, if it is not the
1906 case: create a new string with of the right kind. Write NULL into *p_unicode
1907 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001908static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001909unicode_adjust_maxchar(PyObject **p_unicode)
1910{
1911 PyObject *unicode, *copy;
1912 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001913 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001914 unsigned int kind;
1915
1916 assert(p_unicode != NULL);
1917 unicode = *p_unicode;
1918 assert(PyUnicode_IS_READY(unicode));
1919 if (PyUnicode_IS_ASCII(unicode))
1920 return;
1921
1922 len = PyUnicode_GET_LENGTH(unicode);
1923 kind = PyUnicode_KIND(unicode);
1924 if (kind == PyUnicode_1BYTE_KIND) {
1925 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001926 max_char = ucs1lib_find_max_char(u, u + len);
1927 if (max_char >= 128)
1928 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001929 }
1930 else if (kind == PyUnicode_2BYTE_KIND) {
1931 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001932 max_char = ucs2lib_find_max_char(u, u + len);
1933 if (max_char >= 256)
1934 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001935 }
1936 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001937 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001938 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001939 max_char = ucs4lib_find_max_char(u, u + len);
1940 if (max_char >= 0x10000)
1941 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001942 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001943 copy = PyUnicode_New(len, max_char);
1944 copy_characters(copy, 0, unicode, 0, len);
1945 Py_DECREF(unicode);
1946 *p_unicode = copy;
1947}
1948
Victor Stinner034f6cf2011-09-30 02:26:44 +02001949PyObject*
1950PyUnicode_Copy(PyObject *unicode)
1951{
Victor Stinner87af4f22011-11-21 23:03:47 +01001952 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001953 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001954
Victor Stinner034f6cf2011-09-30 02:26:44 +02001955 if (!PyUnicode_Check(unicode)) {
1956 PyErr_BadInternalCall();
1957 return NULL;
1958 }
1959 if (PyUnicode_READY(unicode))
1960 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001961
Victor Stinner87af4f22011-11-21 23:03:47 +01001962 length = PyUnicode_GET_LENGTH(unicode);
1963 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001964 if (!copy)
1965 return NULL;
1966 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1967
Victor Stinner87af4f22011-11-21 23:03:47 +01001968 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1969 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001970 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001971 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001972}
1973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974
Victor Stinnerbc603d12011-10-02 01:00:40 +02001975/* Widen Unicode objects to larger buffers. Don't write terminating null
1976 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977
1978void*
1979_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1980{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001981 Py_ssize_t len;
1982 void *result;
1983 unsigned int skind;
1984
1985 if (PyUnicode_READY(s))
1986 return NULL;
1987
1988 len = PyUnicode_GET_LENGTH(s);
1989 skind = PyUnicode_KIND(s);
1990 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001991 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 return NULL;
1993 }
1994 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001995 case PyUnicode_2BYTE_KIND:
1996 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1997 if (!result)
1998 return PyErr_NoMemory();
1999 assert(skind == PyUnicode_1BYTE_KIND);
2000 _PyUnicode_CONVERT_BYTES(
2001 Py_UCS1, Py_UCS2,
2002 PyUnicode_1BYTE_DATA(s),
2003 PyUnicode_1BYTE_DATA(s) + len,
2004 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002006 case PyUnicode_4BYTE_KIND:
2007 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2008 if (!result)
2009 return PyErr_NoMemory();
2010 if (skind == PyUnicode_2BYTE_KIND) {
2011 _PyUnicode_CONVERT_BYTES(
2012 Py_UCS2, Py_UCS4,
2013 PyUnicode_2BYTE_DATA(s),
2014 PyUnicode_2BYTE_DATA(s) + len,
2015 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002017 else {
2018 assert(skind == PyUnicode_1BYTE_KIND);
2019 _PyUnicode_CONVERT_BYTES(
2020 Py_UCS1, Py_UCS4,
2021 PyUnicode_1BYTE_DATA(s),
2022 PyUnicode_1BYTE_DATA(s) + len,
2023 result);
2024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002026 default:
2027 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028 }
Victor Stinner01698042011-10-04 00:04:26 +02002029 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 return NULL;
2031}
2032
2033static Py_UCS4*
2034as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2035 int copy_null)
2036{
2037 int kind;
2038 void *data;
2039 Py_ssize_t len, targetlen;
2040 if (PyUnicode_READY(string) == -1)
2041 return NULL;
2042 kind = PyUnicode_KIND(string);
2043 data = PyUnicode_DATA(string);
2044 len = PyUnicode_GET_LENGTH(string);
2045 targetlen = len;
2046 if (copy_null)
2047 targetlen++;
2048 if (!target) {
2049 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2050 PyErr_NoMemory();
2051 return NULL;
2052 }
2053 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2054 if (!target) {
2055 PyErr_NoMemory();
2056 return NULL;
2057 }
2058 }
2059 else {
2060 if (targetsize < targetlen) {
2061 PyErr_Format(PyExc_SystemError,
2062 "string is longer than the buffer");
2063 if (copy_null && 0 < targetsize)
2064 target[0] = 0;
2065 return NULL;
2066 }
2067 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002068 if (kind == PyUnicode_1BYTE_KIND) {
2069 Py_UCS1 *start = (Py_UCS1 *) data;
2070 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002072 else if (kind == PyUnicode_2BYTE_KIND) {
2073 Py_UCS2 *start = (Py_UCS2 *) data;
2074 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2075 }
2076 else {
2077 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002080 if (copy_null)
2081 target[len] = 0;
2082 return target;
2083}
2084
2085Py_UCS4*
2086PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2087 int copy_null)
2088{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002089 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090 PyErr_BadInternalCall();
2091 return NULL;
2092 }
2093 return as_ucs4(string, target, targetsize, copy_null);
2094}
2095
2096Py_UCS4*
2097PyUnicode_AsUCS4Copy(PyObject *string)
2098{
2099 return as_ucs4(string, NULL, 0, 1);
2100}
2101
2102#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002103
Alexander Belopolsky40018472011-02-26 01:02:56 +00002104PyObject *
2105PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002106{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002107 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002108 if (size == 0) {
2109 Py_INCREF(unicode_empty);
2110 return unicode_empty;
2111 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002112 PyErr_BadInternalCall();
2113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002114 }
2115
Martin v. Löwis790465f2008-04-05 20:41:37 +00002116 if (size == -1) {
2117 size = wcslen(w);
2118 }
2119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002120 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002121}
2122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002123#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002124
Walter Dörwald346737f2007-05-31 10:44:43 +00002125static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002126makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2127 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002128{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002129 *fmt++ = '%';
2130 if (width) {
2131 if (zeropad)
2132 *fmt++ = '0';
2133 fmt += sprintf(fmt, "%d", width);
2134 }
2135 if (precision)
2136 fmt += sprintf(fmt, ".%d", precision);
2137 if (longflag)
2138 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002139 else if (longlongflag) {
2140 /* longlongflag should only ever be nonzero on machines with
2141 HAVE_LONG_LONG defined */
2142#ifdef HAVE_LONG_LONG
2143 char *f = PY_FORMAT_LONG_LONG;
2144 while (*f)
2145 *fmt++ = *f++;
2146#else
2147 /* we shouldn't ever get here */
2148 assert(0);
2149 *fmt++ = 'l';
2150#endif
2151 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002152 else if (size_tflag) {
2153 char *f = PY_FORMAT_SIZE_T;
2154 while (*f)
2155 *fmt++ = *f++;
2156 }
2157 *fmt++ = c;
2158 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002159}
2160
Victor Stinner96865452011-03-01 23:44:09 +00002161/* helper for PyUnicode_FromFormatV() */
2162
2163static const char*
2164parse_format_flags(const char *f,
2165 int *p_width, int *p_precision,
2166 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2167{
2168 int width, precision, longflag, longlongflag, size_tflag;
2169
2170 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2171 f++;
2172 width = 0;
2173 while (Py_ISDIGIT((unsigned)*f))
2174 width = (width*10) + *f++ - '0';
2175 precision = 0;
2176 if (*f == '.') {
2177 f++;
2178 while (Py_ISDIGIT((unsigned)*f))
2179 precision = (precision*10) + *f++ - '0';
2180 if (*f == '%') {
2181 /* "%.3%s" => f points to "3" */
2182 f--;
2183 }
2184 }
2185 if (*f == '\0') {
2186 /* bogus format "%.1" => go backward, f points to "1" */
2187 f--;
2188 }
2189 if (p_width != NULL)
2190 *p_width = width;
2191 if (p_precision != NULL)
2192 *p_precision = precision;
2193
2194 /* Handle %ld, %lu, %lld and %llu. */
2195 longflag = 0;
2196 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002197 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002198
2199 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002200 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002201 longflag = 1;
2202 ++f;
2203 }
2204#ifdef HAVE_LONG_LONG
2205 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002206 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002207 longlongflag = 1;
2208 f += 2;
2209 }
2210#endif
2211 }
2212 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002213 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002214 size_tflag = 1;
2215 ++f;
2216 }
2217 if (p_longflag != NULL)
2218 *p_longflag = longflag;
2219 if (p_longlongflag != NULL)
2220 *p_longlongflag = longlongflag;
2221 if (p_size_tflag != NULL)
2222 *p_size_tflag = size_tflag;
2223 return f;
2224}
2225
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002226/* maximum number of characters required for output of %ld. 21 characters
2227 allows for 64-bit integers (in decimal) and an optional sign. */
2228#define MAX_LONG_CHARS 21
2229/* maximum number of characters required for output of %lld.
2230 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2231 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2232#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2233
Walter Dörwaldd2034312007-05-18 16:29:38 +00002234PyObject *
2235PyUnicode_FromFormatV(const char *format, va_list vargs)
2236{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002237 va_list count;
2238 Py_ssize_t callcount = 0;
2239 PyObject **callresults = NULL;
2240 PyObject **callresult = NULL;
2241 Py_ssize_t n = 0;
2242 int width = 0;
2243 int precision = 0;
2244 int zeropad;
2245 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002246 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002247 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002248 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002249 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2250 Py_UCS4 argmaxchar;
2251 Py_ssize_t numbersize = 0;
2252 char *numberresults = NULL;
2253 char *numberresult = NULL;
2254 Py_ssize_t i;
2255 int kind;
2256 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002257
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002258 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002259 /* step 1: count the number of %S/%R/%A/%s format specifications
2260 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2261 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002262 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002263 * also estimate a upper bound for all the number formats in the string,
2264 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002266 for (f = format; *f; f++) {
2267 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002268 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002269 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2270 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2271 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2272 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002275#ifdef HAVE_LONG_LONG
2276 if (longlongflag) {
2277 if (width < MAX_LONG_LONG_CHARS)
2278 width = MAX_LONG_LONG_CHARS;
2279 }
2280 else
2281#endif
2282 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2283 including sign. Decimal takes the most space. This
2284 isn't enough for octal. If a width is specified we
2285 need more (which we allocate later). */
2286 if (width < MAX_LONG_CHARS)
2287 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002288
2289 /* account for the size + '\0' to separate numbers
2290 inside of the numberresults buffer */
2291 numbersize += (width + 1);
2292 }
2293 }
2294 else if ((unsigned char)*f > 127) {
2295 PyErr_Format(PyExc_ValueError,
2296 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2297 "string, got a non-ASCII byte: 0x%02x",
2298 (unsigned char)*f);
2299 return NULL;
2300 }
2301 }
2302 /* step 2: allocate memory for the results of
2303 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2304 if (callcount) {
2305 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2306 if (!callresults) {
2307 PyErr_NoMemory();
2308 return NULL;
2309 }
2310 callresult = callresults;
2311 }
2312 /* step 2.5: allocate memory for the results of formating numbers */
2313 if (numbersize) {
2314 numberresults = PyObject_Malloc(numbersize);
2315 if (!numberresults) {
2316 PyErr_NoMemory();
2317 goto fail;
2318 }
2319 numberresult = numberresults;
2320 }
2321
2322 /* step 3: format numbers and figure out how large a buffer we need */
2323 for (f = format; *f; f++) {
2324 if (*f == '%') {
2325 const char* p;
2326 int longflag;
2327 int longlongflag;
2328 int size_tflag;
2329 int numprinted;
2330
2331 p = f;
2332 zeropad = (f[1] == '0');
2333 f = parse_format_flags(f, &width, &precision,
2334 &longflag, &longlongflag, &size_tflag);
2335 switch (*f) {
2336 case 'c':
2337 {
2338 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002339 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002340 n++;
2341 break;
2342 }
2343 case '%':
2344 n++;
2345 break;
2346 case 'i':
2347 case 'd':
2348 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2349 width, precision, *f);
2350 if (longflag)
2351 numprinted = sprintf(numberresult, fmt,
2352 va_arg(count, long));
2353#ifdef HAVE_LONG_LONG
2354 else if (longlongflag)
2355 numprinted = sprintf(numberresult, fmt,
2356 va_arg(count, PY_LONG_LONG));
2357#endif
2358 else if (size_tflag)
2359 numprinted = sprintf(numberresult, fmt,
2360 va_arg(count, Py_ssize_t));
2361 else
2362 numprinted = sprintf(numberresult, fmt,
2363 va_arg(count, int));
2364 n += numprinted;
2365 /* advance by +1 to skip over the '\0' */
2366 numberresult += (numprinted + 1);
2367 assert(*(numberresult - 1) == '\0');
2368 assert(*(numberresult - 2) != '\0');
2369 assert(numprinted >= 0);
2370 assert(numberresult <= numberresults + numbersize);
2371 break;
2372 case 'u':
2373 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2374 width, precision, 'u');
2375 if (longflag)
2376 numprinted = sprintf(numberresult, fmt,
2377 va_arg(count, unsigned long));
2378#ifdef HAVE_LONG_LONG
2379 else if (longlongflag)
2380 numprinted = sprintf(numberresult, fmt,
2381 va_arg(count, unsigned PY_LONG_LONG));
2382#endif
2383 else if (size_tflag)
2384 numprinted = sprintf(numberresult, fmt,
2385 va_arg(count, size_t));
2386 else
2387 numprinted = sprintf(numberresult, fmt,
2388 va_arg(count, unsigned int));
2389 n += numprinted;
2390 numberresult += (numprinted + 1);
2391 assert(*(numberresult - 1) == '\0');
2392 assert(*(numberresult - 2) != '\0');
2393 assert(numprinted >= 0);
2394 assert(numberresult <= numberresults + numbersize);
2395 break;
2396 case 'x':
2397 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2398 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2399 n += numprinted;
2400 numberresult += (numprinted + 1);
2401 assert(*(numberresult - 1) == '\0');
2402 assert(*(numberresult - 2) != '\0');
2403 assert(numprinted >= 0);
2404 assert(numberresult <= numberresults + numbersize);
2405 break;
2406 case 'p':
2407 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2408 /* %p is ill-defined: ensure leading 0x. */
2409 if (numberresult[1] == 'X')
2410 numberresult[1] = 'x';
2411 else if (numberresult[1] != 'x') {
2412 memmove(numberresult + 2, numberresult,
2413 strlen(numberresult) + 1);
2414 numberresult[0] = '0';
2415 numberresult[1] = 'x';
2416 numprinted += 2;
2417 }
2418 n += numprinted;
2419 numberresult += (numprinted + 1);
2420 assert(*(numberresult - 1) == '\0');
2421 assert(*(numberresult - 2) != '\0');
2422 assert(numprinted >= 0);
2423 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 break;
2425 case 's':
2426 {
2427 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002428 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002429 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002430 if (!str)
2431 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432 /* since PyUnicode_DecodeUTF8 returns already flexible
2433 unicode objects, there is no need to call ready on them */
2434 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002435 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002436 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002437 /* Remember the str and switch to the next slot */
2438 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002439 break;
2440 }
2441 case 'U':
2442 {
2443 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002444 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002445 if (PyUnicode_READY(obj) == -1)
2446 goto fail;
2447 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002448 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002450 break;
2451 }
2452 case 'V':
2453 {
2454 PyObject *obj = va_arg(count, PyObject *);
2455 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002456 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002457 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002458 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002459 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002460 if (PyUnicode_READY(obj) == -1)
2461 goto fail;
2462 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002463 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002465 *callresult++ = NULL;
2466 }
2467 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002468 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002469 if (!str_obj)
2470 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002471 if (PyUnicode_READY(str_obj)) {
2472 Py_DECREF(str_obj);
2473 goto fail;
2474 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002476 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002478 *callresult++ = str_obj;
2479 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002480 break;
2481 }
2482 case 'S':
2483 {
2484 PyObject *obj = va_arg(count, PyObject *);
2485 PyObject *str;
2486 assert(obj);
2487 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002488 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002489 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002490 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002491 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002493 /* Remember the str and switch to the next slot */
2494 *callresult++ = str;
2495 break;
2496 }
2497 case 'R':
2498 {
2499 PyObject *obj = va_arg(count, PyObject *);
2500 PyObject *repr;
2501 assert(obj);
2502 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002504 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002506 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002507 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 /* Remember the repr and switch to the next slot */
2509 *callresult++ = repr;
2510 break;
2511 }
2512 case 'A':
2513 {
2514 PyObject *obj = va_arg(count, PyObject *);
2515 PyObject *ascii;
2516 assert(obj);
2517 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002519 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002521 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002523 /* Remember the repr and switch to the next slot */
2524 *callresult++ = ascii;
2525 break;
2526 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002527 default:
2528 /* if we stumble upon an unknown
2529 formatting code, copy the rest of
2530 the format string to the output
2531 string. (we cannot just skip the
2532 code, since there's no way to know
2533 what's in the argument list) */
2534 n += strlen(p);
2535 goto expand;
2536 }
2537 } else
2538 n++;
2539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002540 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002543 we don't have to resize the string.
2544 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002545 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002546 if (!string)
2547 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002548 kind = PyUnicode_KIND(string);
2549 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002550 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002554 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002555 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002556
2557 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002558 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2559 /* checking for == because the last argument could be a empty
2560 string, which causes i to point to end, the assert at the end of
2561 the loop */
2562 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002563
Benjamin Peterson14339b62009-01-31 16:36:08 +00002564 switch (*f) {
2565 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002566 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002567 const int ordinal = va_arg(vargs, int);
2568 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002570 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002571 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002572 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002573 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002574 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002575 case 'p':
2576 /* unused, since we already have the result */
2577 if (*f == 'p')
2578 (void) va_arg(vargs, void *);
2579 else
2580 (void) va_arg(vargs, int);
2581 /* extract the result from numberresults and append. */
2582 for (; *numberresult; ++i, ++numberresult)
2583 PyUnicode_WRITE(kind, data, i, *numberresult);
2584 /* skip over the separating '\0' */
2585 assert(*numberresult == '\0');
2586 numberresult++;
2587 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002588 break;
2589 case 's':
2590 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002591 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002593 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002594 size = PyUnicode_GET_LENGTH(*callresult);
2595 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002596 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002598 /* We're done with the unicode()/repr() => forget it */
2599 Py_DECREF(*callresult);
2600 /* switch to next unicode()/repr() result */
2601 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002602 break;
2603 }
2604 case 'U':
2605 {
2606 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002607 Py_ssize_t size;
2608 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2609 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002610 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002611 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 break;
2613 }
2614 case 'V':
2615 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002618 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002619 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 size = PyUnicode_GET_LENGTH(obj);
2621 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002622 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002624 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002625 size = PyUnicode_GET_LENGTH(*callresult);
2626 assert(PyUnicode_KIND(*callresult) <=
2627 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002628 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002630 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002631 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002632 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 break;
2634 }
2635 case 'S':
2636 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002637 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002638 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002639 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002640 /* unused, since we already have the result */
2641 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002643 copy_characters(string, i, *callresult, 0, size);
2644 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002645 /* We're done with the unicode()/repr() => forget it */
2646 Py_DECREF(*callresult);
2647 /* switch to next unicode()/repr() result */
2648 ++callresult;
2649 break;
2650 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002651 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 break;
2654 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 for (; *p; ++p, ++i)
2656 PyUnicode_WRITE(kind, data, i, *p);
2657 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002658 goto end;
2659 }
Victor Stinner1205f272010-09-11 00:54:47 +00002660 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 else {
2662 assert(i < PyUnicode_GET_LENGTH(string));
2663 PyUnicode_WRITE(kind, data, i++, *f);
2664 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002666 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002667
Benjamin Peterson29060642009-01-31 22:14:21 +00002668 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 if (callresults)
2670 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002671 if (numberresults)
2672 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002673 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002674 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002675 if (callresults) {
2676 PyObject **callresult2 = callresults;
2677 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002678 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002679 ++callresult2;
2680 }
2681 PyObject_Free(callresults);
2682 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002683 if (numberresults)
2684 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002685 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002686}
2687
Walter Dörwaldd2034312007-05-18 16:29:38 +00002688PyObject *
2689PyUnicode_FromFormat(const char *format, ...)
2690{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002691 PyObject* ret;
2692 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002693
2694#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002695 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002696#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002697 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002698#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 ret = PyUnicode_FromFormatV(format, vargs);
2700 va_end(vargs);
2701 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002702}
2703
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704#ifdef HAVE_WCHAR_H
2705
Victor Stinner5593d8a2010-10-02 11:11:27 +00002706/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2707 convert a Unicode object to a wide character string.
2708
Victor Stinnerd88d9832011-09-06 02:00:05 +02002709 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002710 character) required to convert the unicode object. Ignore size argument.
2711
Victor Stinnerd88d9832011-09-06 02:00:05 +02002712 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002713 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002714 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002715static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002716unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002717 wchar_t *w,
2718 Py_ssize_t size)
2719{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002720 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002721 const wchar_t *wstr;
2722
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002723 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002724 if (wstr == NULL)
2725 return -1;
2726
Victor Stinner5593d8a2010-10-02 11:11:27 +00002727 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002728 if (size > res)
2729 size = res + 1;
2730 else
2731 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002733 return res;
2734 }
2735 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002737}
2738
2739Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002740PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002741 wchar_t *w,
2742 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002743{
2744 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002745 PyErr_BadInternalCall();
2746 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002747 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002748 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002749}
2750
Victor Stinner137c34c2010-09-29 10:25:54 +00002751wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002752PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002753 Py_ssize_t *size)
2754{
2755 wchar_t* buffer;
2756 Py_ssize_t buflen;
2757
2758 if (unicode == NULL) {
2759 PyErr_BadInternalCall();
2760 return NULL;
2761 }
2762
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002763 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 if (buflen == -1)
2765 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002766 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002767 PyErr_NoMemory();
2768 return NULL;
2769 }
2770
Victor Stinner137c34c2010-09-29 10:25:54 +00002771 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2772 if (buffer == NULL) {
2773 PyErr_NoMemory();
2774 return NULL;
2775 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002776 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002777 if (buflen == -1)
2778 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002779 if (size != NULL)
2780 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002781 return buffer;
2782}
2783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002784#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002785
Alexander Belopolsky40018472011-02-26 01:02:56 +00002786PyObject *
2787PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002790 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002791 PyErr_SetString(PyExc_ValueError,
2792 "chr() arg not in range(0x110000)");
2793 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002794 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002796 if (ordinal < 256)
2797 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002799 v = PyUnicode_New(1, ordinal);
2800 if (v == NULL)
2801 return NULL;
2802 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002803 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002804 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002805}
2806
Alexander Belopolsky40018472011-02-26 01:02:56 +00002807PyObject *
2808PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002810 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002811 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002812 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002813 if (PyUnicode_READY(obj))
2814 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002815 Py_INCREF(obj);
2816 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002817 }
2818 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002819 /* For a Unicode subtype that's not a Unicode object,
2820 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002821 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002822 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002823 PyErr_Format(PyExc_TypeError,
2824 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002825 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002826 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002827}
2828
Alexander Belopolsky40018472011-02-26 01:02:56 +00002829PyObject *
2830PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002831 const char *encoding,
2832 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002833{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002834 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002835 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002836
Guido van Rossumd57fd912000-03-10 22:53:23 +00002837 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002838 PyErr_BadInternalCall();
2839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002840 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002841
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002842 /* Decoding bytes objects is the most common case and should be fast */
2843 if (PyBytes_Check(obj)) {
2844 if (PyBytes_GET_SIZE(obj) == 0) {
2845 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002846 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002847 }
2848 else {
2849 v = PyUnicode_Decode(
2850 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2851 encoding, errors);
2852 }
2853 return v;
2854 }
2855
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002856 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 PyErr_SetString(PyExc_TypeError,
2858 "decoding str is not supported");
2859 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002860 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002861
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002862 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2863 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2864 PyErr_Format(PyExc_TypeError,
2865 "coercing to str: need bytes, bytearray "
2866 "or buffer-like object, %.80s found",
2867 Py_TYPE(obj)->tp_name);
2868 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002869 }
Tim Petersced69f82003-09-16 20:30:58 +00002870
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002871 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002872 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002873 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002874 }
Tim Petersced69f82003-09-16 20:30:58 +00002875 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002876 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002877
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002878 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002879 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002880}
2881
Victor Stinner600d3be2010-06-10 12:00:55 +00002882/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002883 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2884 1 on success. */
2885static int
2886normalize_encoding(const char *encoding,
2887 char *lower,
2888 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002889{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002890 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002891 char *l;
2892 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002893
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002894 if (encoding == NULL) {
2895 strcpy(lower, "utf-8");
2896 return 1;
2897 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002898 e = encoding;
2899 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002900 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002901 while (*e) {
2902 if (l == l_end)
2903 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002904 if (Py_ISUPPER(*e)) {
2905 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002906 }
2907 else if (*e == '_') {
2908 *l++ = '-';
2909 e++;
2910 }
2911 else {
2912 *l++ = *e++;
2913 }
2914 }
2915 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002916 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002917}
2918
Alexander Belopolsky40018472011-02-26 01:02:56 +00002919PyObject *
2920PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002921 Py_ssize_t size,
2922 const char *encoding,
2923 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002924{
2925 PyObject *buffer = NULL, *unicode;
2926 Py_buffer info;
2927 char lower[11]; /* Enough for any encoding shortcut */
2928
Fred Drakee4315f52000-05-09 19:53:39 +00002929 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002930 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002931 if ((strcmp(lower, "utf-8") == 0) ||
2932 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002933 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002934 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002935 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002936 (strcmp(lower, "iso-8859-1") == 0))
2937 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002938#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002939 else if (strcmp(lower, "mbcs") == 0)
2940 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002941#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002942 else if (strcmp(lower, "ascii") == 0)
2943 return PyUnicode_DecodeASCII(s, size, errors);
2944 else if (strcmp(lower, "utf-16") == 0)
2945 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2946 else if (strcmp(lower, "utf-32") == 0)
2947 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2948 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002949
2950 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002951 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002952 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002953 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002954 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002955 if (buffer == NULL)
2956 goto onError;
2957 unicode = PyCodec_Decode(buffer, encoding, errors);
2958 if (unicode == NULL)
2959 goto onError;
2960 if (!PyUnicode_Check(unicode)) {
2961 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002962 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002963 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002964 Py_DECREF(unicode);
2965 goto onError;
2966 }
2967 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002968 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002969
Benjamin Peterson29060642009-01-31 22:14:21 +00002970 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002971 Py_XDECREF(buffer);
2972 return NULL;
2973}
2974
Alexander Belopolsky40018472011-02-26 01:02:56 +00002975PyObject *
2976PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002977 const char *encoding,
2978 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002979{
2980 PyObject *v;
2981
2982 if (!PyUnicode_Check(unicode)) {
2983 PyErr_BadArgument();
2984 goto onError;
2985 }
2986
2987 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002988 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002989
2990 /* Decode via the codec registry */
2991 v = PyCodec_Decode(unicode, encoding, errors);
2992 if (v == NULL)
2993 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002994 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002995
Benjamin Peterson29060642009-01-31 22:14:21 +00002996 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002997 return NULL;
2998}
2999
Alexander Belopolsky40018472011-02-26 01:02:56 +00003000PyObject *
3001PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003002 const char *encoding,
3003 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003004{
3005 PyObject *v;
3006
3007 if (!PyUnicode_Check(unicode)) {
3008 PyErr_BadArgument();
3009 goto onError;
3010 }
3011
3012 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003013 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003014
3015 /* Decode via the codec registry */
3016 v = PyCodec_Decode(unicode, encoding, errors);
3017 if (v == NULL)
3018 goto onError;
3019 if (!PyUnicode_Check(v)) {
3020 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003021 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003022 Py_TYPE(v)->tp_name);
3023 Py_DECREF(v);
3024 goto onError;
3025 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003026 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003027
Benjamin Peterson29060642009-01-31 22:14:21 +00003028 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003029 return NULL;
3030}
3031
Alexander Belopolsky40018472011-02-26 01:02:56 +00003032PyObject *
3033PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003034 Py_ssize_t size,
3035 const char *encoding,
3036 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037{
3038 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003039
Guido van Rossumd57fd912000-03-10 22:53:23 +00003040 unicode = PyUnicode_FromUnicode(s, size);
3041 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3044 Py_DECREF(unicode);
3045 return v;
3046}
3047
Alexander Belopolsky40018472011-02-26 01:02:56 +00003048PyObject *
3049PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003050 const char *encoding,
3051 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003052{
3053 PyObject *v;
3054
3055 if (!PyUnicode_Check(unicode)) {
3056 PyErr_BadArgument();
3057 goto onError;
3058 }
3059
3060 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003061 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003062
3063 /* Encode via the codec registry */
3064 v = PyCodec_Encode(unicode, encoding, errors);
3065 if (v == NULL)
3066 goto onError;
3067 return v;
3068
Benjamin Peterson29060642009-01-31 22:14:21 +00003069 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003070 return NULL;
3071}
3072
Victor Stinnerad158722010-10-27 00:25:46 +00003073PyObject *
3074PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003075{
Victor Stinner99b95382011-07-04 14:23:54 +02003076#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003077 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003078#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003079 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003080#else
Victor Stinner793b5312011-04-27 00:24:21 +02003081 PyInterpreterState *interp = PyThreadState_GET()->interp;
3082 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3083 cannot use it to encode and decode filenames before it is loaded. Load
3084 the Python codec requires to encode at least its own filename. Use the C
3085 version of the locale codec until the codec registry is initialized and
3086 the Python codec is loaded.
3087
3088 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3089 cannot only rely on it: check also interp->fscodec_initialized for
3090 subinterpreters. */
3091 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003092 return PyUnicode_AsEncodedString(unicode,
3093 Py_FileSystemDefaultEncoding,
3094 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003095 }
3096 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003097 /* locale encoding with surrogateescape */
3098 wchar_t *wchar;
3099 char *bytes;
3100 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003101 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003102
3103 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3104 if (wchar == NULL)
3105 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003106 bytes = _Py_wchar2char(wchar, &error_pos);
3107 if (bytes == NULL) {
3108 if (error_pos != (size_t)-1) {
3109 char *errmsg = strerror(errno);
3110 PyObject *exc = NULL;
3111 if (errmsg == NULL)
3112 errmsg = "Py_wchar2char() failed";
3113 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003114 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003115 error_pos, error_pos+1,
3116 errmsg);
3117 Py_XDECREF(exc);
3118 }
3119 else
3120 PyErr_NoMemory();
3121 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003122 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003123 }
3124 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003125
3126 bytes_obj = PyBytes_FromString(bytes);
3127 PyMem_Free(bytes);
3128 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003129 }
Victor Stinnerad158722010-10-27 00:25:46 +00003130#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003131}
3132
Alexander Belopolsky40018472011-02-26 01:02:56 +00003133PyObject *
3134PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003135 const char *encoding,
3136 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003137{
3138 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003139 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003140
Guido van Rossumd57fd912000-03-10 22:53:23 +00003141 if (!PyUnicode_Check(unicode)) {
3142 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003143 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003144 }
Fred Drakee4315f52000-05-09 19:53:39 +00003145
Fred Drakee4315f52000-05-09 19:53:39 +00003146 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003147 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003148 if ((strcmp(lower, "utf-8") == 0) ||
3149 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003150 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003151 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003152 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003153 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003154 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003155 }
Victor Stinner37296e82010-06-10 13:36:23 +00003156 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003157 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003158 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003159 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003160#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003161 else if (strcmp(lower, "mbcs") == 0)
3162 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003163#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003164 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003165 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003166 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003167
3168 /* Encode via the codec registry */
3169 v = PyCodec_Encode(unicode, encoding, errors);
3170 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003171 return NULL;
3172
3173 /* The normal path */
3174 if (PyBytes_Check(v))
3175 return v;
3176
3177 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003178 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003179 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003180 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003181
3182 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3183 "encoder %s returned bytearray instead of bytes",
3184 encoding);
3185 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003186 Py_DECREF(v);
3187 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003188 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003189
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003190 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3191 Py_DECREF(v);
3192 return b;
3193 }
3194
3195 PyErr_Format(PyExc_TypeError,
3196 "encoder did not return a bytes object (type=%.400s)",
3197 Py_TYPE(v)->tp_name);
3198 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003199 return NULL;
3200}
3201
Alexander Belopolsky40018472011-02-26 01:02:56 +00003202PyObject *
3203PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003204 const char *encoding,
3205 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003206{
3207 PyObject *v;
3208
3209 if (!PyUnicode_Check(unicode)) {
3210 PyErr_BadArgument();
3211 goto onError;
3212 }
3213
3214 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003215 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003216
3217 /* Encode via the codec registry */
3218 v = PyCodec_Encode(unicode, encoding, errors);
3219 if (v == NULL)
3220 goto onError;
3221 if (!PyUnicode_Check(v)) {
3222 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003223 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003224 Py_TYPE(v)->tp_name);
3225 Py_DECREF(v);
3226 goto onError;
3227 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003228 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003229
Benjamin Peterson29060642009-01-31 22:14:21 +00003230 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003231 return NULL;
3232}
3233
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003234PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003235PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003236 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003237 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3238}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003239
Christian Heimes5894ba72007-11-04 11:43:14 +00003240PyObject*
3241PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3242{
Victor Stinner99b95382011-07-04 14:23:54 +02003243#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003244 return PyUnicode_DecodeMBCS(s, size, NULL);
3245#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003246 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003247#else
Victor Stinner793b5312011-04-27 00:24:21 +02003248 PyInterpreterState *interp = PyThreadState_GET()->interp;
3249 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3250 cannot use it to encode and decode filenames before it is loaded. Load
3251 the Python codec requires to encode at least its own filename. Use the C
3252 version of the locale codec until the codec registry is initialized and
3253 the Python codec is loaded.
3254
3255 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3256 cannot only rely on it: check also interp->fscodec_initialized for
3257 subinterpreters. */
3258 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003259 return PyUnicode_Decode(s, size,
3260 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003261 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003262 }
3263 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003264 /* locale encoding with surrogateescape */
3265 wchar_t *wchar;
3266 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003267 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003268
3269 if (s[size] != '\0' || size != strlen(s)) {
3270 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3271 return NULL;
3272 }
3273
Victor Stinner168e1172010-10-16 23:16:16 +00003274 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003275 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003276 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003277
Victor Stinner168e1172010-10-16 23:16:16 +00003278 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003279 PyMem_Free(wchar);
3280 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003281 }
Victor Stinnerad158722010-10-27 00:25:46 +00003282#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003283}
3284
Martin v. Löwis011e8422009-05-05 04:43:17 +00003285
3286int
3287PyUnicode_FSConverter(PyObject* arg, void* addr)
3288{
3289 PyObject *output = NULL;
3290 Py_ssize_t size;
3291 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003292 if (arg == NULL) {
3293 Py_DECREF(*(PyObject**)addr);
3294 return 1;
3295 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003296 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003297 output = arg;
3298 Py_INCREF(output);
3299 }
3300 else {
3301 arg = PyUnicode_FromObject(arg);
3302 if (!arg)
3303 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003304 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003305 Py_DECREF(arg);
3306 if (!output)
3307 return 0;
3308 if (!PyBytes_Check(output)) {
3309 Py_DECREF(output);
3310 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3311 return 0;
3312 }
3313 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003314 size = PyBytes_GET_SIZE(output);
3315 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003316 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003317 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003318 Py_DECREF(output);
3319 return 0;
3320 }
3321 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003322 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003323}
3324
3325
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003326int
3327PyUnicode_FSDecoder(PyObject* arg, void* addr)
3328{
3329 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003330 if (arg == NULL) {
3331 Py_DECREF(*(PyObject**)addr);
3332 return 1;
3333 }
3334 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003335 if (PyUnicode_READY(arg))
3336 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003337 output = arg;
3338 Py_INCREF(output);
3339 }
3340 else {
3341 arg = PyBytes_FromObject(arg);
3342 if (!arg)
3343 return 0;
3344 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3345 PyBytes_GET_SIZE(arg));
3346 Py_DECREF(arg);
3347 if (!output)
3348 return 0;
3349 if (!PyUnicode_Check(output)) {
3350 Py_DECREF(output);
3351 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3352 return 0;
3353 }
3354 }
Victor Stinner065836e2011-10-27 01:56:33 +02003355 if (PyUnicode_READY(output) < 0) {
3356 Py_DECREF(output);
3357 return 0;
3358 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003359 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003360 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003361 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3362 Py_DECREF(output);
3363 return 0;
3364 }
3365 *(PyObject**)addr = output;
3366 return Py_CLEANUP_SUPPORTED;
3367}
3368
3369
Martin v. Löwis5b222132007-06-10 09:51:05 +00003370char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003371PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003372{
Christian Heimesf3863112007-11-22 07:46:41 +00003373 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003374
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003375 if (!PyUnicode_Check(unicode)) {
3376 PyErr_BadArgument();
3377 return NULL;
3378 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003379 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003380 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003381
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003382 if (PyUnicode_UTF8(unicode) == NULL) {
3383 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003384 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3385 if (bytes == NULL)
3386 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003387 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3388 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003389 Py_DECREF(bytes);
3390 return NULL;
3391 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003392 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3393 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3394 PyBytes_AS_STRING(bytes),
3395 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003396 Py_DECREF(bytes);
3397 }
3398
3399 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003400 *psize = PyUnicode_UTF8_LENGTH(unicode);
3401 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003402}
3403
3404char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003405PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003406{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003407 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3408}
3409
3410#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003411static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003412#endif
3413
3414
3415Py_UNICODE *
3416PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3417{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003418 const unsigned char *one_byte;
3419#if SIZEOF_WCHAR_T == 4
3420 const Py_UCS2 *two_bytes;
3421#else
3422 const Py_UCS4 *four_bytes;
3423 const Py_UCS4 *ucs4_end;
3424 Py_ssize_t num_surrogates;
3425#endif
3426 wchar_t *w;
3427 wchar_t *wchar_end;
3428
3429 if (!PyUnicode_Check(unicode)) {
3430 PyErr_BadArgument();
3431 return NULL;
3432 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003433 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003434 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003435 assert(_PyUnicode_KIND(unicode) != 0);
3436 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437
3438#ifdef Py_DEBUG
3439 ++unicode_as_unicode_calls;
3440#endif
3441
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003443#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003444 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3445 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446 num_surrogates = 0;
3447
3448 for (; four_bytes < ucs4_end; ++four_bytes) {
3449 if (*four_bytes > 0xFFFF)
3450 ++num_surrogates;
3451 }
3452
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003453 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3454 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3455 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003456 PyErr_NoMemory();
3457 return NULL;
3458 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003459 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003460
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003461 w = _PyUnicode_WSTR(unicode);
3462 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3463 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003464 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3465 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003466 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003467 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003468 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3469 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003470 }
3471 else
3472 *w = *four_bytes;
3473
3474 if (w > wchar_end) {
3475 assert(0 && "Miscalculated string end");
3476 }
3477 }
3478 *w = 0;
3479#else
3480 /* sizeof(wchar_t) == 4 */
3481 Py_FatalError("Impossible unicode object state, wstr and str "
3482 "should share memory already.");
3483 return NULL;
3484#endif
3485 }
3486 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003487 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3488 (_PyUnicode_LENGTH(unicode) + 1));
3489 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003490 PyErr_NoMemory();
3491 return NULL;
3492 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003493 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3494 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3495 w = _PyUnicode_WSTR(unicode);
3496 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003497
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003498 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3499 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003500 for (; w < wchar_end; ++one_byte, ++w)
3501 *w = *one_byte;
3502 /* null-terminate the wstr */
3503 *w = 0;
3504 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003505 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003506#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003507 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003508 for (; w < wchar_end; ++two_bytes, ++w)
3509 *w = *two_bytes;
3510 /* null-terminate the wstr */
3511 *w = 0;
3512#else
3513 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003514 PyObject_FREE(_PyUnicode_WSTR(unicode));
3515 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003516 Py_FatalError("Impossible unicode object state, wstr "
3517 "and str should share memory already.");
3518 return NULL;
3519#endif
3520 }
3521 else {
3522 assert(0 && "This should never happen.");
3523 }
3524 }
3525 }
3526 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003527 *size = PyUnicode_WSTR_LENGTH(unicode);
3528 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003529}
3530
Alexander Belopolsky40018472011-02-26 01:02:56 +00003531Py_UNICODE *
3532PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003533{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003534 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003535}
3536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003537
Alexander Belopolsky40018472011-02-26 01:02:56 +00003538Py_ssize_t
3539PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003540{
3541 if (!PyUnicode_Check(unicode)) {
3542 PyErr_BadArgument();
3543 goto onError;
3544 }
3545 return PyUnicode_GET_SIZE(unicode);
3546
Benjamin Peterson29060642009-01-31 22:14:21 +00003547 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003548 return -1;
3549}
3550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003551Py_ssize_t
3552PyUnicode_GetLength(PyObject *unicode)
3553{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003554 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003555 PyErr_BadArgument();
3556 return -1;
3557 }
3558
3559 return PyUnicode_GET_LENGTH(unicode);
3560}
3561
3562Py_UCS4
3563PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3564{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003565 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3566 PyErr_BadArgument();
3567 return (Py_UCS4)-1;
3568 }
3569 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3570 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003571 return (Py_UCS4)-1;
3572 }
3573 return PyUnicode_READ_CHAR(unicode, index);
3574}
3575
3576int
3577PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3578{
3579 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003580 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003581 return -1;
3582 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003583 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3584 PyErr_SetString(PyExc_IndexError, "string index out of range");
3585 return -1;
3586 }
3587 if (_PyUnicode_Dirty(unicode))
3588 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003589 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3590 index, ch);
3591 return 0;
3592}
3593
Alexander Belopolsky40018472011-02-26 01:02:56 +00003594const char *
3595PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003596{
Victor Stinner42cb4622010-09-01 19:39:01 +00003597 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003598}
3599
Victor Stinner554f3f02010-06-16 23:33:54 +00003600/* create or adjust a UnicodeDecodeError */
3601static void
3602make_decode_exception(PyObject **exceptionObject,
3603 const char *encoding,
3604 const char *input, Py_ssize_t length,
3605 Py_ssize_t startpos, Py_ssize_t endpos,
3606 const char *reason)
3607{
3608 if (*exceptionObject == NULL) {
3609 *exceptionObject = PyUnicodeDecodeError_Create(
3610 encoding, input, length, startpos, endpos, reason);
3611 }
3612 else {
3613 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3614 goto onError;
3615 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3616 goto onError;
3617 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3618 goto onError;
3619 }
3620 return;
3621
3622onError:
3623 Py_DECREF(*exceptionObject);
3624 *exceptionObject = NULL;
3625}
3626
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003627/* error handling callback helper:
3628 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003629 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003630 and adjust various state variables.
3631 return 0 on success, -1 on error
3632*/
3633
Alexander Belopolsky40018472011-02-26 01:02:56 +00003634static int
3635unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003636 const char *encoding, const char *reason,
3637 const char **input, const char **inend, Py_ssize_t *startinpos,
3638 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003639 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003640{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003641 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642
3643 PyObject *restuple = NULL;
3644 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003645 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003646 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003647 Py_ssize_t requiredsize;
3648 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003649 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650 int res = -1;
3651
Victor Stinner596a6c42011-11-09 00:02:18 +01003652 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3653 outsize = PyUnicode_GET_LENGTH(*output);
3654 else
3655 outsize = _PyUnicode_WSTR_LENGTH(*output);
3656
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003657 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003658 *errorHandler = PyCodec_LookupError(errors);
3659 if (*errorHandler == NULL)
3660 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003661 }
3662
Victor Stinner554f3f02010-06-16 23:33:54 +00003663 make_decode_exception(exceptionObject,
3664 encoding,
3665 *input, *inend - *input,
3666 *startinpos, *endinpos,
3667 reason);
3668 if (*exceptionObject == NULL)
3669 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003670
3671 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3672 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003673 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003674 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003675 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003676 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003677 }
3678 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003679 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003680 if (PyUnicode_READY(repunicode) < 0)
3681 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003682
3683 /* Copy back the bytes variables, which might have been modified by the
3684 callback */
3685 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3686 if (!inputobj)
3687 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003688 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003689 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003690 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003691 *input = PyBytes_AS_STRING(inputobj);
3692 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003693 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003694 /* we can DECREF safely, as the exception has another reference,
3695 so the object won't go away. */
3696 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003697
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003698 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003699 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003700 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003701 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3702 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003703 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003704
Victor Stinner596a6c42011-11-09 00:02:18 +01003705 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3706 /* need more space? (at least enough for what we
3707 have+the replacement+the rest of the string (starting
3708 at the new input position), so we won't have to check space
3709 when there are no errors in the rest of the string) */
3710 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3711 requiredsize = *outpos + replen + insize-newpos;
3712 if (requiredsize > outsize) {
3713 if (requiredsize<2*outsize)
3714 requiredsize = 2*outsize;
3715 if (unicode_resize(output, requiredsize) < 0)
3716 goto onError;
3717 }
3718 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003719 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003720 copy_characters(*output, *outpos, repunicode, 0, replen);
3721 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003722 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003723 else {
3724 wchar_t *repwstr;
3725 Py_ssize_t repwlen;
3726 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3727 if (repwstr == NULL)
3728 goto onError;
3729 /* need more space? (at least enough for what we
3730 have+the replacement+the rest of the string (starting
3731 at the new input position), so we won't have to check space
3732 when there are no errors in the rest of the string) */
3733 requiredsize = *outpos + repwlen + insize-newpos;
3734 if (requiredsize > outsize) {
3735 if (requiredsize < 2*outsize)
3736 requiredsize = 2*outsize;
3737 if (unicode_resize(output, requiredsize) < 0)
3738 goto onError;
3739 }
3740 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3741 *outpos += repwlen;
3742 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003743 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003744 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003745
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003746 /* we made it! */
3747 res = 0;
3748
Benjamin Peterson29060642009-01-31 22:14:21 +00003749 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003750 Py_XDECREF(restuple);
3751 return res;
3752}
3753
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003754/* --- UTF-7 Codec -------------------------------------------------------- */
3755
Antoine Pitrou244651a2009-05-04 18:56:13 +00003756/* See RFC2152 for details. We encode conservatively and decode liberally. */
3757
3758/* Three simple macros defining base-64. */
3759
3760/* Is c a base-64 character? */
3761
3762#define IS_BASE64(c) \
3763 (((c) >= 'A' && (c) <= 'Z') || \
3764 ((c) >= 'a' && (c) <= 'z') || \
3765 ((c) >= '0' && (c) <= '9') || \
3766 (c) == '+' || (c) == '/')
3767
3768/* given that c is a base-64 character, what is its base-64 value? */
3769
3770#define FROM_BASE64(c) \
3771 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3772 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3773 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3774 (c) == '+' ? 62 : 63)
3775
3776/* What is the base-64 character of the bottom 6 bits of n? */
3777
3778#define TO_BASE64(n) \
3779 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3780
3781/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3782 * decoded as itself. We are permissive on decoding; the only ASCII
3783 * byte not decoding to itself is the + which begins a base64
3784 * string. */
3785
3786#define DECODE_DIRECT(c) \
3787 ((c) <= 127 && (c) != '+')
3788
3789/* The UTF-7 encoder treats ASCII characters differently according to
3790 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3791 * the above). See RFC2152. This array identifies these different
3792 * sets:
3793 * 0 : "Set D"
3794 * alphanumeric and '(),-./:?
3795 * 1 : "Set O"
3796 * !"#$%&*;<=>@[]^_`{|}
3797 * 2 : "whitespace"
3798 * ht nl cr sp
3799 * 3 : special (must be base64 encoded)
3800 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3801 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003802
Tim Petersced69f82003-09-16 20:30:58 +00003803static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003804char utf7_category[128] = {
3805/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3806 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3807/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3808 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3809/* sp ! " # $ % & ' ( ) * + , - . / */
3810 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3811/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3812 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3813/* @ A B C D E F G H I J K L M N O */
3814 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3815/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3816 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3817/* ` a b c d e f g h i j k l m n o */
3818 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3819/* p q r s t u v w x y z { | } ~ del */
3820 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003821};
3822
Antoine Pitrou244651a2009-05-04 18:56:13 +00003823/* ENCODE_DIRECT: this character should be encoded as itself. The
3824 * answer depends on whether we are encoding set O as itself, and also
3825 * on whether we are encoding whitespace as itself. RFC2152 makes it
3826 * clear that the answers to these questions vary between
3827 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003828
Antoine Pitrou244651a2009-05-04 18:56:13 +00003829#define ENCODE_DIRECT(c, directO, directWS) \
3830 ((c) < 128 && (c) > 0 && \
3831 ((utf7_category[(c)] == 0) || \
3832 (directWS && (utf7_category[(c)] == 2)) || \
3833 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003834
Alexander Belopolsky40018472011-02-26 01:02:56 +00003835PyObject *
3836PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003837 Py_ssize_t size,
3838 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003839{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003840 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3841}
3842
Antoine Pitrou244651a2009-05-04 18:56:13 +00003843/* The decoder. The only state we preserve is our read position,
3844 * i.e. how many characters we have consumed. So if we end in the
3845 * middle of a shift sequence we have to back off the read position
3846 * and the output to the beginning of the sequence, otherwise we lose
3847 * all the shift state (seen bits, number of bits seen, high
3848 * surrogate). */
3849
Alexander Belopolsky40018472011-02-26 01:02:56 +00003850PyObject *
3851PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003852 Py_ssize_t size,
3853 const char *errors,
3854 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003855{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003856 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003857 Py_ssize_t startinpos;
3858 Py_ssize_t endinpos;
3859 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003860 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003861 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 const char *errmsg = "";
3863 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003864 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003865 unsigned int base64bits = 0;
3866 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003867 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003868 PyObject *errorHandler = NULL;
3869 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003870
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003871 /* Start off assuming it's all ASCII. Widen later as necessary. */
3872 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003873 if (!unicode)
3874 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003875 if (size == 0) {
3876 if (consumed)
3877 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003878 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003879 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003880
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003881 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003882 e = s + size;
3883
3884 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003885 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003886 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003887 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003888
Antoine Pitrou244651a2009-05-04 18:56:13 +00003889 if (inShift) { /* in a base-64 section */
3890 if (IS_BASE64(ch)) { /* consume a base-64 character */
3891 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3892 base64bits += 6;
3893 s++;
3894 if (base64bits >= 16) {
3895 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003896 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 base64bits -= 16;
3898 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3899 if (surrogate) {
3900 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01003901 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
3902 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003903 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3904 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003905 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003906 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003907 }
3908 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003909 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3910 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003911 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003912 }
3913 }
Victor Stinner551ac952011-11-29 22:58:13 +01003914 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003915 /* first surrogate */
3916 surrogate = outCh;
3917 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003918 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003919 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3920 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003921 }
3922 }
3923 }
3924 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003925 inShift = 0;
3926 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003927 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003928 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3929 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003930 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003931 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003932 if (base64bits > 0) { /* left-over bits */
3933 if (base64bits >= 6) {
3934 /* We've seen at least one base-64 character */
3935 errmsg = "partial character in shift sequence";
3936 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003937 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938 else {
3939 /* Some bits remain; they should be zero */
3940 if (base64buffer != 0) {
3941 errmsg = "non-zero padding bits in shift sequence";
3942 goto utf7Error;
3943 }
3944 }
3945 }
3946 if (ch != '-') {
3947 /* '-' is absorbed; other terminating
3948 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003949 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3950 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003951 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003952 }
3953 }
3954 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003955 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003956 s++; /* consume '+' */
3957 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003958 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003959 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3960 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003961 }
3962 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003963 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003964 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003965 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003966 }
3967 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003968 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003969 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3970 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003971 s++;
3972 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003973 else {
3974 startinpos = s-starts;
3975 s++;
3976 errmsg = "unexpected special character";
3977 goto utf7Error;
3978 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003979 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003980utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003981 endinpos = s-starts;
3982 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003983 errors, &errorHandler,
3984 "utf7", errmsg,
3985 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003986 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003987 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003988 }
3989
Antoine Pitrou244651a2009-05-04 18:56:13 +00003990 /* end of string */
3991
3992 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3993 /* if we're in an inconsistent state, that's an error */
3994 if (surrogate ||
3995 (base64bits >= 6) ||
3996 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003997 endinpos = size;
3998 if (unicode_decode_call_errorhandler(
3999 errors, &errorHandler,
4000 "utf7", "unterminated shift sequence",
4001 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004002 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004003 goto onError;
4004 if (s < e)
4005 goto restart;
4006 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004007 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004008
4009 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004010 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004011 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004012 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004013 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004014 }
4015 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004016 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004017 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004018 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004019
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004020 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004021 goto onError;
4022
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004023 Py_XDECREF(errorHandler);
4024 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004025 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004026
Benjamin Peterson29060642009-01-31 22:14:21 +00004027 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004028 Py_XDECREF(errorHandler);
4029 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004030 Py_DECREF(unicode);
4031 return NULL;
4032}
4033
4034
Alexander Belopolsky40018472011-02-26 01:02:56 +00004035PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004036_PyUnicode_EncodeUTF7(PyObject *str,
4037 int base64SetO,
4038 int base64WhiteSpace,
4039 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004040{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004041 int kind;
4042 void *data;
4043 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004044 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004045 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004046 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004047 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004048 unsigned int base64bits = 0;
4049 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004050 char * out;
4051 char * start;
4052
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004053 if (PyUnicode_READY(str) < 0)
4054 return NULL;
4055 kind = PyUnicode_KIND(str);
4056 data = PyUnicode_DATA(str);
4057 len = PyUnicode_GET_LENGTH(str);
4058
4059 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004060 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004061
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004062 /* It might be possible to tighten this worst case */
4063 allocated = 8 * len;
4064 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004065 return PyErr_NoMemory();
4066
Antoine Pitrou244651a2009-05-04 18:56:13 +00004067 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004068 if (v == NULL)
4069 return NULL;
4070
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004071 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004072 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004073 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004074
Antoine Pitrou244651a2009-05-04 18:56:13 +00004075 if (inShift) {
4076 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4077 /* shifting out */
4078 if (base64bits) { /* output remaining bits */
4079 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4080 base64buffer = 0;
4081 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004082 }
4083 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004084 /* Characters not in the BASE64 set implicitly unshift the sequence
4085 so no '-' is required, except if the character is itself a '-' */
4086 if (IS_BASE64(ch) || ch == '-') {
4087 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004088 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004089 *out++ = (char) ch;
4090 }
4091 else {
4092 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004093 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004094 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004095 else { /* not in a shift sequence */
4096 if (ch == '+') {
4097 *out++ = '+';
4098 *out++ = '-';
4099 }
4100 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4101 *out++ = (char) ch;
4102 }
4103 else {
4104 *out++ = '+';
4105 inShift = 1;
4106 goto encode_char;
4107 }
4108 }
4109 continue;
4110encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004111 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004112 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004113
Antoine Pitrou244651a2009-05-04 18:56:13 +00004114 /* code first surrogate */
4115 base64bits += 16;
4116 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4117 while (base64bits >= 6) {
4118 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4119 base64bits -= 6;
4120 }
4121 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004122 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004123 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004124 base64bits += 16;
4125 base64buffer = (base64buffer << 16) | ch;
4126 while (base64bits >= 6) {
4127 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4128 base64bits -= 6;
4129 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004130 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004131 if (base64bits)
4132 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4133 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004134 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004135 if (_PyBytes_Resize(&v, out - start) < 0)
4136 return NULL;
4137 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004138}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004139PyObject *
4140PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4141 Py_ssize_t size,
4142 int base64SetO,
4143 int base64WhiteSpace,
4144 const char *errors)
4145{
4146 PyObject *result;
4147 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4148 if (tmp == NULL)
4149 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004150 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004151 base64WhiteSpace, errors);
4152 Py_DECREF(tmp);
4153 return result;
4154}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004155
Antoine Pitrou244651a2009-05-04 18:56:13 +00004156#undef IS_BASE64
4157#undef FROM_BASE64
4158#undef TO_BASE64
4159#undef DECODE_DIRECT
4160#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004161
Guido van Rossumd57fd912000-03-10 22:53:23 +00004162/* --- UTF-8 Codec -------------------------------------------------------- */
4163
Tim Petersced69f82003-09-16 20:30:58 +00004164static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004165char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004166 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4167 illegal prefix. See RFC 3629 for details */
4168 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4169 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004170 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004171 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,
4174 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004175 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4176 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 +00004177 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4178 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004179 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4180 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4181 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4182 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4183 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 +00004184};
4185
Alexander Belopolsky40018472011-02-26 01:02:56 +00004186PyObject *
4187PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004188 Py_ssize_t size,
4189 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004190{
Walter Dörwald69652032004-09-07 20:24:22 +00004191 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4192}
4193
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004194#include "stringlib/ucs1lib.h"
4195#include "stringlib/codecs.h"
4196#include "stringlib/undef.h"
4197
4198#include "stringlib/ucs2lib.h"
4199#include "stringlib/codecs.h"
4200#include "stringlib/undef.h"
4201
4202#include "stringlib/ucs4lib.h"
4203#include "stringlib/codecs.h"
4204#include "stringlib/undef.h"
4205
Antoine Pitrouab868312009-01-10 15:40:25 +00004206/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4207#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4208
4209/* Mask to quickly check whether a C 'long' contains a
4210 non-ASCII, UTF8-encoded char. */
4211#if (SIZEOF_LONG == 8)
4212# define ASCII_CHAR_MASK 0x8080808080808080L
4213#elif (SIZEOF_LONG == 4)
4214# define ASCII_CHAR_MASK 0x80808080L
4215#else
4216# error C 'long' size should be either 4 or 8!
4217#endif
4218
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004219/* Scans a UTF-8 string and returns the maximum character to be expected
4220 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004221
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004222 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004223 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004224 */
4225static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004226utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004227{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004228 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004229 const unsigned char *end = p + string_size;
4230 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004231
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004232 assert(unicode_size != NULL);
4233
4234 /* By having a cascade of independent loops which fallback onto each
4235 other, we minimize the amount of work done in the average loop
4236 iteration, and we also maximize the CPU's ability to predict
4237 branches correctly (because a given condition will have always the
4238 same boolean outcome except perhaps in the last iteration of the
4239 corresponding loop).
4240 In the general case this brings us rather close to decoding
4241 performance pre-PEP 393, despite the two-pass decoding.
4242
4243 Note that the pure ASCII loop is not duplicated once a non-ASCII
4244 character has been encountered. It is actually a pessimization (by
4245 a significant factor) to use this loop on text with many non-ASCII
4246 characters, and it is important to avoid bad performance on valid
4247 utf-8 data (invalid utf-8 being a different can of worms).
4248 */
4249
4250 /* ASCII */
4251 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004252 /* Only check value if it's not a ASCII char... */
4253 if (*p < 0x80) {
4254 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4255 an explanation. */
4256 if (!((size_t) p & LONG_PTR_MASK)) {
4257 /* Help register allocation */
4258 register const unsigned char *_p = p;
4259 while (_p < aligned_end) {
4260 unsigned long value = *(unsigned long *) _p;
4261 if (value & ASCII_CHAR_MASK)
4262 break;
4263 _p += SIZEOF_LONG;
4264 char_count += SIZEOF_LONG;
4265 }
4266 p = _p;
4267 if (p == end)
4268 break;
4269 }
4270 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004271 if (*p < 0x80)
4272 ++char_count;
4273 else
4274 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004275 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004276 *unicode_size = char_count;
4277 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004278
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004279_ucs1loop:
4280 for (; p < end; ++p) {
4281 if (*p < 0xc4)
4282 char_count += ((*p & 0xc0) != 0x80);
4283 else
4284 goto _ucs2loop;
4285 }
4286 *unicode_size = char_count;
4287 return 255;
4288
4289_ucs2loop:
4290 for (; p < end; ++p) {
4291 if (*p < 0xf0)
4292 char_count += ((*p & 0xc0) != 0x80);
4293 else
4294 goto _ucs4loop;
4295 }
4296 *unicode_size = char_count;
4297 return 65535;
4298
4299_ucs4loop:
4300 for (; p < end; ++p) {
4301 char_count += ((*p & 0xc0) != 0x80);
4302 }
4303 *unicode_size = char_count;
4304 return 65537;
4305}
4306
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004307/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004308 in case of errors. Implicit parameters: unicode, kind, data, onError.
4309 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004310*/
Victor Stinner785938e2011-12-11 20:09:03 +01004311#define WRITE_MAYBE_FAIL(index, value) \
4312 do { \
4313 Py_ssize_t pos = index; \
4314 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4315 unicode_resize(&unicode, pos + pos/8) < 0) \
4316 goto onError; \
4317 if (unicode_putchar(&unicode, &pos, value) < 0) \
4318 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004319 } while (0)
4320
Alexander Belopolsky40018472011-02-26 01:02:56 +00004321PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004322decode_utf8_errors(const char *starts,
4323 Py_ssize_t size,
4324 const char *errors,
4325 Py_ssize_t *consumed,
4326 const char *s,
4327 PyObject *unicode,
4328 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004329{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004330 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004331 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004332 Py_ssize_t startinpos;
4333 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004334 const char *e = starts + size;
4335 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004336 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004337 PyObject *errorHandler = NULL;
4338 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004339
Antoine Pitrouab868312009-01-10 15:40:25 +00004340 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004341
4342 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004343 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004344
4345 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004346 /* Fast path for runs of ASCII characters. Given that common UTF-8
4347 input will consist of an overwhelming majority of ASCII
4348 characters, we try to optimize for this case by checking
4349 as many characters as a C 'long' can contain.
4350 First, check if we can do an aligned read, as most CPUs have
4351 a penalty for unaligned reads.
4352 */
4353 if (!((size_t) s & LONG_PTR_MASK)) {
4354 /* Help register allocation */
4355 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004356 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004357 while (_s < aligned_end) {
4358 /* Read a whole long at a time (either 4 or 8 bytes),
4359 and do a fast unrolled copy if it only contains ASCII
4360 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004361 unsigned long value = *(unsigned long *) _s;
4362 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004363 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004364 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4365 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4366 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4367 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004368#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4370 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4371 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4372 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004373#endif
4374 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004375 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004376 }
4377 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004378 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004379 if (s == e)
4380 break;
4381 ch = (unsigned char)*s;
4382 }
4383 }
4384
4385 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004386 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004387 s++;
4388 continue;
4389 }
4390
4391 n = utf8_code_length[ch];
4392
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004393 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 if (consumed)
4395 break;
4396 else {
4397 errmsg = "unexpected end of data";
4398 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004399 endinpos = startinpos+1;
4400 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4401 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 goto utf8Error;
4403 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004404 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004405
4406 switch (n) {
4407
4408 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004409 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004410 startinpos = s-starts;
4411 endinpos = startinpos+1;
4412 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004413
4414 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004415 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004416 startinpos = s-starts;
4417 endinpos = startinpos+1;
4418 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004419
4420 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004421 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004422 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004423 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004424 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004425 goto utf8Error;
4426 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004427 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004428 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004429 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004430 break;
4431
4432 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004433 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4434 will result in surrogates in range d800-dfff. Surrogates are
4435 not valid UTF-8 so they are rejected.
4436 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4437 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004438 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004439 (s[2] & 0xc0) != 0x80 ||
4440 ((unsigned char)s[0] == 0xE0 &&
4441 (unsigned char)s[1] < 0xA0) ||
4442 ((unsigned char)s[0] == 0xED &&
4443 (unsigned char)s[1] > 0x9F)) {
4444 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004445 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004446 endinpos = startinpos + 1;
4447
4448 /* if s[1] first two bits are 1 and 0, then the invalid
4449 continuation byte is s[2], so increment endinpos by 1,
4450 if not, s[1] is invalid and endinpos doesn't need to
4451 be incremented. */
4452 if ((s[1] & 0xC0) == 0x80)
4453 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004454 goto utf8Error;
4455 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004456 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004457 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004458 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004459 break;
4460
4461 case 4:
4462 if ((s[1] & 0xc0) != 0x80 ||
4463 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004464 (s[3] & 0xc0) != 0x80 ||
4465 ((unsigned char)s[0] == 0xF0 &&
4466 (unsigned char)s[1] < 0x90) ||
4467 ((unsigned char)s[0] == 0xF4 &&
4468 (unsigned char)s[1] > 0x8F)) {
4469 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004470 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004471 endinpos = startinpos + 1;
4472 if ((s[1] & 0xC0) == 0x80) {
4473 endinpos++;
4474 if ((s[2] & 0xC0) == 0x80)
4475 endinpos++;
4476 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004477 goto utf8Error;
4478 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004479 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004480 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004481 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004482
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004483 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004484 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004485 }
4486 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004487 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004488
Benjamin Peterson29060642009-01-31 22:14:21 +00004489 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 if (unicode_decode_call_errorhandler(
4491 errors, &errorHandler,
4492 "utf8", errmsg,
4493 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004494 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004496 /* Update data because unicode_decode_call_errorhandler might have
4497 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004498 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004499 }
Walter Dörwald69652032004-09-07 20:24:22 +00004500 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004503 /* Adjust length and ready string when it contained errors and
4504 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004505 if (unicode_resize(&unicode, i) < 0)
4506 goto onError;
4507 unicode_adjust_maxchar(&unicode);
4508 if (unicode == NULL)
4509 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004510
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004511 Py_XDECREF(errorHandler);
4512 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004513 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004514 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004515
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004517 Py_XDECREF(errorHandler);
4518 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004519 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004520 return NULL;
4521}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004522#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004523
Victor Stinner785938e2011-12-11 20:09:03 +01004524PyObject *
4525PyUnicode_DecodeUTF8Stateful(const char *s,
4526 Py_ssize_t size,
4527 const char *errors,
4528 Py_ssize_t *consumed)
4529{
4530 Py_UCS4 maxchar = 0;
4531 Py_ssize_t unicode_size;
4532 int has_errors = 0;
4533 PyObject *unicode;
4534 int kind;
4535 void *data;
4536 const char *starts = s;
4537 const char *e;
4538 Py_ssize_t i;
4539
4540 if (size == 0) {
4541 if (consumed)
4542 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004543 Py_INCREF(unicode_empty);
4544 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004545 }
4546
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004547 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004548
4549 /* When the string is ASCII only, just use memcpy and return.
4550 unicode_size may be != size if there is an incomplete UTF-8
4551 sequence at the end of the ASCII block. */
4552 if (maxchar < 128 && size == unicode_size) {
4553 if (consumed)
4554 *consumed = size;
4555 return unicode_fromascii(s, size);
4556 }
4557
4558 unicode = PyUnicode_New(unicode_size, maxchar);
4559 if (!unicode)
4560 return NULL;
4561 kind = PyUnicode_KIND(unicode);
4562 data = PyUnicode_DATA(unicode);
4563
4564 /* Unpack UTF-8 encoded data */
4565 i = 0;
4566 e = starts + size;
4567 switch (kind) {
4568 case PyUnicode_1BYTE_KIND:
4569 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4570 break;
4571 case PyUnicode_2BYTE_KIND:
4572 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4573 break;
4574 case PyUnicode_4BYTE_KIND:
4575 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4576 break;
4577 }
4578 if (!has_errors) {
4579 /* Ensure the unicode size calculation was correct */
4580 assert(i == unicode_size);
4581 assert(s == e);
4582 if (consumed)
4583 *consumed = size;
4584 return unicode;
4585 }
4586
4587 /* In case of errors, maxchar and size computation might be incorrect;
4588 code below refits and resizes as necessary. */
4589 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4590}
4591
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004592#ifdef __APPLE__
4593
4594/* Simplified UTF-8 decoder using surrogateescape error handler,
4595 used to decode the command line arguments on Mac OS X. */
4596
4597wchar_t*
4598_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4599{
4600 int n;
4601 const char *e;
4602 wchar_t *unicode, *p;
4603
4604 /* Note: size will always be longer than the resulting Unicode
4605 character count */
4606 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4607 PyErr_NoMemory();
4608 return NULL;
4609 }
4610 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4611 if (!unicode)
4612 return NULL;
4613
4614 /* Unpack UTF-8 encoded data */
4615 p = unicode;
4616 e = s + size;
4617 while (s < e) {
4618 Py_UCS4 ch = (unsigned char)*s;
4619
4620 if (ch < 0x80) {
4621 *p++ = (wchar_t)ch;
4622 s++;
4623 continue;
4624 }
4625
4626 n = utf8_code_length[ch];
4627 if (s + n > e) {
4628 goto surrogateescape;
4629 }
4630
4631 switch (n) {
4632 case 0:
4633 case 1:
4634 goto surrogateescape;
4635
4636 case 2:
4637 if ((s[1] & 0xc0) != 0x80)
4638 goto surrogateescape;
4639 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4640 assert ((ch > 0x007F) && (ch <= 0x07FF));
4641 *p++ = (wchar_t)ch;
4642 break;
4643
4644 case 3:
4645 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4646 will result in surrogates in range d800-dfff. Surrogates are
4647 not valid UTF-8 so they are rejected.
4648 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4649 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4650 if ((s[1] & 0xc0) != 0x80 ||
4651 (s[2] & 0xc0) != 0x80 ||
4652 ((unsigned char)s[0] == 0xE0 &&
4653 (unsigned char)s[1] < 0xA0) ||
4654 ((unsigned char)s[0] == 0xED &&
4655 (unsigned char)s[1] > 0x9F)) {
4656
4657 goto surrogateescape;
4658 }
4659 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4660 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004661 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004662 break;
4663
4664 case 4:
4665 if ((s[1] & 0xc0) != 0x80 ||
4666 (s[2] & 0xc0) != 0x80 ||
4667 (s[3] & 0xc0) != 0x80 ||
4668 ((unsigned char)s[0] == 0xF0 &&
4669 (unsigned char)s[1] < 0x90) ||
4670 ((unsigned char)s[0] == 0xF4 &&
4671 (unsigned char)s[1] > 0x8F)) {
4672 goto surrogateescape;
4673 }
4674 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4675 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004676 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004677
4678#if SIZEOF_WCHAR_T == 4
4679 *p++ = (wchar_t)ch;
4680#else
4681 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01004682 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4683 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004684#endif
4685 break;
4686 }
4687 s += n;
4688 continue;
4689
4690 surrogateescape:
4691 *p++ = 0xDC00 + ch;
4692 s++;
4693 }
4694 *p = L'\0';
4695 return unicode;
4696}
4697
4698#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004700/* Primary internal function which creates utf8 encoded bytes objects.
4701
4702 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004703 and allocate exactly as much space needed at the end. Else allocate the
4704 maximum possible needed (4 result bytes per Unicode character), and return
4705 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004706*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004707PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004708_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004709{
Tim Peters602f7402002-04-27 18:03:26 +00004710#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004711
Guido van Rossum98297ee2007-11-06 21:34:58 +00004712 Py_ssize_t i; /* index into s of next input byte */
4713 PyObject *result; /* result string object */
4714 char *p; /* next free byte in output buffer */
4715 Py_ssize_t nallocated; /* number of result bytes allocated */
4716 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004717 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004718 PyObject *errorHandler = NULL;
4719 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004720 int kind;
4721 void *data;
4722 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004723 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004725 if (!PyUnicode_Check(unicode)) {
4726 PyErr_BadArgument();
4727 return NULL;
4728 }
4729
4730 if (PyUnicode_READY(unicode) == -1)
4731 return NULL;
4732
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004733 if (PyUnicode_UTF8(unicode))
4734 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4735 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004736
4737 kind = PyUnicode_KIND(unicode);
4738 data = PyUnicode_DATA(unicode);
4739 size = PyUnicode_GET_LENGTH(unicode);
4740
Tim Peters602f7402002-04-27 18:03:26 +00004741 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004742
Tim Peters602f7402002-04-27 18:03:26 +00004743 if (size <= MAX_SHORT_UNICHARS) {
4744 /* Write into the stack buffer; nallocated can't overflow.
4745 * At the end, we'll allocate exactly as much heap space as it
4746 * turns out we need.
4747 */
4748 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004749 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004750 p = stackbuf;
4751 }
4752 else {
4753 /* Overallocate on the heap, and give the excess back at the end. */
4754 nallocated = size * 4;
4755 if (nallocated / 4 != size) /* overflow! */
4756 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004757 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004758 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004759 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004760 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004761 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004762
Tim Peters602f7402002-04-27 18:03:26 +00004763 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004764 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004765
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004766 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004767 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004768 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004769
Guido van Rossumd57fd912000-03-10 22:53:23 +00004770 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004771 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004772 *p++ = (char)(0xc0 | (ch >> 6));
4773 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner551ac952011-11-29 22:58:13 +01004774 } else if (Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004775 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004776 Py_ssize_t repsize, k, startpos;
4777 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004778 rep = unicode_encode_call_errorhandler(
4779 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004780 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004781 if (!rep)
4782 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004784 if (PyBytes_Check(rep))
4785 repsize = PyBytes_GET_SIZE(rep);
4786 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004787 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004788
4789 if (repsize > 4) {
4790 Py_ssize_t offset;
4791
4792 if (result == NULL)
4793 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004794 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004795 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4798 /* integer overflow */
4799 PyErr_NoMemory();
4800 goto error;
4801 }
4802 nallocated += repsize - 4;
4803 if (result != NULL) {
4804 if (_PyBytes_Resize(&result, nallocated) < 0)
4805 goto error;
4806 } else {
4807 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004808 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004809 goto error;
4810 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4811 }
4812 p = PyBytes_AS_STRING(result) + offset;
4813 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004815 if (PyBytes_Check(rep)) {
4816 char *prep = PyBytes_AS_STRING(rep);
4817 for(k = repsize; k > 0; k--)
4818 *p++ = *prep++;
4819 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004820 enum PyUnicode_Kind repkind;
4821 void *repdata;
4822
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004823 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004824 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004825 repkind = PyUnicode_KIND(rep);
4826 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827
4828 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004829 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004831 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004832 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004833 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004834 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004835 goto error;
4836 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004837 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004838 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004839 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004840 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004841 } else if (ch < 0x10000) {
4842 *p++ = (char)(0xe0 | (ch >> 12));
4843 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4844 *p++ = (char)(0x80 | (ch & 0x3f));
4845 } else /* ch >= 0x10000 */ {
Victor Stinner8faf8212011-12-08 22:14:11 +01004846 assert(ch <= MAX_UNICODE);
Tim Peters602f7402002-04-27 18:03:26 +00004847 /* Encode UCS4 Unicode ordinals */
4848 *p++ = (char)(0xf0 | (ch >> 18));
4849 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4850 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4851 *p++ = (char)(0x80 | (ch & 0x3f));
4852 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004853 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004854
Guido van Rossum98297ee2007-11-06 21:34:58 +00004855 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004856 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004857 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004858 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004859 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004860 }
4861 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004862 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004863 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004864 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004865 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004866 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004867
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004868 Py_XDECREF(errorHandler);
4869 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004870 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004871 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004872 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004873 Py_XDECREF(errorHandler);
4874 Py_XDECREF(exc);
4875 Py_XDECREF(result);
4876 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004877
Tim Peters602f7402002-04-27 18:03:26 +00004878#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879}
4880
Alexander Belopolsky40018472011-02-26 01:02:56 +00004881PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004882PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4883 Py_ssize_t size,
4884 const char *errors)
4885{
4886 PyObject *v, *unicode;
4887
4888 unicode = PyUnicode_FromUnicode(s, size);
4889 if (unicode == NULL)
4890 return NULL;
4891 v = _PyUnicode_AsUTF8String(unicode, errors);
4892 Py_DECREF(unicode);
4893 return v;
4894}
4895
4896PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004897PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004898{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004899 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004900}
4901
Walter Dörwald41980ca2007-08-16 21:55:45 +00004902/* --- UTF-32 Codec ------------------------------------------------------- */
4903
4904PyObject *
4905PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004906 Py_ssize_t size,
4907 const char *errors,
4908 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004909{
4910 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4911}
4912
4913PyObject *
4914PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004915 Py_ssize_t size,
4916 const char *errors,
4917 int *byteorder,
4918 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004919{
4920 const char *starts = s;
4921 Py_ssize_t startinpos;
4922 Py_ssize_t endinpos;
4923 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004924 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004925 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004926 int bo = 0; /* assume native ordering by default */
4927 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004928 /* Offsets from q for retrieving bytes in the right order. */
4929#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4930 int iorder[] = {0, 1, 2, 3};
4931#else
4932 int iorder[] = {3, 2, 1, 0};
4933#endif
4934 PyObject *errorHandler = NULL;
4935 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004936
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937 q = (unsigned char *)s;
4938 e = q + size;
4939
4940 if (byteorder)
4941 bo = *byteorder;
4942
4943 /* Check for BOM marks (U+FEFF) in the input and adjust current
4944 byte order setting accordingly. In native mode, the leading BOM
4945 mark is skipped, in all other modes, it is copied to the output
4946 stream as-is (giving a ZWNBSP character). */
4947 if (bo == 0) {
4948 if (size >= 4) {
4949 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004951#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004952 if (bom == 0x0000FEFF) {
4953 q += 4;
4954 bo = -1;
4955 }
4956 else if (bom == 0xFFFE0000) {
4957 q += 4;
4958 bo = 1;
4959 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004961 if (bom == 0x0000FEFF) {
4962 q += 4;
4963 bo = 1;
4964 }
4965 else if (bom == 0xFFFE0000) {
4966 q += 4;
4967 bo = -1;
4968 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004970 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971 }
4972
4973 if (bo == -1) {
4974 /* force LE */
4975 iorder[0] = 0;
4976 iorder[1] = 1;
4977 iorder[2] = 2;
4978 iorder[3] = 3;
4979 }
4980 else if (bo == 1) {
4981 /* force BE */
4982 iorder[0] = 3;
4983 iorder[1] = 2;
4984 iorder[2] = 1;
4985 iorder[3] = 0;
4986 }
4987
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004988 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004989 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004990 if (!unicode)
4991 return NULL;
4992 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004993 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004994 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004995
Walter Dörwald41980ca2007-08-16 21:55:45 +00004996 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004997 Py_UCS4 ch;
4998 /* remaining bytes at the end? (size should be divisible by 4) */
4999 if (e-q<4) {
5000 if (consumed)
5001 break;
5002 errmsg = "truncated data";
5003 startinpos = ((const char *)q)-starts;
5004 endinpos = ((const char *)e)-starts;
5005 goto utf32Error;
5006 /* The remaining input chars are ignored if the callback
5007 chooses to skip the input */
5008 }
5009 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5010 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005011
Benjamin Peterson29060642009-01-31 22:14:21 +00005012 if (ch >= 0x110000)
5013 {
5014 errmsg = "codepoint not in range(0x110000)";
5015 startinpos = ((const char *)q)-starts;
5016 endinpos = startinpos+4;
5017 goto utf32Error;
5018 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005019 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5020 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 q += 4;
5022 continue;
5023 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 if (unicode_decode_call_errorhandler(
5025 errors, &errorHandler,
5026 "utf32", errmsg,
5027 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005028 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005030 }
5031
5032 if (byteorder)
5033 *byteorder = bo;
5034
5035 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005037
5038 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005039 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005040 goto onError;
5041
5042 Py_XDECREF(errorHandler);
5043 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005044 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045
Benjamin Peterson29060642009-01-31 22:14:21 +00005046 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047 Py_DECREF(unicode);
5048 Py_XDECREF(errorHandler);
5049 Py_XDECREF(exc);
5050 return NULL;
5051}
5052
5053PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005054_PyUnicode_EncodeUTF32(PyObject *str,
5055 const char *errors,
5056 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005058 int kind;
5059 void *data;
5060 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005061 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005063 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064 /* Offsets from p for storing byte pairs in the right order. */
5065#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5066 int iorder[] = {0, 1, 2, 3};
5067#else
5068 int iorder[] = {3, 2, 1, 0};
5069#endif
5070
Benjamin Peterson29060642009-01-31 22:14:21 +00005071#define STORECHAR(CH) \
5072 do { \
5073 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5074 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5075 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5076 p[iorder[0]] = (CH) & 0xff; \
5077 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005078 } while(0)
5079
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005080 if (!PyUnicode_Check(str)) {
5081 PyErr_BadArgument();
5082 return NULL;
5083 }
5084 if (PyUnicode_READY(str) < 0)
5085 return NULL;
5086 kind = PyUnicode_KIND(str);
5087 data = PyUnicode_DATA(str);
5088 len = PyUnicode_GET_LENGTH(str);
5089
5090 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005091 bytesize = nsize * 4;
5092 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005094 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095 if (v == NULL)
5096 return NULL;
5097
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005098 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005099 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005101 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005102 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103
5104 if (byteorder == -1) {
5105 /* force LE */
5106 iorder[0] = 0;
5107 iorder[1] = 1;
5108 iorder[2] = 2;
5109 iorder[3] = 3;
5110 }
5111 else if (byteorder == 1) {
5112 /* force BE */
5113 iorder[0] = 3;
5114 iorder[1] = 2;
5115 iorder[2] = 1;
5116 iorder[3] = 0;
5117 }
5118
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005119 for (i = 0; i < len; i++)
5120 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005121
5122 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005123 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005124#undef STORECHAR
5125}
5126
Alexander Belopolsky40018472011-02-26 01:02:56 +00005127PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005128PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5129 Py_ssize_t size,
5130 const char *errors,
5131 int byteorder)
5132{
5133 PyObject *result;
5134 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5135 if (tmp == NULL)
5136 return NULL;
5137 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5138 Py_DECREF(tmp);
5139 return result;
5140}
5141
5142PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005143PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144{
Victor Stinnerb960b342011-11-20 19:12:52 +01005145 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005146}
5147
Guido van Rossumd57fd912000-03-10 22:53:23 +00005148/* --- UTF-16 Codec ------------------------------------------------------- */
5149
Tim Peters772747b2001-08-09 22:21:55 +00005150PyObject *
5151PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005152 Py_ssize_t size,
5153 const char *errors,
5154 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005155{
Walter Dörwald69652032004-09-07 20:24:22 +00005156 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5157}
5158
Antoine Pitrouab868312009-01-10 15:40:25 +00005159/* Two masks for fast checking of whether a C 'long' may contain
5160 UTF16-encoded surrogate characters. This is an efficient heuristic,
5161 assuming that non-surrogate characters with a code point >= 0x8000 are
5162 rare in most input.
5163 FAST_CHAR_MASK is used when the input is in native byte ordering,
5164 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005165*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005166#if (SIZEOF_LONG == 8)
5167# define FAST_CHAR_MASK 0x8000800080008000L
5168# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5169#elif (SIZEOF_LONG == 4)
5170# define FAST_CHAR_MASK 0x80008000L
5171# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5172#else
5173# error C 'long' size should be either 4 or 8!
5174#endif
5175
Walter Dörwald69652032004-09-07 20:24:22 +00005176PyObject *
5177PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005178 Py_ssize_t size,
5179 const char *errors,
5180 int *byteorder,
5181 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005182{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005183 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005184 Py_ssize_t startinpos;
5185 Py_ssize_t endinpos;
5186 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005187 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005188 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005189 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005190 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005191 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005192 /* Offsets from q for retrieving byte pairs in the right order. */
5193#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5194 int ihi = 1, ilo = 0;
5195#else
5196 int ihi = 0, ilo = 1;
5197#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005198 PyObject *errorHandler = NULL;
5199 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200
5201 /* Note: size will always be longer than the resulting Unicode
5202 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005203 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005204 if (!unicode)
5205 return NULL;
5206 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005207 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005208 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209
Tim Peters772747b2001-08-09 22:21:55 +00005210 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005211 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
5213 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005214 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005216 /* Check for BOM marks (U+FEFF) in the input and adjust current
5217 byte order setting accordingly. In native mode, the leading BOM
5218 mark is skipped, in all other modes, it is copied to the output
5219 stream as-is (giving a ZWNBSP character). */
5220 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005221 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005222 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005223#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 if (bom == 0xFEFF) {
5225 q += 2;
5226 bo = -1;
5227 }
5228 else if (bom == 0xFFFE) {
5229 q += 2;
5230 bo = 1;
5231 }
Tim Petersced69f82003-09-16 20:30:58 +00005232#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005233 if (bom == 0xFEFF) {
5234 q += 2;
5235 bo = 1;
5236 }
5237 else if (bom == 0xFFFE) {
5238 q += 2;
5239 bo = -1;
5240 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005241#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005242 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005244
Tim Peters772747b2001-08-09 22:21:55 +00005245 if (bo == -1) {
5246 /* force LE */
5247 ihi = 1;
5248 ilo = 0;
5249 }
5250 else if (bo == 1) {
5251 /* force BE */
5252 ihi = 0;
5253 ilo = 1;
5254 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005255#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5256 native_ordering = ilo < ihi;
5257#else
5258 native_ordering = ilo > ihi;
5259#endif
Tim Peters772747b2001-08-09 22:21:55 +00005260
Antoine Pitrouab868312009-01-10 15:40:25 +00005261 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005262 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005263 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005264 /* First check for possible aligned read of a C 'long'. Unaligned
5265 reads are more expensive, better to defer to another iteration. */
5266 if (!((size_t) q & LONG_PTR_MASK)) {
5267 /* Fast path for runs of non-surrogate chars. */
5268 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005269 int kind = PyUnicode_KIND(unicode);
5270 void *data = PyUnicode_DATA(unicode);
5271 while (_q < aligned_end) {
5272 unsigned long block = * (unsigned long *) _q;
5273 unsigned short *pblock = (unsigned short*)&block;
5274 Py_UCS4 maxch;
5275 if (native_ordering) {
5276 /* Can use buffer directly */
5277 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005278 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005279 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005280 else {
5281 /* Need to byte-swap */
5282 unsigned char *_p = (unsigned char*)pblock;
5283 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005284 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005285 _p[0] = _q[1];
5286 _p[1] = _q[0];
5287 _p[2] = _q[3];
5288 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005289#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005290 _p[4] = _q[5];
5291 _p[5] = _q[4];
5292 _p[6] = _q[7];
5293 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005294#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005295 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005296 maxch = Py_MAX(pblock[0], pblock[1]);
5297#if SIZEOF_LONG == 8
5298 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5299#endif
5300 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5301 if (unicode_widen(&unicode, maxch) < 0)
5302 goto onError;
5303 kind = PyUnicode_KIND(unicode);
5304 data = PyUnicode_DATA(unicode);
5305 }
5306 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5307 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5308#if SIZEOF_LONG == 8
5309 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5310 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5311#endif
5312 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005313 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005314 q = _q;
5315 if (q >= e)
5316 break;
5317 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005319
Benjamin Peterson14339b62009-01-31 16:36:08 +00005320 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005321
Victor Stinner551ac952011-11-29 22:58:13 +01005322 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005323 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5324 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 continue;
5326 }
5327
5328 /* UTF-16 code pair: */
5329 if (q > e) {
5330 errmsg = "unexpected end of data";
5331 startinpos = (((const char *)q) - 2) - starts;
5332 endinpos = ((const char *)e) + 1 - starts;
5333 goto utf16Error;
5334 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005335 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5336 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005338 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005339 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005340 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005341 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005342 continue;
5343 }
5344 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005345 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005346 startinpos = (((const char *)q)-4)-starts;
5347 endinpos = startinpos+2;
5348 goto utf16Error;
5349 }
5350
Benjamin Peterson14339b62009-01-31 16:36:08 +00005351 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 errmsg = "illegal encoding";
5353 startinpos = (((const char *)q)-2)-starts;
5354 endinpos = startinpos+2;
5355 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005356
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005359 errors,
5360 &errorHandler,
5361 "utf16", errmsg,
5362 &starts,
5363 (const char **)&e,
5364 &startinpos,
5365 &endinpos,
5366 &exc,
5367 (const char **)&q,
5368 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005369 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005370 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005371 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005372 /* remaining byte at the end? (size should be even) */
5373 if (e == q) {
5374 if (!consumed) {
5375 errmsg = "truncated data";
5376 startinpos = ((const char *)q) - starts;
5377 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005378 if (unicode_decode_call_errorhandler(
5379 errors,
5380 &errorHandler,
5381 "utf16", errmsg,
5382 &starts,
5383 (const char **)&e,
5384 &startinpos,
5385 &endinpos,
5386 &exc,
5387 (const char **)&q,
5388 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005389 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005390 goto onError;
5391 /* The remaining input chars are ignored if the callback
5392 chooses to skip the input */
5393 }
5394 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395
5396 if (byteorder)
5397 *byteorder = bo;
5398
Walter Dörwald69652032004-09-07 20:24:22 +00005399 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005400 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005401
Guido van Rossumd57fd912000-03-10 22:53:23 +00005402 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005403 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005404 goto onError;
5405
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005406 Py_XDECREF(errorHandler);
5407 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005408 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005409
Benjamin Peterson29060642009-01-31 22:14:21 +00005410 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005411 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005412 Py_XDECREF(errorHandler);
5413 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005414 return NULL;
5415}
5416
Antoine Pitrouab868312009-01-10 15:40:25 +00005417#undef FAST_CHAR_MASK
5418#undef SWAPPED_FAST_CHAR_MASK
5419
Tim Peters772747b2001-08-09 22:21:55 +00005420PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005421_PyUnicode_EncodeUTF16(PyObject *str,
5422 const char *errors,
5423 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005425 int kind;
5426 void *data;
5427 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005428 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005429 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005430 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005431 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005432 /* Offsets from p for storing byte pairs in the right order. */
5433#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5434 int ihi = 1, ilo = 0;
5435#else
5436 int ihi = 0, ilo = 1;
5437#endif
5438
Benjamin Peterson29060642009-01-31 22:14:21 +00005439#define STORECHAR(CH) \
5440 do { \
5441 p[ihi] = ((CH) >> 8) & 0xff; \
5442 p[ilo] = (CH) & 0xff; \
5443 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005444 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005446 if (!PyUnicode_Check(str)) {
5447 PyErr_BadArgument();
5448 return NULL;
5449 }
5450 if (PyUnicode_READY(str) < 0)
5451 return NULL;
5452 kind = PyUnicode_KIND(str);
5453 data = PyUnicode_DATA(str);
5454 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005455
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005456 pairs = 0;
5457 if (kind == PyUnicode_4BYTE_KIND)
5458 for (i = 0; i < len; i++)
5459 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5460 pairs++;
5461 /* 2 * (len + pairs + (byteorder == 0)) */
5462 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005463 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005464 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005465 bytesize = nsize * 2;
5466 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005467 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005468 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005469 if (v == NULL)
5470 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005471
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005472 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005473 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005474 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005475 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005476 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005477
5478 if (byteorder == -1) {
5479 /* force LE */
5480 ihi = 1;
5481 ilo = 0;
5482 }
5483 else if (byteorder == 1) {
5484 /* force BE */
5485 ihi = 0;
5486 ilo = 1;
5487 }
5488
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005489 for (i = 0; i < len; i++) {
5490 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5491 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005492 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005493 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5494 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 }
Tim Peters772747b2001-08-09 22:21:55 +00005496 STORECHAR(ch);
5497 if (ch2)
5498 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005499 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005500
5501 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005502 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005503#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005504}
5505
Alexander Belopolsky40018472011-02-26 01:02:56 +00005506PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005507PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5508 Py_ssize_t size,
5509 const char *errors,
5510 int byteorder)
5511{
5512 PyObject *result;
5513 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5514 if (tmp == NULL)
5515 return NULL;
5516 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5517 Py_DECREF(tmp);
5518 return result;
5519}
5520
5521PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005522PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005524 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525}
5526
5527/* --- Unicode Escape Codec ----------------------------------------------- */
5528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005529/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5530 if all the escapes in the string make it still a valid ASCII string.
5531 Returns -1 if any escapes were found which cause the string to
5532 pop out of ASCII range. Otherwise returns the length of the
5533 required buffer to hold the string.
5534 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005535static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005536length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5537{
5538 const unsigned char *p = (const unsigned char *)s;
5539 const unsigned char *end = p + size;
5540 Py_ssize_t length = 0;
5541
5542 if (size < 0)
5543 return -1;
5544
5545 for (; p < end; ++p) {
5546 if (*p > 127) {
5547 /* Non-ASCII */
5548 return -1;
5549 }
5550 else if (*p != '\\') {
5551 /* Normal character */
5552 ++length;
5553 }
5554 else {
5555 /* Backslash-escape, check next char */
5556 ++p;
5557 /* Escape sequence reaches till end of string or
5558 non-ASCII follow-up. */
5559 if (p >= end || *p > 127)
5560 return -1;
5561 switch (*p) {
5562 case '\n':
5563 /* backslash + \n result in zero characters */
5564 break;
5565 case '\\': case '\'': case '\"':
5566 case 'b': case 'f': case 't':
5567 case 'n': case 'r': case 'v': case 'a':
5568 ++length;
5569 break;
5570 case '0': case '1': case '2': case '3':
5571 case '4': case '5': case '6': case '7':
5572 case 'x': case 'u': case 'U': case 'N':
5573 /* these do not guarantee ASCII characters */
5574 return -1;
5575 default:
5576 /* count the backslash + the other character */
5577 length += 2;
5578 }
5579 }
5580 }
5581 return length;
5582}
5583
Fredrik Lundh06d12682001-01-24 07:59:11 +00005584static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005585
Alexander Belopolsky40018472011-02-26 01:02:56 +00005586PyObject *
5587PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005588 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005589 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005591 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005592 Py_ssize_t startinpos;
5593 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005594 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005595 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005596 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005597 char* message;
5598 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005599 PyObject *errorHandler = NULL;
5600 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005601 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005602 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005603
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005604 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005605
5606 /* After length_of_escaped_ascii_string() there are two alternatives,
5607 either the string is pure ASCII with named escapes like \n, etc.
5608 and we determined it's exact size (common case)
5609 or it contains \x, \u, ... escape sequences. then we create a
5610 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005611 if (len >= 0) {
5612 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005613 if (!v)
5614 goto onError;
5615 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005616 }
5617 else {
5618 /* Escaped strings will always be longer than the resulting
5619 Unicode string, so we start with size here and then reduce the
5620 length after conversion to the true value.
5621 (but if the error callback returns a long replacement string
5622 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005623 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005624 if (!v)
5625 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005626 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005627 }
5628
Guido van Rossumd57fd912000-03-10 22:53:23 +00005629 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005630 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005631 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005633
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634 while (s < end) {
5635 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005636 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005637 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005638
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005639 /* The only case in which i == ascii_length is a backslash
5640 followed by a newline. */
5641 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642
Guido van Rossumd57fd912000-03-10 22:53:23 +00005643 /* Non-escape characters are interpreted as Unicode ordinals */
5644 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005645 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5646 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647 continue;
5648 }
5649
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005650 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651 /* \ - Escapes */
5652 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005653 c = *s++;
5654 if (s > end)
5655 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005656
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005657 /* The only case in which i == ascii_length is a backslash
5658 followed by a newline. */
5659 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005660
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005661 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005662
Benjamin Peterson29060642009-01-31 22:14:21 +00005663 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005664#define WRITECHAR(ch) \
5665 do { \
5666 if (unicode_putchar(&v, &i, ch) < 0) \
5667 goto onError; \
5668 }while(0)
5669
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005671 case '\\': WRITECHAR('\\'); break;
5672 case '\'': WRITECHAR('\''); break;
5673 case '\"': WRITECHAR('\"'); break;
5674 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005675 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005676 case 'f': WRITECHAR('\014'); break;
5677 case 't': WRITECHAR('\t'); break;
5678 case 'n': WRITECHAR('\n'); break;
5679 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005681 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005682 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005683 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684
Benjamin Peterson29060642009-01-31 22:14:21 +00005685 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 case '0': case '1': case '2': case '3':
5687 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005688 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005689 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005690 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005691 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005692 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005694 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695 break;
5696
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 /* hex escapes */
5698 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005699 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005700 digits = 2;
5701 message = "truncated \\xXX escape";
5702 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703
Benjamin Peterson29060642009-01-31 22:14:21 +00005704 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005705 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005706 digits = 4;
5707 message = "truncated \\uXXXX escape";
5708 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709
Benjamin Peterson29060642009-01-31 22:14:21 +00005710 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005711 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005712 digits = 8;
5713 message = "truncated \\UXXXXXXXX escape";
5714 hexescape:
5715 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005716 if (s+digits>end) {
5717 endinpos = size;
5718 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005719 errors, &errorHandler,
5720 "unicodeescape", "end of string in escape sequence",
5721 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005722 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005723 goto onError;
5724 goto nextByte;
5725 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005726 for (j = 0; j < digits; ++j) {
5727 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005728 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005729 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005730 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005731 errors, &errorHandler,
5732 "unicodeescape", message,
5733 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005734 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005735 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005736 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005738 }
5739 chr = (chr<<4) & ~0xF;
5740 if (c >= '0' && c <= '9')
5741 chr += c - '0';
5742 else if (c >= 'a' && c <= 'f')
5743 chr += 10 + c - 'a';
5744 else
5745 chr += 10 + c - 'A';
5746 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005747 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005748 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005749 /* _decoding_error will have already written into the
5750 target buffer. */
5751 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005752 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005753 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005754 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005755 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005756 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005757 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005758 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005759 errors, &errorHandler,
5760 "unicodeescape", "illegal Unicode character",
5761 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005762 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005763 goto onError;
5764 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005765 break;
5766
Benjamin Peterson29060642009-01-31 22:14:21 +00005767 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005768 case 'N':
5769 message = "malformed \\N character escape";
5770 if (ucnhash_CAPI == NULL) {
5771 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005772 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5773 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005774 if (ucnhash_CAPI == NULL)
5775 goto ucnhashError;
5776 }
5777 if (*s == '{') {
5778 const char *start = s+1;
5779 /* look for the closing brace */
5780 while (*s != '}' && s < end)
5781 s++;
5782 if (s > start && s < end && *s == '}') {
5783 /* found a name. look it up in the unicode database */
5784 message = "unknown Unicode character name";
5785 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005786 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005787 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005788 goto store;
5789 }
5790 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005791 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005792 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005793 errors, &errorHandler,
5794 "unicodeescape", message,
5795 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005796 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005798 break;
5799
5800 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005801 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005802 message = "\\ at end of string";
5803 s--;
5804 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005805 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 errors, &errorHandler,
5807 "unicodeescape", message,
5808 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005809 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005810 goto onError;
5811 }
5812 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005813 WRITECHAR('\\');
5814 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005815 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005816 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005818 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005819 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005820 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005821#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005822
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005823 if (PyUnicode_Resize(&v, i) < 0)
5824 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005825 Py_XDECREF(errorHandler);
5826 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005827 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005828
Benjamin Peterson29060642009-01-31 22:14:21 +00005829 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005830 PyErr_SetString(
5831 PyExc_UnicodeError,
5832 "\\N escapes not supported (can't load unicodedata module)"
5833 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005834 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005835 Py_XDECREF(errorHandler);
5836 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005837 return NULL;
5838
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005840 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005841 Py_XDECREF(errorHandler);
5842 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843 return NULL;
5844}
5845
5846/* Return a Unicode-Escape string version of the Unicode object.
5847
5848 If quotes is true, the string is enclosed in u"" or u'' quotes as
5849 appropriate.
5850
5851*/
5852
Alexander Belopolsky40018472011-02-26 01:02:56 +00005853PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005854PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005856 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005857 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005858 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005859 int kind;
5860 void *data;
5861 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862
Thomas Wouters89f507f2006-12-13 04:49:30 +00005863 /* Initial allocation is based on the longest-possible unichr
5864 escape.
5865
5866 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5867 unichr, so in this case it's the longest unichr escape. In
5868 narrow (UTF-16) builds this is five chars per source unichr
5869 since there are two unichrs in the surrogate pair, so in narrow
5870 (UTF-16) builds it's not the longest unichr escape.
5871
5872 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5873 so in the narrow (UTF-16) build case it's the longest unichr
5874 escape.
5875 */
5876
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005877 if (!PyUnicode_Check(unicode)) {
5878 PyErr_BadArgument();
5879 return NULL;
5880 }
5881 if (PyUnicode_READY(unicode) < 0)
5882 return NULL;
5883 len = PyUnicode_GET_LENGTH(unicode);
5884 kind = PyUnicode_KIND(unicode);
5885 data = PyUnicode_DATA(unicode);
5886 switch(kind) {
5887 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5888 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5889 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5890 }
5891
5892 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005893 return PyBytes_FromStringAndSize(NULL, 0);
5894
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005895 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005897
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005898 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005900 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902 if (repr == NULL)
5903 return NULL;
5904
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005905 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005907 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005908 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005909
Walter Dörwald79e913e2007-05-12 11:08:06 +00005910 /* Escape backslashes */
5911 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 *p++ = '\\';
5913 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005914 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005915 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005916
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005917 /* Map 21-bit characters to '\U00xxxxxx' */
5918 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005919 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005920 *p++ = '\\';
5921 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005922 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5923 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5924 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5925 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5926 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5927 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5928 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5929 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005931 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005932
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005934 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 *p++ = '\\';
5936 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005937 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5938 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5939 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5940 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005942
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005943 /* Map special whitespace to '\t', \n', '\r' */
5944 else if (ch == '\t') {
5945 *p++ = '\\';
5946 *p++ = 't';
5947 }
5948 else if (ch == '\n') {
5949 *p++ = '\\';
5950 *p++ = 'n';
5951 }
5952 else if (ch == '\r') {
5953 *p++ = '\\';
5954 *p++ = 'r';
5955 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005956
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005957 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005958 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005960 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005961 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5962 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005963 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005964
Guido van Rossumd57fd912000-03-10 22:53:23 +00005965 /* Copy everything else as-is */
5966 else
5967 *p++ = (char) ch;
5968 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005970 assert(p - PyBytes_AS_STRING(repr) > 0);
5971 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5972 return NULL;
5973 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974}
5975
Alexander Belopolsky40018472011-02-26 01:02:56 +00005976PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005977PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5978 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005980 PyObject *result;
5981 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5982 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005984 result = PyUnicode_AsUnicodeEscapeString(tmp);
5985 Py_DECREF(tmp);
5986 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987}
5988
5989/* --- Raw Unicode Escape Codec ------------------------------------------- */
5990
Alexander Belopolsky40018472011-02-26 01:02:56 +00005991PyObject *
5992PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005993 Py_ssize_t size,
5994 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005996 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005997 Py_ssize_t startinpos;
5998 Py_ssize_t endinpos;
5999 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006000 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001 const char *end;
6002 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006003 PyObject *errorHandler = NULL;
6004 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006005
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 /* Escaped strings will always be longer than the resulting
6007 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006008 length after conversion to the true value. (But decoding error
6009 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006010 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006014 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006015 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016 end = s + size;
6017 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006018 unsigned char c;
6019 Py_UCS4 x;
6020 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006021 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022
Benjamin Peterson29060642009-01-31 22:14:21 +00006023 /* Non-escape characters are interpreted as Unicode ordinals */
6024 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006025 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6026 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006027 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006028 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006029 startinpos = s-starts;
6030
6031 /* \u-escapes are only interpreted iff the number of leading
6032 backslashes if odd */
6033 bs = s;
6034 for (;s < end;) {
6035 if (*s != '\\')
6036 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006037 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6038 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 }
6040 if (((s - bs) & 1) == 0 ||
6041 s >= end ||
6042 (*s != 'u' && *s != 'U')) {
6043 continue;
6044 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006045 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 count = *s=='u' ? 4 : 8;
6047 s++;
6048
6049 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 for (x = 0, i = 0; i < count; ++i, ++s) {
6051 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006052 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006053 endinpos = s-starts;
6054 if (unicode_decode_call_errorhandler(
6055 errors, &errorHandler,
6056 "rawunicodeescape", "truncated \\uXXXX",
6057 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006058 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 goto onError;
6060 goto nextByte;
6061 }
6062 x = (x<<4) & ~0xF;
6063 if (c >= '0' && c <= '9')
6064 x += c - '0';
6065 else if (c >= 'a' && c <= 'f')
6066 x += 10 + c - 'a';
6067 else
6068 x += 10 + c - 'A';
6069 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006070 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006071 if (unicode_putchar(&v, &outpos, x) < 0)
6072 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006073 } else {
6074 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006075 if (unicode_decode_call_errorhandler(
6076 errors, &errorHandler,
6077 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006079 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006081 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 nextByte:
6083 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006085 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006087 Py_XDECREF(errorHandler);
6088 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006089 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006090
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006093 Py_XDECREF(errorHandler);
6094 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095 return NULL;
6096}
6097
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006098
Alexander Belopolsky40018472011-02-26 01:02:56 +00006099PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006100PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006102 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103 char *p;
6104 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006105 Py_ssize_t expandsize, pos;
6106 int kind;
6107 void *data;
6108 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006110 if (!PyUnicode_Check(unicode)) {
6111 PyErr_BadArgument();
6112 return NULL;
6113 }
6114 if (PyUnicode_READY(unicode) < 0)
6115 return NULL;
6116 kind = PyUnicode_KIND(unicode);
6117 data = PyUnicode_DATA(unicode);
6118 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006119 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6120 bytes, and 1 byte characters 4. */
6121 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006122
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006123 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006125
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127 if (repr == NULL)
6128 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006129 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006130 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006132 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133 for (pos = 0; pos < len; pos++) {
6134 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006135 /* Map 32-bit characters to '\Uxxxxxxxx' */
6136 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006137 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006138 *p++ = '\\';
6139 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006140 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6141 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6142 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6143 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6144 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6145 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6146 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6147 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006148 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 *p++ = '\\';
6152 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006153 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6154 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6155 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6156 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 /* Copy everything else as-is */
6159 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 *p++ = (char) ch;
6161 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006162
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006163 assert(p > q);
6164 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006165 return NULL;
6166 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167}
6168
Alexander Belopolsky40018472011-02-26 01:02:56 +00006169PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006170PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6171 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006172{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006173 PyObject *result;
6174 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6175 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006176 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006177 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6178 Py_DECREF(tmp);
6179 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180}
6181
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006182/* --- Unicode Internal Codec ------------------------------------------- */
6183
Alexander Belopolsky40018472011-02-26 01:02:56 +00006184PyObject *
6185_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006186 Py_ssize_t size,
6187 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006188{
6189 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006190 Py_ssize_t startinpos;
6191 Py_ssize_t endinpos;
6192 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006193 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006194 const char *end;
6195 const char *reason;
6196 PyObject *errorHandler = NULL;
6197 PyObject *exc = NULL;
6198
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006199 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006200 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006201 1))
6202 return NULL;
6203
Thomas Wouters89f507f2006-12-13 04:49:30 +00006204 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006205 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006206 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006208 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006209 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006210 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006211 end = s + size;
6212
6213 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006214 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006215 Py_UCS4 ch;
6216 /* We copy the raw representation one byte at a time because the
6217 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006218 ((char *) &uch)[0] = s[0];
6219 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006220#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006221 ((char *) &uch)[2] = s[2];
6222 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006223#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006224 ch = uch;
6225
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006226 /* We have to sanity check the raw data, otherwise doom looms for
6227 some malformed UCS-4 data. */
6228 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006229#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006230 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006231#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006232 end-s < Py_UNICODE_SIZE
6233 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006234 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006235 startinpos = s - starts;
6236 if (end-s < Py_UNICODE_SIZE) {
6237 endinpos = end-starts;
6238 reason = "truncated input";
6239 }
6240 else {
6241 endinpos = s - starts + Py_UNICODE_SIZE;
6242 reason = "illegal code point (> 0x10FFFF)";
6243 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006244 if (unicode_decode_call_errorhandler(
6245 errors, &errorHandler,
6246 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006247 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006248 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006249 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006250 continue;
6251 }
6252
6253 s += Py_UNICODE_SIZE;
6254#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006255 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006256 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006257 Py_UNICODE uch2;
6258 ((char *) &uch2)[0] = s[0];
6259 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006260 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006261 {
Victor Stinner551ac952011-11-29 22:58:13 +01006262 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006263 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006264 }
6265 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006266#endif
6267
6268 if (unicode_putchar(&v, &outpos, ch) < 0)
6269 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 }
6271
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006272 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006273 goto onError;
6274 Py_XDECREF(errorHandler);
6275 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006276 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006277
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279 Py_XDECREF(v);
6280 Py_XDECREF(errorHandler);
6281 Py_XDECREF(exc);
6282 return NULL;
6283}
6284
Guido van Rossumd57fd912000-03-10 22:53:23 +00006285/* --- Latin-1 Codec ------------------------------------------------------ */
6286
Alexander Belopolsky40018472011-02-26 01:02:56 +00006287PyObject *
6288PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006289 Py_ssize_t size,
6290 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006292 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006293 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294}
6295
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006296/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006297static void
6298make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006299 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006300 PyObject *unicode,
6301 Py_ssize_t startpos, Py_ssize_t endpos,
6302 const char *reason)
6303{
6304 if (*exceptionObject == NULL) {
6305 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006306 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006307 encoding, unicode, startpos, endpos, reason);
6308 }
6309 else {
6310 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6311 goto onError;
6312 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6313 goto onError;
6314 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6315 goto onError;
6316 return;
6317 onError:
6318 Py_DECREF(*exceptionObject);
6319 *exceptionObject = NULL;
6320 }
6321}
6322
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006323/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006324static void
6325raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006326 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006327 PyObject *unicode,
6328 Py_ssize_t startpos, Py_ssize_t endpos,
6329 const char *reason)
6330{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006331 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006332 encoding, unicode, startpos, endpos, reason);
6333 if (*exceptionObject != NULL)
6334 PyCodec_StrictErrors(*exceptionObject);
6335}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006336
6337/* error handling callback helper:
6338 build arguments, call the callback and check the arguments,
6339 put the result into newpos and return the replacement string, which
6340 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006341static PyObject *
6342unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006343 PyObject **errorHandler,
6344 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006345 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006346 Py_ssize_t startpos, Py_ssize_t endpos,
6347 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006348{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006349 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006350 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006351 PyObject *restuple;
6352 PyObject *resunicode;
6353
6354 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006358 }
6359
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006360 if (PyUnicode_READY(unicode) < 0)
6361 return NULL;
6362 len = PyUnicode_GET_LENGTH(unicode);
6363
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006364 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006365 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006367 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006368
6369 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006372 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006374 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006375 Py_DECREF(restuple);
6376 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006378 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 &resunicode, newpos)) {
6380 Py_DECREF(restuple);
6381 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006382 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006383 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6384 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6385 Py_DECREF(restuple);
6386 return NULL;
6387 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006389 *newpos = len + *newpos;
6390 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6392 Py_DECREF(restuple);
6393 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006394 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006395 Py_INCREF(resunicode);
6396 Py_DECREF(restuple);
6397 return resunicode;
6398}
6399
Alexander Belopolsky40018472011-02-26 01:02:56 +00006400static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006401unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006402 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006403 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006405 /* input state */
6406 Py_ssize_t pos=0, size;
6407 int kind;
6408 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 /* output object */
6410 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 /* pointer into the output */
6412 char *str;
6413 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006414 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006415 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6416 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 PyObject *errorHandler = NULL;
6418 PyObject *exc = NULL;
6419 /* the following variable is used for caching string comparisons
6420 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6421 int known_errorHandler = -1;
6422
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006423 if (PyUnicode_READY(unicode) < 0)
6424 return NULL;
6425 size = PyUnicode_GET_LENGTH(unicode);
6426 kind = PyUnicode_KIND(unicode);
6427 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 /* allocate enough for a simple encoding without
6429 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006430 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006431 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006432 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006434 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006435 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436 ressize = size;
6437
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006438 while (pos < size) {
6439 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440
Benjamin Peterson29060642009-01-31 22:14:21 +00006441 /* can we encode this? */
6442 if (c<limit) {
6443 /* no overflow check, because we know that the space is enough */
6444 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006445 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006446 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006447 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006448 Py_ssize_t requiredsize;
6449 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006450 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006451 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006452 Py_ssize_t collstart = pos;
6453 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006454 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 ++collend;
6457 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6458 if (known_errorHandler==-1) {
6459 if ((errors==NULL) || (!strcmp(errors, "strict")))
6460 known_errorHandler = 1;
6461 else if (!strcmp(errors, "replace"))
6462 known_errorHandler = 2;
6463 else if (!strcmp(errors, "ignore"))
6464 known_errorHandler = 3;
6465 else if (!strcmp(errors, "xmlcharrefreplace"))
6466 known_errorHandler = 4;
6467 else
6468 known_errorHandler = 0;
6469 }
6470 switch (known_errorHandler) {
6471 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006472 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006473 goto onError;
6474 case 2: /* replace */
6475 while (collstart++<collend)
6476 *str++ = '?'; /* fall through */
6477 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006478 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 break;
6480 case 4: /* xmlcharrefreplace */
6481 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006482 /* determine replacement size */
6483 for (i = collstart, repsize = 0; i < collend; ++i) {
6484 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6485 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006486 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006489 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006492 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006493 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006494 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006496 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006497 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006498 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006500 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 if (requiredsize > ressize) {
6504 if (requiredsize<2*ressize)
6505 requiredsize = 2*ressize;
6506 if (_PyBytes_Resize(&res, requiredsize))
6507 goto onError;
6508 str = PyBytes_AS_STRING(res) + respos;
6509 ressize = requiredsize;
6510 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 /* generate replacement */
6512 for (i = collstart; i < collend; ++i) {
6513 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006515 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006516 break;
6517 default:
6518 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006519 encoding, reason, unicode, &exc,
6520 collstart, collend, &newpos);
6521 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6522 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006524 if (PyBytes_Check(repunicode)) {
6525 /* Directly copy bytes result to output. */
6526 repsize = PyBytes_Size(repunicode);
6527 if (repsize > 1) {
6528 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006529 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006530 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6531 Py_DECREF(repunicode);
6532 goto onError;
6533 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006534 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006535 ressize += repsize-1;
6536 }
6537 memcpy(str, PyBytes_AsString(repunicode), repsize);
6538 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006540 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006541 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006542 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 /* need more space? (at least enough for what we
6544 have+the replacement+the rest of the string, so
6545 we won't have to check space for encodable characters) */
6546 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 repsize = PyUnicode_GET_LENGTH(repunicode);
6548 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 if (requiredsize > ressize) {
6550 if (requiredsize<2*ressize)
6551 requiredsize = 2*ressize;
6552 if (_PyBytes_Resize(&res, requiredsize)) {
6553 Py_DECREF(repunicode);
6554 goto onError;
6555 }
6556 str = PyBytes_AS_STRING(res) + respos;
6557 ressize = requiredsize;
6558 }
6559 /* check if there is anything unencodable in the replacement
6560 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006561 for (i = 0; repsize-->0; ++i, ++str) {
6562 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006563 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006564 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006565 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 Py_DECREF(repunicode);
6567 goto onError;
6568 }
6569 *str = (char)c;
6570 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006572 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006573 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006574 }
6575 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006576 /* Resize if we allocated to much */
6577 size = str - PyBytes_AS_STRING(res);
6578 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006579 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006580 if (_PyBytes_Resize(&res, size) < 0)
6581 goto onError;
6582 }
6583
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584 Py_XDECREF(errorHandler);
6585 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006586 return res;
6587
6588 onError:
6589 Py_XDECREF(res);
6590 Py_XDECREF(errorHandler);
6591 Py_XDECREF(exc);
6592 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006593}
6594
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006595/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006596PyObject *
6597PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006598 Py_ssize_t size,
6599 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006600{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006601 PyObject *result;
6602 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6603 if (unicode == NULL)
6604 return NULL;
6605 result = unicode_encode_ucs1(unicode, errors, 256);
6606 Py_DECREF(unicode);
6607 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006608}
6609
Alexander Belopolsky40018472011-02-26 01:02:56 +00006610PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006611_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006612{
6613 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006614 PyErr_BadArgument();
6615 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006616 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006617 if (PyUnicode_READY(unicode) == -1)
6618 return NULL;
6619 /* Fast path: if it is a one-byte string, construct
6620 bytes object directly. */
6621 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6622 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6623 PyUnicode_GET_LENGTH(unicode));
6624 /* Non-Latin-1 characters present. Defer to above function to
6625 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006626 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006627}
6628
6629PyObject*
6630PyUnicode_AsLatin1String(PyObject *unicode)
6631{
6632 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633}
6634
6635/* --- 7-bit ASCII Codec -------------------------------------------------- */
6636
Alexander Belopolsky40018472011-02-26 01:02:56 +00006637PyObject *
6638PyUnicode_DecodeASCII(const char *s,
6639 Py_ssize_t size,
6640 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006641{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006643 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006644 int kind;
6645 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006646 Py_ssize_t startinpos;
6647 Py_ssize_t endinpos;
6648 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006650 int has_error;
6651 const unsigned char *p = (const unsigned char *)s;
6652 const unsigned char *end = p + size;
6653 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654 PyObject *errorHandler = NULL;
6655 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006656
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006657 if (size == 0) {
6658 Py_INCREF(unicode_empty);
6659 return unicode_empty;
6660 }
6661
Guido van Rossumd57fd912000-03-10 22:53:23 +00006662 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006663 if (size == 1 && (unsigned char)s[0] < 128)
6664 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006665
Victor Stinner702c7342011-10-05 13:50:52 +02006666 has_error = 0;
6667 while (p < end && !has_error) {
6668 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6669 an explanation. */
6670 if (!((size_t) p & LONG_PTR_MASK)) {
6671 /* Help register allocation */
6672 register const unsigned char *_p = p;
6673 while (_p < aligned_end) {
6674 unsigned long value = *(unsigned long *) _p;
6675 if (value & ASCII_CHAR_MASK) {
6676 has_error = 1;
6677 break;
6678 }
6679 _p += SIZEOF_LONG;
6680 }
6681 if (_p == end)
6682 break;
6683 if (has_error)
6684 break;
6685 p = _p;
6686 }
6687 if (*p & 0x80) {
6688 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006689 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006690 }
6691 else {
6692 ++p;
6693 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006694 }
Victor Stinner702c7342011-10-05 13:50:52 +02006695 if (!has_error)
6696 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006697
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006698 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006699 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006700 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006701 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006702 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006703 kind = PyUnicode_KIND(v);
6704 data = PyUnicode_DATA(v);
6705 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706 e = s + size;
6707 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 register unsigned char c = (unsigned char)*s;
6709 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006710 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 ++s;
6712 }
6713 else {
6714 startinpos = s-starts;
6715 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 if (unicode_decode_call_errorhandler(
6717 errors, &errorHandler,
6718 "ascii", "ordinal not in range(128)",
6719 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006720 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006722 kind = PyUnicode_KIND(v);
6723 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006725 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006726 if (PyUnicode_Resize(&v, outpos) < 0)
6727 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006728 Py_XDECREF(errorHandler);
6729 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006730 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006731 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006732
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006734 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 Py_XDECREF(errorHandler);
6736 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006737 return NULL;
6738}
6739
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006740/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006741PyObject *
6742PyUnicode_EncodeASCII(const Py_UNICODE *p,
6743 Py_ssize_t size,
6744 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006745{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006746 PyObject *result;
6747 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6748 if (unicode == NULL)
6749 return NULL;
6750 result = unicode_encode_ucs1(unicode, errors, 128);
6751 Py_DECREF(unicode);
6752 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006753}
6754
Alexander Belopolsky40018472011-02-26 01:02:56 +00006755PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006756_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006757{
6758 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 PyErr_BadArgument();
6760 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006761 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006762 if (PyUnicode_READY(unicode) == -1)
6763 return NULL;
6764 /* Fast path: if it is an ASCII-only string, construct bytes object
6765 directly. Else defer to above function to raise the exception. */
6766 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6767 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6768 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006769 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006770}
6771
6772PyObject *
6773PyUnicode_AsASCIIString(PyObject *unicode)
6774{
6775 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776}
6777
Victor Stinner99b95382011-07-04 14:23:54 +02006778#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006779
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006780/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006781
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006782#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006783#define NEED_RETRY
6784#endif
6785
Victor Stinner3a50e702011-10-18 21:21:00 +02006786#ifndef WC_ERR_INVALID_CHARS
6787# define WC_ERR_INVALID_CHARS 0x0080
6788#endif
6789
6790static char*
6791code_page_name(UINT code_page, PyObject **obj)
6792{
6793 *obj = NULL;
6794 if (code_page == CP_ACP)
6795 return "mbcs";
6796 if (code_page == CP_UTF7)
6797 return "CP_UTF7";
6798 if (code_page == CP_UTF8)
6799 return "CP_UTF8";
6800
6801 *obj = PyBytes_FromFormat("cp%u", code_page);
6802 if (*obj == NULL)
6803 return NULL;
6804 return PyBytes_AS_STRING(*obj);
6805}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006806
Alexander Belopolsky40018472011-02-26 01:02:56 +00006807static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006808is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006809{
6810 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006811 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006812
Victor Stinner3a50e702011-10-18 21:21:00 +02006813 if (!IsDBCSLeadByteEx(code_page, *curr))
6814 return 0;
6815
6816 prev = CharPrevExA(code_page, s, curr, 0);
6817 if (prev == curr)
6818 return 1;
6819 /* FIXME: This code is limited to "true" double-byte encodings,
6820 as it assumes an incomplete character consists of a single
6821 byte. */
6822 if (curr - prev == 2)
6823 return 1;
6824 if (!IsDBCSLeadByteEx(code_page, *prev))
6825 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006826 return 0;
6827}
6828
Victor Stinner3a50e702011-10-18 21:21:00 +02006829static DWORD
6830decode_code_page_flags(UINT code_page)
6831{
6832 if (code_page == CP_UTF7) {
6833 /* The CP_UTF7 decoder only supports flags=0 */
6834 return 0;
6835 }
6836 else
6837 return MB_ERR_INVALID_CHARS;
6838}
6839
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006840/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006841 * Decode a byte string from a Windows code page into unicode object in strict
6842 * mode.
6843 *
6844 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6845 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006846 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006847static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006848decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006849 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006850 const char *in,
6851 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006852{
Victor Stinner3a50e702011-10-18 21:21:00 +02006853 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006854 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006855 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006856
6857 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 assert(insize > 0);
6859 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6860 if (outsize <= 0)
6861 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006862
6863 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006864 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006865 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006866 if (*v == NULL)
6867 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006868 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869 }
6870 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006872 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006873 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006874 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006875 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006876 }
6877
6878 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006879 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6880 if (outsize <= 0)
6881 goto error;
6882 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006883
Victor Stinner3a50e702011-10-18 21:21:00 +02006884error:
6885 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6886 return -2;
6887 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006888 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006889}
6890
Victor Stinner3a50e702011-10-18 21:21:00 +02006891/*
6892 * Decode a byte string from a code page into unicode object with an error
6893 * handler.
6894 *
6895 * Returns consumed size if succeed, or raise a WindowsError or
6896 * UnicodeDecodeError exception and returns -1 on error.
6897 */
6898static int
6899decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006900 PyObject **v,
6901 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 const char *errors)
6903{
6904 const char *startin = in;
6905 const char *endin = in + size;
6906 const DWORD flags = decode_code_page_flags(code_page);
6907 /* Ideally, we should get reason from FormatMessage. This is the Windows
6908 2000 English version of the message. */
6909 const char *reason = "No mapping for the Unicode character exists "
6910 "in the target code page.";
6911 /* each step cannot decode more than 1 character, but a character can be
6912 represented as a surrogate pair */
6913 wchar_t buffer[2], *startout, *out;
6914 int insize, outsize;
6915 PyObject *errorHandler = NULL;
6916 PyObject *exc = NULL;
6917 PyObject *encoding_obj = NULL;
6918 char *encoding;
6919 DWORD err;
6920 int ret = -1;
6921
6922 assert(size > 0);
6923
6924 encoding = code_page_name(code_page, &encoding_obj);
6925 if (encoding == NULL)
6926 return -1;
6927
6928 if (errors == NULL || strcmp(errors, "strict") == 0) {
6929 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6930 UnicodeDecodeError. */
6931 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6932 if (exc != NULL) {
6933 PyCodec_StrictErrors(exc);
6934 Py_CLEAR(exc);
6935 }
6936 goto error;
6937 }
6938
6939 if (*v == NULL) {
6940 /* Create unicode object */
6941 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6942 PyErr_NoMemory();
6943 goto error;
6944 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006945 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006946 if (*v == NULL)
6947 goto error;
6948 startout = PyUnicode_AS_UNICODE(*v);
6949 }
6950 else {
6951 /* Extend unicode object */
6952 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6953 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6954 PyErr_NoMemory();
6955 goto error;
6956 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006957 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006958 goto error;
6959 startout = PyUnicode_AS_UNICODE(*v) + n;
6960 }
6961
6962 /* Decode the byte string character per character */
6963 out = startout;
6964 while (in < endin)
6965 {
6966 /* Decode a character */
6967 insize = 1;
6968 do
6969 {
6970 outsize = MultiByteToWideChar(code_page, flags,
6971 in, insize,
6972 buffer, Py_ARRAY_LENGTH(buffer));
6973 if (outsize > 0)
6974 break;
6975 err = GetLastError();
6976 if (err != ERROR_NO_UNICODE_TRANSLATION
6977 && err != ERROR_INSUFFICIENT_BUFFER)
6978 {
6979 PyErr_SetFromWindowsErr(0);
6980 goto error;
6981 }
6982 insize++;
6983 }
6984 /* 4=maximum length of a UTF-8 sequence */
6985 while (insize <= 4 && (in + insize) <= endin);
6986
6987 if (outsize <= 0) {
6988 Py_ssize_t startinpos, endinpos, outpos;
6989
6990 startinpos = in - startin;
6991 endinpos = startinpos + 1;
6992 outpos = out - PyUnicode_AS_UNICODE(*v);
6993 if (unicode_decode_call_errorhandler(
6994 errors, &errorHandler,
6995 encoding, reason,
6996 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006997 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006998 {
6999 goto error;
7000 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007001 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007002 }
7003 else {
7004 in += insize;
7005 memcpy(out, buffer, outsize * sizeof(wchar_t));
7006 out += outsize;
7007 }
7008 }
7009
7010 /* write a NUL character at the end */
7011 *out = 0;
7012
7013 /* Extend unicode object */
7014 outsize = out - startout;
7015 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007016 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007018 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007019
7020error:
7021 Py_XDECREF(encoding_obj);
7022 Py_XDECREF(errorHandler);
7023 Py_XDECREF(exc);
7024 return ret;
7025}
7026
Victor Stinner3a50e702011-10-18 21:21:00 +02007027static PyObject *
7028decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007029 const char *s, Py_ssize_t size,
7030 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031{
Victor Stinner76a31a62011-11-04 00:05:13 +01007032 PyObject *v = NULL;
7033 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 if (code_page < 0) {
7036 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7037 return NULL;
7038 }
7039
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007041 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007042
Victor Stinner76a31a62011-11-04 00:05:13 +01007043 do
7044 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007046 if (size > INT_MAX) {
7047 chunk_size = INT_MAX;
7048 final = 0;
7049 done = 0;
7050 }
7051 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007053 {
7054 chunk_size = (int)size;
7055 final = (consumed == NULL);
7056 done = 1;
7057 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007058
Victor Stinner76a31a62011-11-04 00:05:13 +01007059 /* Skip trailing lead-byte unless 'final' is set */
7060 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7061 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007062
Victor Stinner76a31a62011-11-04 00:05:13 +01007063 if (chunk_size == 0 && done) {
7064 if (v != NULL)
7065 break;
7066 Py_INCREF(unicode_empty);
7067 return unicode_empty;
7068 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069
Victor Stinner76a31a62011-11-04 00:05:13 +01007070
7071 converted = decode_code_page_strict(code_page, &v,
7072 s, chunk_size);
7073 if (converted == -2)
7074 converted = decode_code_page_errors(code_page, &v,
7075 s, chunk_size,
7076 errors);
7077 assert(converted != 0);
7078
7079 if (converted < 0) {
7080 Py_XDECREF(v);
7081 return NULL;
7082 }
7083
7084 if (consumed)
7085 *consumed += converted;
7086
7087 s += converted;
7088 size -= converted;
7089 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007090
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007091 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092}
7093
Alexander Belopolsky40018472011-02-26 01:02:56 +00007094PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007095PyUnicode_DecodeCodePageStateful(int code_page,
7096 const char *s,
7097 Py_ssize_t size,
7098 const char *errors,
7099 Py_ssize_t *consumed)
7100{
7101 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7102}
7103
7104PyObject *
7105PyUnicode_DecodeMBCSStateful(const char *s,
7106 Py_ssize_t size,
7107 const char *errors,
7108 Py_ssize_t *consumed)
7109{
7110 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7111}
7112
7113PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007114PyUnicode_DecodeMBCS(const char *s,
7115 Py_ssize_t size,
7116 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007117{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7119}
7120
Victor Stinner3a50e702011-10-18 21:21:00 +02007121static DWORD
7122encode_code_page_flags(UINT code_page, const char *errors)
7123{
7124 if (code_page == CP_UTF8) {
7125 if (winver.dwMajorVersion >= 6)
7126 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7127 and later */
7128 return WC_ERR_INVALID_CHARS;
7129 else
7130 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7131 return 0;
7132 }
7133 else if (code_page == CP_UTF7) {
7134 /* CP_UTF7 only supports flags=0 */
7135 return 0;
7136 }
7137 else {
7138 if (errors != NULL && strcmp(errors, "replace") == 0)
7139 return 0;
7140 else
7141 return WC_NO_BEST_FIT_CHARS;
7142 }
7143}
7144
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007145/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 * Encode a Unicode string to a Windows code page into a byte string in strict
7147 * mode.
7148 *
7149 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7150 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007151 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007152static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007153encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007154 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007156{
Victor Stinner554f3f02010-06-16 23:33:54 +00007157 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 BOOL *pusedDefaultChar = &usedDefaultChar;
7159 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007160 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007161 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007162 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 const DWORD flags = encode_code_page_flags(code_page, NULL);
7164 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007165 /* Create a substring so that we can get the UTF-16 representation
7166 of just the slice under consideration. */
7167 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007168
Martin v. Löwis3d325192011-11-04 18:23:06 +01007169 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007170
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007172 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007174 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007175
Victor Stinner2fc507f2011-11-04 20:06:39 +01007176 substring = PyUnicode_Substring(unicode, offset, offset+len);
7177 if (substring == NULL)
7178 return -1;
7179 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7180 if (p == NULL) {
7181 Py_DECREF(substring);
7182 return -1;
7183 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007184
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007185 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 outsize = WideCharToMultiByte(code_page, flags,
7187 p, size,
7188 NULL, 0,
7189 NULL, pusedDefaultChar);
7190 if (outsize <= 0)
7191 goto error;
7192 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007193 if (pusedDefaultChar && *pusedDefaultChar) {
7194 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007196 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007197
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007199 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007200 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007201 if (*outbytes == NULL) {
7202 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007203 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007204 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007206 }
7207 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007208 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 const Py_ssize_t n = PyBytes_Size(*outbytes);
7210 if (outsize > PY_SSIZE_T_MAX - n) {
7211 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007212 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007213 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007215 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7216 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007218 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007220 }
7221
7222 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 outsize = WideCharToMultiByte(code_page, flags,
7224 p, size,
7225 out, outsize,
7226 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007227 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 if (outsize <= 0)
7229 goto error;
7230 if (pusedDefaultChar && *pusedDefaultChar)
7231 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007232 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007233
Victor Stinner3a50e702011-10-18 21:21:00 +02007234error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007235 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7237 return -2;
7238 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007239 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007240}
7241
Victor Stinner3a50e702011-10-18 21:21:00 +02007242/*
7243 * Encode a Unicode string to a Windows code page into a byte string using a
7244 * error handler.
7245 *
7246 * Returns consumed characters if succeed, or raise a WindowsError and returns
7247 * -1 on other error.
7248 */
7249static int
7250encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007251 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007252 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007253{
Victor Stinner3a50e702011-10-18 21:21:00 +02007254 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007255 Py_ssize_t pos = unicode_offset;
7256 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007257 /* Ideally, we should get reason from FormatMessage. This is the Windows
7258 2000 English version of the message. */
7259 const char *reason = "invalid character";
7260 /* 4=maximum length of a UTF-8 sequence */
7261 char buffer[4];
7262 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7263 Py_ssize_t outsize;
7264 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 PyObject *errorHandler = NULL;
7266 PyObject *exc = NULL;
7267 PyObject *encoding_obj = NULL;
7268 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007269 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 PyObject *rep;
7271 int ret = -1;
7272
7273 assert(insize > 0);
7274
7275 encoding = code_page_name(code_page, &encoding_obj);
7276 if (encoding == NULL)
7277 return -1;
7278
7279 if (errors == NULL || strcmp(errors, "strict") == 0) {
7280 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7281 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007282 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 if (exc != NULL) {
7284 PyCodec_StrictErrors(exc);
7285 Py_DECREF(exc);
7286 }
7287 Py_XDECREF(encoding_obj);
7288 return -1;
7289 }
7290
7291 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7292 pusedDefaultChar = &usedDefaultChar;
7293 else
7294 pusedDefaultChar = NULL;
7295
7296 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7297 PyErr_NoMemory();
7298 goto error;
7299 }
7300 outsize = insize * Py_ARRAY_LENGTH(buffer);
7301
7302 if (*outbytes == NULL) {
7303 /* Create string object */
7304 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7305 if (*outbytes == NULL)
7306 goto error;
7307 out = PyBytes_AS_STRING(*outbytes);
7308 }
7309 else {
7310 /* Extend string object */
7311 Py_ssize_t n = PyBytes_Size(*outbytes);
7312 if (n > PY_SSIZE_T_MAX - outsize) {
7313 PyErr_NoMemory();
7314 goto error;
7315 }
7316 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7317 goto error;
7318 out = PyBytes_AS_STRING(*outbytes) + n;
7319 }
7320
7321 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007322 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007323 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007324 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7325 wchar_t chars[2];
7326 int charsize;
7327 if (ch < 0x10000) {
7328 chars[0] = (wchar_t)ch;
7329 charsize = 1;
7330 }
7331 else {
7332 ch -= 0x10000;
7333 chars[0] = 0xd800 + (ch >> 10);
7334 chars[1] = 0xdc00 + (ch & 0x3ff);
7335 charsize = 2;
7336 }
7337
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007339 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007340 buffer, Py_ARRAY_LENGTH(buffer),
7341 NULL, pusedDefaultChar);
7342 if (outsize > 0) {
7343 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7344 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007345 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007346 memcpy(out, buffer, outsize);
7347 out += outsize;
7348 continue;
7349 }
7350 }
7351 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7352 PyErr_SetFromWindowsErr(0);
7353 goto error;
7354 }
7355
Victor Stinner3a50e702011-10-18 21:21:00 +02007356 rep = unicode_encode_call_errorhandler(
7357 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007358 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007360 if (rep == NULL)
7361 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007362 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007363
7364 if (PyBytes_Check(rep)) {
7365 outsize = PyBytes_GET_SIZE(rep);
7366 if (outsize != 1) {
7367 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7368 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7369 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7370 Py_DECREF(rep);
7371 goto error;
7372 }
7373 out = PyBytes_AS_STRING(*outbytes) + offset;
7374 }
7375 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7376 out += outsize;
7377 }
7378 else {
7379 Py_ssize_t i;
7380 enum PyUnicode_Kind kind;
7381 void *data;
7382
7383 if (PyUnicode_READY(rep) < 0) {
7384 Py_DECREF(rep);
7385 goto error;
7386 }
7387
7388 outsize = PyUnicode_GET_LENGTH(rep);
7389 if (outsize != 1) {
7390 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7391 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7392 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7393 Py_DECREF(rep);
7394 goto error;
7395 }
7396 out = PyBytes_AS_STRING(*outbytes) + offset;
7397 }
7398 kind = PyUnicode_KIND(rep);
7399 data = PyUnicode_DATA(rep);
7400 for (i=0; i < outsize; i++) {
7401 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7402 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007403 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007404 encoding, unicode,
7405 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 "unable to encode error handler result to ASCII");
7407 Py_DECREF(rep);
7408 goto error;
7409 }
7410 *out = (unsigned char)ch;
7411 out++;
7412 }
7413 }
7414 Py_DECREF(rep);
7415 }
7416 /* write a NUL byte */
7417 *out = 0;
7418 outsize = out - PyBytes_AS_STRING(*outbytes);
7419 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7420 if (_PyBytes_Resize(outbytes, outsize) < 0)
7421 goto error;
7422 ret = 0;
7423
7424error:
7425 Py_XDECREF(encoding_obj);
7426 Py_XDECREF(errorHandler);
7427 Py_XDECREF(exc);
7428 return ret;
7429}
7430
Victor Stinner3a50e702011-10-18 21:21:00 +02007431static PyObject *
7432encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007433 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 const char *errors)
7435{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007436 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007438 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007439 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007440
Victor Stinner2fc507f2011-11-04 20:06:39 +01007441 if (PyUnicode_READY(unicode) < 0)
7442 return NULL;
7443 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007444
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 if (code_page < 0) {
7446 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7447 return NULL;
7448 }
7449
Martin v. Löwis3d325192011-11-04 18:23:06 +01007450 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007451 return PyBytes_FromStringAndSize(NULL, 0);
7452
Victor Stinner7581cef2011-11-03 22:32:33 +01007453 offset = 0;
7454 do
7455 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007456#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007458 chunks. */
7459 if (len > INT_MAX/2) {
7460 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007461 done = 0;
7462 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007463 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007464#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007465 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007466 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007467 done = 1;
7468 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007469
Victor Stinner76a31a62011-11-04 00:05:13 +01007470 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007471 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007472 errors);
7473 if (ret == -2)
7474 ret = encode_code_page_errors(code_page, &outbytes,
7475 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007476 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007477 if (ret < 0) {
7478 Py_XDECREF(outbytes);
7479 return NULL;
7480 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007481
Victor Stinner7581cef2011-11-03 22:32:33 +01007482 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007483 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007484 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007485
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 return outbytes;
7487}
7488
7489PyObject *
7490PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7491 Py_ssize_t size,
7492 const char *errors)
7493{
Victor Stinner7581cef2011-11-03 22:32:33 +01007494 PyObject *unicode, *res;
7495 unicode = PyUnicode_FromUnicode(p, size);
7496 if (unicode == NULL)
7497 return NULL;
7498 res = encode_code_page(CP_ACP, unicode, errors);
7499 Py_DECREF(unicode);
7500 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007501}
7502
7503PyObject *
7504PyUnicode_EncodeCodePage(int code_page,
7505 PyObject *unicode,
7506 const char *errors)
7507{
Victor Stinner7581cef2011-11-03 22:32:33 +01007508 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007509}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007510
Alexander Belopolsky40018472011-02-26 01:02:56 +00007511PyObject *
7512PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007513{
7514 if (!PyUnicode_Check(unicode)) {
7515 PyErr_BadArgument();
7516 return NULL;
7517 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007518 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007519}
7520
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007521#undef NEED_RETRY
7522
Victor Stinner99b95382011-07-04 14:23:54 +02007523#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007524
Guido van Rossumd57fd912000-03-10 22:53:23 +00007525/* --- Character Mapping Codec -------------------------------------------- */
7526
Alexander Belopolsky40018472011-02-26 01:02:56 +00007527PyObject *
7528PyUnicode_DecodeCharmap(const char *s,
7529 Py_ssize_t size,
7530 PyObject *mapping,
7531 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007532{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007533 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007534 Py_ssize_t startinpos;
7535 Py_ssize_t endinpos;
7536 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007537 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007538 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007539 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007540 PyObject *errorHandler = NULL;
7541 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007542
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543 /* Default to Latin-1 */
7544 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007545 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007546
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007547 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007548 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007549 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007550 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007551 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007552 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007553 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007554 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007555 Py_ssize_t maplen;
7556 enum PyUnicode_Kind kind;
7557 void *data;
7558 Py_UCS4 x;
7559
7560 if (PyUnicode_READY(mapping) < 0)
7561 return NULL;
7562
7563 maplen = PyUnicode_GET_LENGTH(mapping);
7564 data = PyUnicode_DATA(mapping);
7565 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007566 while (s < e) {
7567 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007568
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007570 x = PyUnicode_READ(kind, data, ch);
7571 else
7572 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007573
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007574 if (x == 0xfffe)
7575 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007576 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007577 startinpos = s-starts;
7578 endinpos = startinpos+1;
7579 if (unicode_decode_call_errorhandler(
7580 errors, &errorHandler,
7581 "charmap", "character maps to <undefined>",
7582 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007583 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 goto onError;
7585 }
7586 continue;
7587 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007588
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007589 if (unicode_putchar(&v, &outpos, x) < 0)
7590 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007592 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007593 }
7594 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007595 while (s < e) {
7596 unsigned char ch = *s;
7597 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007598
Benjamin Peterson29060642009-01-31 22:14:21 +00007599 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7600 w = PyLong_FromLong((long)ch);
7601 if (w == NULL)
7602 goto onError;
7603 x = PyObject_GetItem(mapping, w);
7604 Py_DECREF(w);
7605 if (x == NULL) {
7606 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7607 /* No mapping found means: mapping is undefined. */
7608 PyErr_Clear();
7609 x = Py_None;
7610 Py_INCREF(x);
7611 } else
7612 goto onError;
7613 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007614
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 /* Apply mapping */
7616 if (PyLong_Check(x)) {
7617 long value = PyLong_AS_LONG(x);
7618 if (value < 0 || value > 65535) {
7619 PyErr_SetString(PyExc_TypeError,
7620 "character mapping must be in range(65536)");
7621 Py_DECREF(x);
7622 goto onError;
7623 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007624 if (unicode_putchar(&v, &outpos, value) < 0)
7625 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 }
7627 else if (x == Py_None) {
7628 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007629 startinpos = s-starts;
7630 endinpos = startinpos+1;
7631 if (unicode_decode_call_errorhandler(
7632 errors, &errorHandler,
7633 "charmap", "character maps to <undefined>",
7634 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007635 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 Py_DECREF(x);
7637 goto onError;
7638 }
7639 Py_DECREF(x);
7640 continue;
7641 }
7642 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007643 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007644
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007645 if (PyUnicode_READY(x) < 0)
7646 goto onError;
7647 targetsize = PyUnicode_GET_LENGTH(x);
7648
7649 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007651 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007652 PyUnicode_READ_CHAR(x, 0)) < 0)
7653 goto onError;
7654 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 else if (targetsize > 1) {
7656 /* 1-n mapping */
7657 if (targetsize > extrachars) {
7658 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 Py_ssize_t needed = (targetsize - extrachars) + \
7660 (targetsize << 2);
7661 extrachars += needed;
7662 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007663 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007664 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007665 Py_DECREF(x);
7666 goto onError;
7667 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007668 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007669 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7670 goto onError;
7671 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7672 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007673 extrachars -= targetsize;
7674 }
7675 /* 1-0 mapping: skip the character */
7676 }
7677 else {
7678 /* wrong return value */
7679 PyErr_SetString(PyExc_TypeError,
7680 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007681 Py_DECREF(x);
7682 goto onError;
7683 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007684 Py_DECREF(x);
7685 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007686 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007687 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007688 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007689 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007690 Py_XDECREF(errorHandler);
7691 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007692 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007693
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007695 Py_XDECREF(errorHandler);
7696 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007697 Py_XDECREF(v);
7698 return NULL;
7699}
7700
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701/* Charmap encoding: the lookup table */
7702
Alexander Belopolsky40018472011-02-26 01:02:56 +00007703struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007704 PyObject_HEAD
7705 unsigned char level1[32];
7706 int count2, count3;
7707 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007708};
7709
7710static PyObject*
7711encoding_map_size(PyObject *obj, PyObject* args)
7712{
7713 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007714 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007715 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007716}
7717
7718static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007719 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 PyDoc_STR("Return the size (in bytes) of this object") },
7721 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007722};
7723
7724static void
7725encoding_map_dealloc(PyObject* o)
7726{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007727 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007728}
7729
7730static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007731 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007732 "EncodingMap", /*tp_name*/
7733 sizeof(struct encoding_map), /*tp_basicsize*/
7734 0, /*tp_itemsize*/
7735 /* methods */
7736 encoding_map_dealloc, /*tp_dealloc*/
7737 0, /*tp_print*/
7738 0, /*tp_getattr*/
7739 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007740 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 0, /*tp_repr*/
7742 0, /*tp_as_number*/
7743 0, /*tp_as_sequence*/
7744 0, /*tp_as_mapping*/
7745 0, /*tp_hash*/
7746 0, /*tp_call*/
7747 0, /*tp_str*/
7748 0, /*tp_getattro*/
7749 0, /*tp_setattro*/
7750 0, /*tp_as_buffer*/
7751 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7752 0, /*tp_doc*/
7753 0, /*tp_traverse*/
7754 0, /*tp_clear*/
7755 0, /*tp_richcompare*/
7756 0, /*tp_weaklistoffset*/
7757 0, /*tp_iter*/
7758 0, /*tp_iternext*/
7759 encoding_map_methods, /*tp_methods*/
7760 0, /*tp_members*/
7761 0, /*tp_getset*/
7762 0, /*tp_base*/
7763 0, /*tp_dict*/
7764 0, /*tp_descr_get*/
7765 0, /*tp_descr_set*/
7766 0, /*tp_dictoffset*/
7767 0, /*tp_init*/
7768 0, /*tp_alloc*/
7769 0, /*tp_new*/
7770 0, /*tp_free*/
7771 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007772};
7773
7774PyObject*
7775PyUnicode_BuildEncodingMap(PyObject* string)
7776{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007777 PyObject *result;
7778 struct encoding_map *mresult;
7779 int i;
7780 int need_dict = 0;
7781 unsigned char level1[32];
7782 unsigned char level2[512];
7783 unsigned char *mlevel1, *mlevel2, *mlevel3;
7784 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007785 int kind;
7786 void *data;
7787 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007789 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007790 PyErr_BadArgument();
7791 return NULL;
7792 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007793 kind = PyUnicode_KIND(string);
7794 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007795 memset(level1, 0xFF, sizeof level1);
7796 memset(level2, 0xFF, sizeof level2);
7797
7798 /* If there isn't a one-to-one mapping of NULL to \0,
7799 or if there are non-BMP characters, we need to use
7800 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007801 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007802 need_dict = 1;
7803 for (i = 1; i < 256; i++) {
7804 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007805 ch = PyUnicode_READ(kind, data, i);
7806 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007807 need_dict = 1;
7808 break;
7809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007810 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007811 /* unmapped character */
7812 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007813 l1 = ch >> 11;
7814 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007815 if (level1[l1] == 0xFF)
7816 level1[l1] = count2++;
7817 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007818 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007819 }
7820
7821 if (count2 >= 0xFF || count3 >= 0xFF)
7822 need_dict = 1;
7823
7824 if (need_dict) {
7825 PyObject *result = PyDict_New();
7826 PyObject *key, *value;
7827 if (!result)
7828 return NULL;
7829 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007830 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007831 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007832 if (!key || !value)
7833 goto failed1;
7834 if (PyDict_SetItem(result, key, value) == -1)
7835 goto failed1;
7836 Py_DECREF(key);
7837 Py_DECREF(value);
7838 }
7839 return result;
7840 failed1:
7841 Py_XDECREF(key);
7842 Py_XDECREF(value);
7843 Py_DECREF(result);
7844 return NULL;
7845 }
7846
7847 /* Create a three-level trie */
7848 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7849 16*count2 + 128*count3 - 1);
7850 if (!result)
7851 return PyErr_NoMemory();
7852 PyObject_Init(result, &EncodingMapType);
7853 mresult = (struct encoding_map*)result;
7854 mresult->count2 = count2;
7855 mresult->count3 = count3;
7856 mlevel1 = mresult->level1;
7857 mlevel2 = mresult->level23;
7858 mlevel3 = mresult->level23 + 16*count2;
7859 memcpy(mlevel1, level1, 32);
7860 memset(mlevel2, 0xFF, 16*count2);
7861 memset(mlevel3, 0, 128*count3);
7862 count3 = 0;
7863 for (i = 1; i < 256; i++) {
7864 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007865 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007866 /* unmapped character */
7867 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007868 o1 = PyUnicode_READ(kind, data, i)>>11;
7869 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870 i2 = 16*mlevel1[o1] + o2;
7871 if (mlevel2[i2] == 0xFF)
7872 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007873 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874 i3 = 128*mlevel2[i2] + o3;
7875 mlevel3[i3] = i;
7876 }
7877 return result;
7878}
7879
7880static int
Victor Stinner22168992011-11-20 17:09:18 +01007881encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882{
7883 struct encoding_map *map = (struct encoding_map*)mapping;
7884 int l1 = c>>11;
7885 int l2 = (c>>7) & 0xF;
7886 int l3 = c & 0x7F;
7887 int i;
7888
Victor Stinner22168992011-11-20 17:09:18 +01007889 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007891 if (c == 0)
7892 return 0;
7893 /* level 1*/
7894 i = map->level1[l1];
7895 if (i == 0xFF) {
7896 return -1;
7897 }
7898 /* level 2*/
7899 i = map->level23[16*i+l2];
7900 if (i == 0xFF) {
7901 return -1;
7902 }
7903 /* level 3 */
7904 i = map->level23[16*map->count2 + 128*i + l3];
7905 if (i == 0) {
7906 return -1;
7907 }
7908 return i;
7909}
7910
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007911/* Lookup the character ch in the mapping. If the character
7912 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007913 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007914static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007915charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007916{
Christian Heimes217cfd12007-12-02 14:31:20 +00007917 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007918 PyObject *x;
7919
7920 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007921 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007922 x = PyObject_GetItem(mapping, w);
7923 Py_DECREF(w);
7924 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7926 /* No mapping found means: mapping is undefined. */
7927 PyErr_Clear();
7928 x = Py_None;
7929 Py_INCREF(x);
7930 return x;
7931 } else
7932 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007933 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007934 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007935 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007936 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 long value = PyLong_AS_LONG(x);
7938 if (value < 0 || value > 255) {
7939 PyErr_SetString(PyExc_TypeError,
7940 "character mapping must be in range(256)");
7941 Py_DECREF(x);
7942 return NULL;
7943 }
7944 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007945 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007946 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007948 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007949 /* wrong return value */
7950 PyErr_Format(PyExc_TypeError,
7951 "character mapping must return integer, bytes or None, not %.400s",
7952 x->ob_type->tp_name);
7953 Py_DECREF(x);
7954 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007955 }
7956}
7957
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007958static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007959charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007960{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007961 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7962 /* exponentially overallocate to minimize reallocations */
7963 if (requiredsize < 2*outsize)
7964 requiredsize = 2*outsize;
7965 if (_PyBytes_Resize(outobj, requiredsize))
7966 return -1;
7967 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007968}
7969
Benjamin Peterson14339b62009-01-31 16:36:08 +00007970typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007972} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007973/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007974 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007975 space is available. Return a new reference to the object that
7976 was put in the output buffer, or Py_None, if the mapping was undefined
7977 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007978 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007979static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007980charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007982{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007983 PyObject *rep;
7984 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007985 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007986
Christian Heimes90aa7642007-12-19 02:45:37 +00007987 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007988 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007990 if (res == -1)
7991 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 if (outsize<requiredsize)
7993 if (charmapencode_resize(outobj, outpos, requiredsize))
7994 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007995 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007996 outstart[(*outpos)++] = (char)res;
7997 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007998 }
7999
8000 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008001 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008002 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008003 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 Py_DECREF(rep);
8005 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008006 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008007 if (PyLong_Check(rep)) {
8008 Py_ssize_t requiredsize = *outpos+1;
8009 if (outsize<requiredsize)
8010 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8011 Py_DECREF(rep);
8012 return enc_EXCEPTION;
8013 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008014 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008016 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 else {
8018 const char *repchars = PyBytes_AS_STRING(rep);
8019 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8020 Py_ssize_t requiredsize = *outpos+repsize;
8021 if (outsize<requiredsize)
8022 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8023 Py_DECREF(rep);
8024 return enc_EXCEPTION;
8025 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008026 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 memcpy(outstart + *outpos, repchars, repsize);
8028 *outpos += repsize;
8029 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008030 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008031 Py_DECREF(rep);
8032 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008033}
8034
8035/* handle an error in PyUnicode_EncodeCharmap
8036 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008037static int
8038charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008039 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008040 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008041 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008042 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043{
8044 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008045 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008046 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008047 enum PyUnicode_Kind kind;
8048 void *data;
8049 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008050 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008051 Py_ssize_t collstartpos = *inpos;
8052 Py_ssize_t collendpos = *inpos+1;
8053 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008054 char *encoding = "charmap";
8055 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008056 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008057 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008058 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008059
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008060 if (PyUnicode_READY(unicode) < 0)
8061 return -1;
8062 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008063 /* find all unencodable characters */
8064 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008066 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008067 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008068 val = encoding_map_lookup(ch, mapping);
8069 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008070 break;
8071 ++collendpos;
8072 continue;
8073 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008074
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008075 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8076 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 if (rep==NULL)
8078 return -1;
8079 else if (rep!=Py_None) {
8080 Py_DECREF(rep);
8081 break;
8082 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008083 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085 }
8086 /* cache callback name lookup
8087 * (if not done yet, i.e. it's the first error) */
8088 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 if ((errors==NULL) || (!strcmp(errors, "strict")))
8090 *known_errorHandler = 1;
8091 else if (!strcmp(errors, "replace"))
8092 *known_errorHandler = 2;
8093 else if (!strcmp(errors, "ignore"))
8094 *known_errorHandler = 3;
8095 else if (!strcmp(errors, "xmlcharrefreplace"))
8096 *known_errorHandler = 4;
8097 else
8098 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008099 }
8100 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008101 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008102 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008103 return -1;
8104 case 2: /* replace */
8105 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 x = charmapencode_output('?', mapping, res, respos);
8107 if (x==enc_EXCEPTION) {
8108 return -1;
8109 }
8110 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008111 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 return -1;
8113 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008114 }
8115 /* fall through */
8116 case 3: /* ignore */
8117 *inpos = collendpos;
8118 break;
8119 case 4: /* xmlcharrefreplace */
8120 /* generate replacement (temporarily (mis)uses p) */
8121 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 char buffer[2+29+1+1];
8123 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008124 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008125 for (cp = buffer; *cp; ++cp) {
8126 x = charmapencode_output(*cp, mapping, res, respos);
8127 if (x==enc_EXCEPTION)
8128 return -1;
8129 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008130 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 return -1;
8132 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008133 }
8134 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008135 *inpos = collendpos;
8136 break;
8137 default:
8138 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008139 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008140 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008143 if (PyBytes_Check(repunicode)) {
8144 /* Directly copy bytes result to output. */
8145 Py_ssize_t outsize = PyBytes_Size(*res);
8146 Py_ssize_t requiredsize;
8147 repsize = PyBytes_Size(repunicode);
8148 requiredsize = *respos + repsize;
8149 if (requiredsize > outsize)
8150 /* Make room for all additional bytes. */
8151 if (charmapencode_resize(res, respos, requiredsize)) {
8152 Py_DECREF(repunicode);
8153 return -1;
8154 }
8155 memcpy(PyBytes_AsString(*res) + *respos,
8156 PyBytes_AsString(repunicode), repsize);
8157 *respos += repsize;
8158 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008159 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008160 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008161 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008162 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008163 if (PyUnicode_READY(repunicode) < 0) {
8164 Py_DECREF(repunicode);
8165 return -1;
8166 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008167 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008168 data = PyUnicode_DATA(repunicode);
8169 kind = PyUnicode_KIND(repunicode);
8170 for (index = 0; index < repsize; index++) {
8171 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8172 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008174 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 return -1;
8176 }
8177 else if (x==enc_FAILED) {
8178 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008179 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 return -1;
8181 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008182 }
8183 *inpos = newpos;
8184 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008185 }
8186 return 0;
8187}
8188
Alexander Belopolsky40018472011-02-26 01:02:56 +00008189PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008190_PyUnicode_EncodeCharmap(PyObject *unicode,
8191 PyObject *mapping,
8192 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008194 /* output object */
8195 PyObject *res = NULL;
8196 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008197 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008200 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008201 PyObject *errorHandler = NULL;
8202 PyObject *exc = NULL;
8203 /* the following variable is used for caching string comparisons
8204 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8205 * 3=ignore, 4=xmlcharrefreplace */
8206 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008207
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008208 if (PyUnicode_READY(unicode) < 0)
8209 return NULL;
8210 size = PyUnicode_GET_LENGTH(unicode);
8211
Guido van Rossumd57fd912000-03-10 22:53:23 +00008212 /* Default to Latin-1 */
8213 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008214 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216 /* allocate enough for a simple encoding without
8217 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008218 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008219 if (res == NULL)
8220 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008221 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008223
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008225 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008227 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 if (x==enc_EXCEPTION) /* error */
8229 goto onError;
8230 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008231 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 &exc,
8233 &known_errorHandler, &errorHandler, errors,
8234 &res, &respos)) {
8235 goto onError;
8236 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008237 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 else
8239 /* done with this character => adjust input position */
8240 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008241 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008242
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008244 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008245 if (_PyBytes_Resize(&res, respos) < 0)
8246 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008247
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008248 Py_XDECREF(exc);
8249 Py_XDECREF(errorHandler);
8250 return res;
8251
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253 Py_XDECREF(res);
8254 Py_XDECREF(exc);
8255 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008256 return NULL;
8257}
8258
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008259/* Deprecated */
8260PyObject *
8261PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8262 Py_ssize_t size,
8263 PyObject *mapping,
8264 const char *errors)
8265{
8266 PyObject *result;
8267 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8268 if (unicode == NULL)
8269 return NULL;
8270 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8271 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008272 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008273}
8274
Alexander Belopolsky40018472011-02-26 01:02:56 +00008275PyObject *
8276PyUnicode_AsCharmapString(PyObject *unicode,
8277 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278{
8279 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 PyErr_BadArgument();
8281 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008282 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008283 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008284}
8285
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008286/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008287static void
8288make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008289 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008290 Py_ssize_t startpos, Py_ssize_t endpos,
8291 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008292{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008294 *exceptionObject = _PyUnicodeTranslateError_Create(
8295 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296 }
8297 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8299 goto onError;
8300 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8301 goto onError;
8302 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8303 goto onError;
8304 return;
8305 onError:
8306 Py_DECREF(*exceptionObject);
8307 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008308 }
8309}
8310
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008311/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008312static void
8313raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008314 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008315 Py_ssize_t startpos, Py_ssize_t endpos,
8316 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317{
8318 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008319 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322}
8323
8324/* error handling callback helper:
8325 build arguments, call the callback and check the arguments,
8326 put the result into newpos and return the replacement string, which
8327 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008328static PyObject *
8329unicode_translate_call_errorhandler(const char *errors,
8330 PyObject **errorHandler,
8331 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008332 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008333 Py_ssize_t startpos, Py_ssize_t endpos,
8334 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008336 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008338 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339 PyObject *restuple;
8340 PyObject *resunicode;
8341
8342 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 }
8347
8348 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008349 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352
8353 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008358 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008359 Py_DECREF(restuple);
8360 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361 }
8362 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 &resunicode, &i_newpos)) {
8364 Py_DECREF(restuple);
8365 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008367 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008368 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008369 else
8370 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008371 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8373 Py_DECREF(restuple);
8374 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008375 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 Py_INCREF(resunicode);
8377 Py_DECREF(restuple);
8378 return resunicode;
8379}
8380
8381/* Lookup the character ch in the mapping and put the result in result,
8382 which must be decrefed by the caller.
8383 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008384static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386{
Christian Heimes217cfd12007-12-02 14:31:20 +00008387 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 PyObject *x;
8389
8390 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 x = PyObject_GetItem(mapping, w);
8393 Py_DECREF(w);
8394 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8396 /* No mapping found means: use 1:1 mapping. */
8397 PyErr_Clear();
8398 *result = NULL;
8399 return 0;
8400 } else
8401 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 }
8403 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 *result = x;
8405 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008406 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008407 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 long value = PyLong_AS_LONG(x);
8409 long max = PyUnicode_GetMax();
8410 if (value < 0 || value > max) {
8411 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008412 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 Py_DECREF(x);
8414 return -1;
8415 }
8416 *result = x;
8417 return 0;
8418 }
8419 else if (PyUnicode_Check(x)) {
8420 *result = x;
8421 return 0;
8422 }
8423 else {
8424 /* wrong return value */
8425 PyErr_SetString(PyExc_TypeError,
8426 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008427 Py_DECREF(x);
8428 return -1;
8429 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430}
8431/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 if not reallocate and adjust various state variables.
8433 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008434static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008437{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008439 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 /* exponentially overallocate to minimize reallocations */
8441 if (requiredsize < 2 * oldsize)
8442 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008443 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8444 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008446 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008447 }
8448 return 0;
8449}
8450/* lookup the character, put the result in the output string and adjust
8451 various state variables. Return a new reference to the object that
8452 was put in the output buffer in *result, or Py_None, if the mapping was
8453 undefined (in which case no character was written).
8454 The called must decref result.
8455 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008456static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8458 PyObject *mapping, Py_UCS4 **output,
8459 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008460 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8463 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 }
8469 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008471 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008473 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 }
8475 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008476 Py_ssize_t repsize;
8477 if (PyUnicode_READY(*res) == -1)
8478 return -1;
8479 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 if (repsize==1) {
8481 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008482 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 }
8484 else if (repsize!=0) {
8485 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008486 Py_ssize_t requiredsize = *opos +
8487 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 Py_ssize_t i;
8490 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 for(i = 0; i < repsize; i++)
8493 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495 }
8496 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 return 0;
8499}
8500
Alexander Belopolsky40018472011-02-26 01:02:56 +00008501PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502_PyUnicode_TranslateCharmap(PyObject *input,
8503 PyObject *mapping,
8504 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506 /* input object */
8507 char *idata;
8508 Py_ssize_t size, i;
8509 int kind;
8510 /* output buffer */
8511 Py_UCS4 *output = NULL;
8512 Py_ssize_t osize;
8513 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 char *reason = "character maps to <undefined>";
8517 PyObject *errorHandler = NULL;
8518 PyObject *exc = NULL;
8519 /* the following variable is used for caching string comparisons
8520 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8521 * 3=ignore, 4=xmlcharrefreplace */
8522 int known_errorHandler = -1;
8523
Guido van Rossumd57fd912000-03-10 22:53:23 +00008524 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 PyErr_BadArgument();
8526 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008527 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008529 if (PyUnicode_READY(input) == -1)
8530 return NULL;
8531 idata = (char*)PyUnicode_DATA(input);
8532 kind = PyUnicode_KIND(input);
8533 size = PyUnicode_GET_LENGTH(input);
8534 i = 0;
8535
8536 if (size == 0) {
8537 Py_INCREF(input);
8538 return input;
8539 }
8540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 /* allocate enough for a simple 1:1 translation without
8542 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008543 osize = size;
8544 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8545 opos = 0;
8546 if (output == NULL) {
8547 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 /* try to encode it */
8553 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 if (charmaptranslate_output(input, i, mapping,
8555 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 Py_XDECREF(x);
8557 goto onError;
8558 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008559 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008561 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 else { /* untranslatable character */
8563 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8564 Py_ssize_t repsize;
8565 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568 Py_ssize_t collstart = i;
8569 Py_ssize_t collend = i+1;
8570 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008571
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 while (collend < size) {
8574 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 goto onError;
8576 Py_XDECREF(x);
8577 if (x!=Py_None)
8578 break;
8579 ++collend;
8580 }
8581 /* cache callback name lookup
8582 * (if not done yet, i.e. it's the first error) */
8583 if (known_errorHandler==-1) {
8584 if ((errors==NULL) || (!strcmp(errors, "strict")))
8585 known_errorHandler = 1;
8586 else if (!strcmp(errors, "replace"))
8587 known_errorHandler = 2;
8588 else if (!strcmp(errors, "ignore"))
8589 known_errorHandler = 3;
8590 else if (!strcmp(errors, "xmlcharrefreplace"))
8591 known_errorHandler = 4;
8592 else
8593 known_errorHandler = 0;
8594 }
8595 switch (known_errorHandler) {
8596 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 raise_translate_exception(&exc, input, collstart,
8598 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008599 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 case 2: /* replace */
8601 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 for (coll = collstart; coll<collend; coll++)
8603 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 /* fall through */
8605 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008607 break;
8608 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 /* generate replacement (temporarily (mis)uses i) */
8610 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 char buffer[2+29+1+1];
8612 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8614 if (charmaptranslate_makespace(&output, &osize,
8615 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 goto onError;
8617 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 break;
8622 default:
8623 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624 reason, input, &exc,
8625 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008626 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008628 if (PyUnicode_READY(repunicode) < 0) {
8629 Py_DECREF(repunicode);
8630 goto onError;
8631 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 repsize = PyUnicode_GET_LENGTH(repunicode);
8634 if (charmaptranslate_makespace(&output, &osize,
8635 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 Py_DECREF(repunicode);
8637 goto onError;
8638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 for (uni2 = 0; repsize-->0; ++uni2)
8640 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8641 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008643 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008644 }
8645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8647 if (!res)
8648 goto onError;
8649 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 Py_XDECREF(exc);
8651 Py_XDECREF(errorHandler);
8652 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008653
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008656 Py_XDECREF(exc);
8657 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008658 return NULL;
8659}
8660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661/* Deprecated. Use PyUnicode_Translate instead. */
8662PyObject *
8663PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8664 Py_ssize_t size,
8665 PyObject *mapping,
8666 const char *errors)
8667{
8668 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8669 if (!unicode)
8670 return NULL;
8671 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8672}
8673
Alexander Belopolsky40018472011-02-26 01:02:56 +00008674PyObject *
8675PyUnicode_Translate(PyObject *str,
8676 PyObject *mapping,
8677 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008678{
8679 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008680
Guido van Rossumd57fd912000-03-10 22:53:23 +00008681 str = PyUnicode_FromObject(str);
8682 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008685 Py_DECREF(str);
8686 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008687
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689 Py_XDECREF(str);
8690 return NULL;
8691}
Tim Petersced69f82003-09-16 20:30:58 +00008692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008694fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695{
8696 /* No need to call PyUnicode_READY(self) because this function is only
8697 called as a callback from fixup() which does it already. */
8698 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8699 const int kind = PyUnicode_KIND(self);
8700 void *data = PyUnicode_DATA(self);
8701 Py_UCS4 maxchar = 0, ch, fixed;
8702 Py_ssize_t i;
8703
8704 for (i = 0; i < len; ++i) {
8705 ch = PyUnicode_READ(kind, data, i);
8706 fixed = 0;
8707 if (ch > 127) {
8708 if (Py_UNICODE_ISSPACE(ch))
8709 fixed = ' ';
8710 else {
8711 const int decimal = Py_UNICODE_TODECIMAL(ch);
8712 if (decimal >= 0)
8713 fixed = '0' + decimal;
8714 }
8715 if (fixed != 0) {
8716 if (fixed > maxchar)
8717 maxchar = fixed;
8718 PyUnicode_WRITE(kind, data, i, fixed);
8719 }
8720 else if (ch > maxchar)
8721 maxchar = ch;
8722 }
8723 else if (ch > maxchar)
8724 maxchar = ch;
8725 }
8726
8727 return maxchar;
8728}
8729
8730PyObject *
8731_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8732{
8733 if (!PyUnicode_Check(unicode)) {
8734 PyErr_BadInternalCall();
8735 return NULL;
8736 }
8737 if (PyUnicode_READY(unicode) == -1)
8738 return NULL;
8739 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8740 /* If the string is already ASCII, just return the same string */
8741 Py_INCREF(unicode);
8742 return unicode;
8743 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008744 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745}
8746
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008747PyObject *
8748PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8749 Py_ssize_t length)
8750{
Victor Stinnerf0124502011-11-21 23:12:56 +01008751 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008752 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008753 Py_UCS4 maxchar;
8754 enum PyUnicode_Kind kind;
8755 void *data;
8756
8757 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008758 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008759 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008760 if (ch > 127) {
8761 int decimal = Py_UNICODE_TODECIMAL(ch);
8762 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008763 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008764 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008765 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008766 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008767
8768 /* Copy to a new string */
8769 decimal = PyUnicode_New(length, maxchar);
8770 if (decimal == NULL)
8771 return decimal;
8772 kind = PyUnicode_KIND(decimal);
8773 data = PyUnicode_DATA(decimal);
8774 /* Iterate over code points */
8775 for (i = 0; i < length; i++) {
8776 Py_UNICODE ch = s[i];
8777 if (ch > 127) {
8778 int decimal = Py_UNICODE_TODECIMAL(ch);
8779 if (decimal >= 0)
8780 ch = '0' + decimal;
8781 }
8782 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008784 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008785}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008786/* --- Decimal Encoder ---------------------------------------------------- */
8787
Alexander Belopolsky40018472011-02-26 01:02:56 +00008788int
8789PyUnicode_EncodeDecimal(Py_UNICODE *s,
8790 Py_ssize_t length,
8791 char *output,
8792 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008793{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008794 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008795 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008796 enum PyUnicode_Kind kind;
8797 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008798
8799 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008800 PyErr_BadArgument();
8801 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008802 }
8803
Victor Stinner42bf7752011-11-21 22:52:58 +01008804 unicode = PyUnicode_FromUnicode(s, length);
8805 if (unicode == NULL)
8806 return -1;
8807
Victor Stinner6345be92011-11-25 20:09:01 +01008808 if (PyUnicode_READY(unicode) < 0) {
8809 Py_DECREF(unicode);
8810 return -1;
8811 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008812 kind = PyUnicode_KIND(unicode);
8813 data = PyUnicode_DATA(unicode);
8814
Victor Stinnerb84d7232011-11-22 01:50:07 +01008815 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008816 PyObject *exc;
8817 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008818 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008819 Py_ssize_t startpos;
8820
8821 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008822
Benjamin Peterson29060642009-01-31 22:14:21 +00008823 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008824 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008825 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008827 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008828 decimal = Py_UNICODE_TODECIMAL(ch);
8829 if (decimal >= 0) {
8830 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008831 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 continue;
8833 }
8834 if (0 < ch && ch < 256) {
8835 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008836 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 continue;
8838 }
Victor Stinner6345be92011-11-25 20:09:01 +01008839
Victor Stinner42bf7752011-11-21 22:52:58 +01008840 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008841 exc = NULL;
8842 raise_encode_exception(&exc, "decimal", unicode,
8843 startpos, startpos+1,
8844 "invalid decimal Unicode string");
8845 Py_XDECREF(exc);
8846 Py_DECREF(unicode);
8847 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008848 }
8849 /* 0-terminate the output string */
8850 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008851 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008852 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008853}
8854
Guido van Rossumd57fd912000-03-10 22:53:23 +00008855/* --- Helpers ------------------------------------------------------------ */
8856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008858any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008859 Py_ssize_t start,
8860 Py_ssize_t end)
8861{
8862 int kind1, kind2, kind;
8863 void *buf1, *buf2;
8864 Py_ssize_t len1, len2, result;
8865
8866 kind1 = PyUnicode_KIND(s1);
8867 kind2 = PyUnicode_KIND(s2);
8868 kind = kind1 > kind2 ? kind1 : kind2;
8869 buf1 = PyUnicode_DATA(s1);
8870 buf2 = PyUnicode_DATA(s2);
8871 if (kind1 != kind)
8872 buf1 = _PyUnicode_AsKind(s1, kind);
8873 if (!buf1)
8874 return -2;
8875 if (kind2 != kind)
8876 buf2 = _PyUnicode_AsKind(s2, kind);
8877 if (!buf2) {
8878 if (kind1 != kind) PyMem_Free(buf1);
8879 return -2;
8880 }
8881 len1 = PyUnicode_GET_LENGTH(s1);
8882 len2 = PyUnicode_GET_LENGTH(s2);
8883
Victor Stinner794d5672011-10-10 03:21:36 +02008884 if (direction > 0) {
8885 switch(kind) {
8886 case PyUnicode_1BYTE_KIND:
8887 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8888 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8889 else
8890 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8891 break;
8892 case PyUnicode_2BYTE_KIND:
8893 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8894 break;
8895 case PyUnicode_4BYTE_KIND:
8896 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8897 break;
8898 default:
8899 assert(0); result = -2;
8900 }
8901 }
8902 else {
8903 switch(kind) {
8904 case PyUnicode_1BYTE_KIND:
8905 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8906 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8907 else
8908 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8909 break;
8910 case PyUnicode_2BYTE_KIND:
8911 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8912 break;
8913 case PyUnicode_4BYTE_KIND:
8914 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8915 break;
8916 default:
8917 assert(0); result = -2;
8918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008919 }
8920
8921 if (kind1 != kind)
8922 PyMem_Free(buf1);
8923 if (kind2 != kind)
8924 PyMem_Free(buf2);
8925
8926 return result;
8927}
8928
8929Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008930_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008931 Py_ssize_t n_buffer,
8932 void *digits, Py_ssize_t n_digits,
8933 Py_ssize_t min_width,
8934 const char *grouping,
8935 const char *thousands_sep)
8936{
8937 switch(kind) {
8938 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008939 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8940 return _PyUnicode_ascii_InsertThousandsGrouping(
8941 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8942 min_width, grouping, thousands_sep);
8943 else
8944 return _PyUnicode_ucs1_InsertThousandsGrouping(
8945 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8946 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008947 case PyUnicode_2BYTE_KIND:
8948 return _PyUnicode_ucs2_InsertThousandsGrouping(
8949 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8950 min_width, grouping, thousands_sep);
8951 case PyUnicode_4BYTE_KIND:
8952 return _PyUnicode_ucs4_InsertThousandsGrouping(
8953 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8954 min_width, grouping, thousands_sep);
8955 }
8956 assert(0);
8957 return -1;
8958}
8959
8960
Thomas Wouters477c8d52006-05-27 19:21:47 +00008961/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008962#define ADJUST_INDICES(start, end, len) \
8963 if (end > len) \
8964 end = len; \
8965 else if (end < 0) { \
8966 end += len; \
8967 if (end < 0) \
8968 end = 0; \
8969 } \
8970 if (start < 0) { \
8971 start += len; \
8972 if (start < 0) \
8973 start = 0; \
8974 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008975
Alexander Belopolsky40018472011-02-26 01:02:56 +00008976Py_ssize_t
8977PyUnicode_Count(PyObject *str,
8978 PyObject *substr,
8979 Py_ssize_t start,
8980 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008981{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008982 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008983 PyObject* str_obj;
8984 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008985 int kind1, kind2, kind;
8986 void *buf1 = NULL, *buf2 = NULL;
8987 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008988
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008989 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008991 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008992 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008993 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008994 Py_DECREF(str_obj);
8995 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996 }
Tim Petersced69f82003-09-16 20:30:58 +00008997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008998 kind1 = PyUnicode_KIND(str_obj);
8999 kind2 = PyUnicode_KIND(sub_obj);
9000 kind = kind1 > kind2 ? kind1 : kind2;
9001 buf1 = PyUnicode_DATA(str_obj);
9002 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009003 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009004 if (!buf1)
9005 goto onError;
9006 buf2 = PyUnicode_DATA(sub_obj);
9007 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009008 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 if (!buf2)
9010 goto onError;
9011 len1 = PyUnicode_GET_LENGTH(str_obj);
9012 len2 = PyUnicode_GET_LENGTH(sub_obj);
9013
9014 ADJUST_INDICES(start, end, len1);
9015 switch(kind) {
9016 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009017 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9018 result = asciilib_count(
9019 ((Py_UCS1*)buf1) + start, end - start,
9020 buf2, len2, PY_SSIZE_T_MAX
9021 );
9022 else
9023 result = ucs1lib_count(
9024 ((Py_UCS1*)buf1) + start, end - start,
9025 buf2, len2, PY_SSIZE_T_MAX
9026 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027 break;
9028 case PyUnicode_2BYTE_KIND:
9029 result = ucs2lib_count(
9030 ((Py_UCS2*)buf1) + start, end - start,
9031 buf2, len2, PY_SSIZE_T_MAX
9032 );
9033 break;
9034 case PyUnicode_4BYTE_KIND:
9035 result = ucs4lib_count(
9036 ((Py_UCS4*)buf1) + start, end - start,
9037 buf2, len2, PY_SSIZE_T_MAX
9038 );
9039 break;
9040 default:
9041 assert(0); result = 0;
9042 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009043
9044 Py_DECREF(sub_obj);
9045 Py_DECREF(str_obj);
9046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 if (kind1 != kind)
9048 PyMem_Free(buf1);
9049 if (kind2 != kind)
9050 PyMem_Free(buf2);
9051
Guido van Rossumd57fd912000-03-10 22:53:23 +00009052 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 onError:
9054 Py_DECREF(sub_obj);
9055 Py_DECREF(str_obj);
9056 if (kind1 != kind && buf1)
9057 PyMem_Free(buf1);
9058 if (kind2 != kind && buf2)
9059 PyMem_Free(buf2);
9060 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061}
9062
Alexander Belopolsky40018472011-02-26 01:02:56 +00009063Py_ssize_t
9064PyUnicode_Find(PyObject *str,
9065 PyObject *sub,
9066 Py_ssize_t start,
9067 Py_ssize_t end,
9068 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009069{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009070 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009071
Guido van Rossumd57fd912000-03-10 22:53:23 +00009072 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009074 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009075 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009077 Py_DECREF(str);
9078 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079 }
Tim Petersced69f82003-09-16 20:30:58 +00009080
Victor Stinner794d5672011-10-10 03:21:36 +02009081 result = any_find_slice(direction,
9082 str, sub, start, end
9083 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009084
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009086 Py_DECREF(sub);
9087
Guido van Rossumd57fd912000-03-10 22:53:23 +00009088 return result;
9089}
9090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091Py_ssize_t
9092PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9093 Py_ssize_t start, Py_ssize_t end,
9094 int direction)
9095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009097 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 if (PyUnicode_READY(str) == -1)
9099 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009100 if (start < 0 || end < 0) {
9101 PyErr_SetString(PyExc_IndexError, "string index out of range");
9102 return -2;
9103 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104 if (end > PyUnicode_GET_LENGTH(str))
9105 end = PyUnicode_GET_LENGTH(str);
9106 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009107 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9108 kind, end-start, ch, direction);
9109 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009111 else
9112 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113}
9114
Alexander Belopolsky40018472011-02-26 01:02:56 +00009115static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009116tailmatch(PyObject *self,
9117 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009118 Py_ssize_t start,
9119 Py_ssize_t end,
9120 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009121{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009122 int kind_self;
9123 int kind_sub;
9124 void *data_self;
9125 void *data_sub;
9126 Py_ssize_t offset;
9127 Py_ssize_t i;
9128 Py_ssize_t end_sub;
9129
9130 if (PyUnicode_READY(self) == -1 ||
9131 PyUnicode_READY(substring) == -1)
9132 return 0;
9133
9134 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 return 1;
9136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9138 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009142 kind_self = PyUnicode_KIND(self);
9143 data_self = PyUnicode_DATA(self);
9144 kind_sub = PyUnicode_KIND(substring);
9145 data_sub = PyUnicode_DATA(substring);
9146 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9147
9148 if (direction > 0)
9149 offset = end;
9150 else
9151 offset = start;
9152
9153 if (PyUnicode_READ(kind_self, data_self, offset) ==
9154 PyUnicode_READ(kind_sub, data_sub, 0) &&
9155 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9156 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9157 /* If both are of the same kind, memcmp is sufficient */
9158 if (kind_self == kind_sub) {
9159 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009160 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 data_sub,
9162 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009163 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 }
9165 /* otherwise we have to compare each character by first accesing it */
9166 else {
9167 /* We do not need to compare 0 and len(substring)-1 because
9168 the if statement above ensured already that they are equal
9169 when we end up here. */
9170 // TODO: honor direction and do a forward or backwards search
9171 for (i = 1; i < end_sub; ++i) {
9172 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9173 PyUnicode_READ(kind_sub, data_sub, i))
9174 return 0;
9175 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178 }
9179
9180 return 0;
9181}
9182
Alexander Belopolsky40018472011-02-26 01:02:56 +00009183Py_ssize_t
9184PyUnicode_Tailmatch(PyObject *str,
9185 PyObject *substr,
9186 Py_ssize_t start,
9187 Py_ssize_t end,
9188 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009189{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009190 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009191
Guido van Rossumd57fd912000-03-10 22:53:23 +00009192 str = PyUnicode_FromObject(str);
9193 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009194 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009195 substr = PyUnicode_FromObject(substr);
9196 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009197 Py_DECREF(str);
9198 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009199 }
Tim Petersced69f82003-09-16 20:30:58 +00009200
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009201 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009202 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203 Py_DECREF(str);
9204 Py_DECREF(substr);
9205 return result;
9206}
9207
Guido van Rossumd57fd912000-03-10 22:53:23 +00009208/* Apply fixfct filter to the Unicode object self and return a
9209 reference to the modified object */
9210
Alexander Belopolsky40018472011-02-26 01:02:56 +00009211static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009212fixup(PyObject *self,
9213 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 PyObject *u;
9216 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009217
Victor Stinner87af4f22011-11-21 23:03:47 +01009218 u = PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009220 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009221 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009223 /* fix functions return the new maximum character in a string,
9224 if the kind of the resulting unicode object does not change,
9225 everything is fine. Otherwise we need to change the string kind
9226 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009227 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 if (maxchar_new == 0)
9229 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9230 else if (maxchar_new <= 127)
9231 maxchar_new = 127;
9232 else if (maxchar_new <= 255)
9233 maxchar_new = 255;
9234 else if (maxchar_new <= 65535)
9235 maxchar_new = 65535;
9236 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009237 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238
9239 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009240 /* fixfct should return TRUE if it modified the buffer. If
9241 FALSE, return a reference to the original buffer instead
9242 (to save space, not time) */
9243 Py_INCREF(self);
9244 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009245 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247 else if (maxchar_new == maxchar_old) {
9248 return u;
9249 }
9250 else {
9251 /* In case the maximum character changed, we need to
9252 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009253 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 if (v == NULL) {
9255 Py_DECREF(u);
9256 return NULL;
9257 }
9258 if (maxchar_new > maxchar_old) {
9259 /* If the maxchar increased so that the kind changed, not all
9260 characters are representable anymore and we need to fix the
9261 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009262 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009263 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9265 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009266 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009267 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269
9270 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009271 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009272 return v;
9273 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009274}
9275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009277fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 /* No need to call PyUnicode_READY(self) because this function is only
9280 called as a callback from fixup() which does it already. */
9281 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9282 const int kind = PyUnicode_KIND(self);
9283 void *data = PyUnicode_DATA(self);
9284 int touched = 0;
9285 Py_UCS4 maxchar = 0;
9286 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 for (i = 0; i < len; ++i) {
9289 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9290 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9291 if (up != ch) {
9292 if (up > maxchar)
9293 maxchar = up;
9294 PyUnicode_WRITE(kind, data, i, up);
9295 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 else if (ch > maxchar)
9298 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299 }
9300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 if (touched)
9302 return maxchar;
9303 else
9304 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305}
9306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009307static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009308fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009309{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009310 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9311 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9312 const int kind = PyUnicode_KIND(self);
9313 void *data = PyUnicode_DATA(self);
9314 int touched = 0;
9315 Py_UCS4 maxchar = 0;
9316 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318 for(i = 0; i < len; ++i) {
9319 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9320 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9321 if (lo != ch) {
9322 if (lo > maxchar)
9323 maxchar = lo;
9324 PyUnicode_WRITE(kind, data, i, lo);
9325 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 else if (ch > maxchar)
9328 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 }
9330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009331 if (touched)
9332 return maxchar;
9333 else
9334 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335}
9336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009338fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009339{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9341 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9342 const int kind = PyUnicode_KIND(self);
9343 void *data = PyUnicode_DATA(self);
9344 int touched = 0;
9345 Py_UCS4 maxchar = 0;
9346 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 for(i = 0; i < len; ++i) {
9349 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9350 Py_UCS4 nu = 0;
9351
9352 if (Py_UNICODE_ISUPPER(ch))
9353 nu = Py_UNICODE_TOLOWER(ch);
9354 else if (Py_UNICODE_ISLOWER(ch))
9355 nu = Py_UNICODE_TOUPPER(ch);
9356
9357 if (nu != 0) {
9358 if (nu > maxchar)
9359 maxchar = nu;
9360 PyUnicode_WRITE(kind, data, i, nu);
9361 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 else if (ch > maxchar)
9364 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009365 }
9366
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 if (touched)
9368 return maxchar;
9369 else
9370 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371}
9372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009374fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9377 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9378 const int kind = PyUnicode_KIND(self);
9379 void *data = PyUnicode_DATA(self);
9380 int touched = 0;
9381 Py_UCS4 maxchar = 0;
9382 Py_ssize_t i = 0;
9383 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009384
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009385 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009386 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009387
9388 ch = PyUnicode_READ(kind, data, i);
9389 if (!Py_UNICODE_ISUPPER(ch)) {
9390 maxchar = Py_UNICODE_TOUPPER(ch);
9391 PyUnicode_WRITE(kind, data, i, maxchar);
9392 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009393 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394 ++i;
9395 for(; i < len; ++i) {
9396 ch = PyUnicode_READ(kind, data, i);
9397 if (!Py_UNICODE_ISLOWER(ch)) {
9398 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9399 if (lo > maxchar)
9400 maxchar = lo;
9401 PyUnicode_WRITE(kind, data, i, lo);
9402 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009403 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404 else if (ch > maxchar)
9405 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009406 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407
9408 if (touched)
9409 return maxchar;
9410 else
9411 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009412}
9413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009415fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009416{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9418 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9419 const int kind = PyUnicode_KIND(self);
9420 void *data = PyUnicode_DATA(self);
9421 Py_UCS4 maxchar = 0;
9422 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423 int previous_is_cased;
9424
9425 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 if (len == 1) {
9427 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9428 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9429 if (ti != ch) {
9430 PyUnicode_WRITE(kind, data, i, ti);
9431 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009432 }
9433 else
9434 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009435 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 for(; i < len; ++i) {
9438 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9439 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009440
Benjamin Peterson29060642009-01-31 22:14:21 +00009441 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009443 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 nu = Py_UNICODE_TOTITLE(ch);
9445
9446 if (nu > maxchar)
9447 maxchar = nu;
9448 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009449
Benjamin Peterson29060642009-01-31 22:14:21 +00009450 if (Py_UNICODE_ISLOWER(ch) ||
9451 Py_UNICODE_ISUPPER(ch) ||
9452 Py_UNICODE_ISTITLE(ch))
9453 previous_is_cased = 1;
9454 else
9455 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458}
9459
Tim Peters8ce9f162004-08-27 01:49:32 +00009460PyObject *
9461PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009464 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009466 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009467 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9468 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009469 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009471 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009473 int use_memcpy;
9474 unsigned char *res_data = NULL, *sep_data = NULL;
9475 PyObject *last_obj;
9476 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477
Tim Peters05eba1f2004-08-27 21:32:02 +00009478 fseq = PySequence_Fast(seq, "");
9479 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009480 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009481 }
9482
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009483 /* NOTE: the following code can't call back into Python code,
9484 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009485 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009486
Tim Peters05eba1f2004-08-27 21:32:02 +00009487 seqlen = PySequence_Fast_GET_SIZE(fseq);
9488 /* If empty sequence, return u"". */
9489 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009490 Py_DECREF(fseq);
9491 Py_INCREF(unicode_empty);
9492 res = unicode_empty;
9493 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009494 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009495
Tim Peters05eba1f2004-08-27 21:32:02 +00009496 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009497 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009498 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009499 if (seqlen == 1) {
9500 if (PyUnicode_CheckExact(items[0])) {
9501 res = items[0];
9502 Py_INCREF(res);
9503 Py_DECREF(fseq);
9504 return res;
9505 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009506 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009507 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009508 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009509 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009510 /* Set up sep and seplen */
9511 if (separator == NULL) {
9512 /* fall back to a blank space separator */
9513 sep = PyUnicode_FromOrdinal(' ');
9514 if (!sep)
9515 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009516 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009517 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009518 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009519 else {
9520 if (!PyUnicode_Check(separator)) {
9521 PyErr_Format(PyExc_TypeError,
9522 "separator: expected str instance,"
9523 " %.80s found",
9524 Py_TYPE(separator)->tp_name);
9525 goto onError;
9526 }
9527 if (PyUnicode_READY(separator))
9528 goto onError;
9529 sep = separator;
9530 seplen = PyUnicode_GET_LENGTH(separator);
9531 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9532 /* inc refcount to keep this code path symmetric with the
9533 above case of a blank separator */
9534 Py_INCREF(sep);
9535 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009536 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009537 }
9538
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009539 /* There are at least two things to join, or else we have a subclass
9540 * of str in the sequence.
9541 * Do a pre-pass to figure out the total amount of space we'll
9542 * need (sz), and see whether all argument are strings.
9543 */
9544 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009545#ifdef Py_DEBUG
9546 use_memcpy = 0;
9547#else
9548 use_memcpy = 1;
9549#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009550 for (i = 0; i < seqlen; i++) {
9551 const Py_ssize_t old_sz = sz;
9552 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009553 if (!PyUnicode_Check(item)) {
9554 PyErr_Format(PyExc_TypeError,
9555 "sequence item %zd: expected str instance,"
9556 " %.80s found",
9557 i, Py_TYPE(item)->tp_name);
9558 goto onError;
9559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 if (PyUnicode_READY(item) == -1)
9561 goto onError;
9562 sz += PyUnicode_GET_LENGTH(item);
9563 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009564 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009565 if (i != 0)
9566 sz += seplen;
9567 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9568 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009570 goto onError;
9571 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009572 if (use_memcpy && last_obj != NULL) {
9573 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9574 use_memcpy = 0;
9575 }
9576 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009577 }
Tim Petersced69f82003-09-16 20:30:58 +00009578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009580 if (res == NULL)
9581 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009582
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009583 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009584#ifdef Py_DEBUG
9585 use_memcpy = 0;
9586#else
9587 if (use_memcpy) {
9588 res_data = PyUnicode_1BYTE_DATA(res);
9589 kind = PyUnicode_KIND(res);
9590 if (seplen != 0)
9591 sep_data = PyUnicode_1BYTE_DATA(sep);
9592 }
9593#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009595 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009596 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009597 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009598 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009599 if (use_memcpy) {
9600 Py_MEMCPY(res_data,
9601 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009602 kind * seplen);
9603 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009604 }
9605 else {
9606 copy_characters(res, res_offset, sep, 0, seplen);
9607 res_offset += seplen;
9608 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009609 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009610 itemlen = PyUnicode_GET_LENGTH(item);
9611 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009612 if (use_memcpy) {
9613 Py_MEMCPY(res_data,
9614 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009615 kind * itemlen);
9616 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009617 }
9618 else {
9619 copy_characters(res, res_offset, item, 0, itemlen);
9620 res_offset += itemlen;
9621 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009622 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009623 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009624 if (use_memcpy)
9625 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009626 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009627 else
9628 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009629
Tim Peters05eba1f2004-08-27 21:32:02 +00009630 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009632 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009633 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634
Benjamin Peterson29060642009-01-31 22:14:21 +00009635 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009636 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009638 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639 return NULL;
9640}
9641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009642#define FILL(kind, data, value, start, length) \
9643 do { \
9644 Py_ssize_t i_ = 0; \
9645 assert(kind != PyUnicode_WCHAR_KIND); \
9646 switch ((kind)) { \
9647 case PyUnicode_1BYTE_KIND: { \
9648 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9649 memset(to_, (unsigned char)value, length); \
9650 break; \
9651 } \
9652 case PyUnicode_2BYTE_KIND: { \
9653 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9654 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9655 break; \
9656 } \
9657 default: { \
9658 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9659 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9660 break; \
9661 } \
9662 } \
9663 } while (0)
9664
Victor Stinner9310abb2011-10-05 00:59:23 +02009665static PyObject *
9666pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009667 Py_ssize_t left,
9668 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009669 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009671 PyObject *u;
9672 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009673 int kind;
9674 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009675
9676 if (left < 0)
9677 left = 0;
9678 if (right < 0)
9679 right = 0;
9680
Tim Peters7a29bd52001-09-12 03:03:31 +00009681 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682 Py_INCREF(self);
9683 return self;
9684 }
9685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009686 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9687 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009688 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9689 return NULL;
9690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9692 if (fill > maxchar)
9693 maxchar = fill;
9694 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009695 if (!u)
9696 return NULL;
9697
9698 kind = PyUnicode_KIND(u);
9699 data = PyUnicode_DATA(u);
9700 if (left)
9701 FILL(kind, data, fill, 0, left);
9702 if (right)
9703 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009704 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009705 assert(_PyUnicode_CheckConsistency(u, 1));
9706 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009707}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009709
Alexander Belopolsky40018472011-02-26 01:02:56 +00009710PyObject *
9711PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009712{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009713 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009714
9715 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009716 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009717 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 switch(PyUnicode_KIND(string)) {
9720 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009721 if (PyUnicode_IS_ASCII(string))
9722 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009723 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009724 PyUnicode_GET_LENGTH(string), keepends);
9725 else
9726 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009727 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009728 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009729 break;
9730 case PyUnicode_2BYTE_KIND:
9731 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009732 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 PyUnicode_GET_LENGTH(string), keepends);
9734 break;
9735 case PyUnicode_4BYTE_KIND:
9736 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009737 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009738 PyUnicode_GET_LENGTH(string), keepends);
9739 break;
9740 default:
9741 assert(0);
9742 list = 0;
9743 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009744 Py_DECREF(string);
9745 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746}
9747
Alexander Belopolsky40018472011-02-26 01:02:56 +00009748static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009749split(PyObject *self,
9750 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009751 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009752{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 int kind1, kind2, kind;
9754 void *buf1, *buf2;
9755 Py_ssize_t len1, len2;
9756 PyObject* out;
9757
Guido van Rossumd57fd912000-03-10 22:53:23 +00009758 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009759 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009761 if (PyUnicode_READY(self) == -1)
9762 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009764 if (substring == NULL)
9765 switch(PyUnicode_KIND(self)) {
9766 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009767 if (PyUnicode_IS_ASCII(self))
9768 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009769 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009770 PyUnicode_GET_LENGTH(self), maxcount
9771 );
9772 else
9773 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009774 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009775 PyUnicode_GET_LENGTH(self), maxcount
9776 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 case PyUnicode_2BYTE_KIND:
9778 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009779 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 PyUnicode_GET_LENGTH(self), maxcount
9781 );
9782 case PyUnicode_4BYTE_KIND:
9783 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009784 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 PyUnicode_GET_LENGTH(self), maxcount
9786 );
9787 default:
9788 assert(0);
9789 return NULL;
9790 }
9791
9792 if (PyUnicode_READY(substring) == -1)
9793 return NULL;
9794
9795 kind1 = PyUnicode_KIND(self);
9796 kind2 = PyUnicode_KIND(substring);
9797 kind = kind1 > kind2 ? kind1 : kind2;
9798 buf1 = PyUnicode_DATA(self);
9799 buf2 = PyUnicode_DATA(substring);
9800 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009801 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009802 if (!buf1)
9803 return NULL;
9804 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009805 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009806 if (!buf2) {
9807 if (kind1 != kind) PyMem_Free(buf1);
9808 return NULL;
9809 }
9810 len1 = PyUnicode_GET_LENGTH(self);
9811 len2 = PyUnicode_GET_LENGTH(substring);
9812
9813 switch(kind) {
9814 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009815 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9816 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009817 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009818 else
9819 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009820 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 break;
9822 case PyUnicode_2BYTE_KIND:
9823 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009824 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 break;
9826 case PyUnicode_4BYTE_KIND:
9827 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009828 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 break;
9830 default:
9831 out = NULL;
9832 }
9833 if (kind1 != kind)
9834 PyMem_Free(buf1);
9835 if (kind2 != kind)
9836 PyMem_Free(buf2);
9837 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009838}
9839
Alexander Belopolsky40018472011-02-26 01:02:56 +00009840static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009841rsplit(PyObject *self,
9842 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009843 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009844{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 int kind1, kind2, kind;
9846 void *buf1, *buf2;
9847 Py_ssize_t len1, len2;
9848 PyObject* out;
9849
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009850 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009851 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009852
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 if (PyUnicode_READY(self) == -1)
9854 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009856 if (substring == NULL)
9857 switch(PyUnicode_KIND(self)) {
9858 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009859 if (PyUnicode_IS_ASCII(self))
9860 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009861 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009862 PyUnicode_GET_LENGTH(self), maxcount
9863 );
9864 else
9865 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009866 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009867 PyUnicode_GET_LENGTH(self), maxcount
9868 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 case PyUnicode_2BYTE_KIND:
9870 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009871 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 PyUnicode_GET_LENGTH(self), maxcount
9873 );
9874 case PyUnicode_4BYTE_KIND:
9875 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009876 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 PyUnicode_GET_LENGTH(self), maxcount
9878 );
9879 default:
9880 assert(0);
9881 return NULL;
9882 }
9883
9884 if (PyUnicode_READY(substring) == -1)
9885 return NULL;
9886
9887 kind1 = PyUnicode_KIND(self);
9888 kind2 = PyUnicode_KIND(substring);
9889 kind = kind1 > kind2 ? kind1 : kind2;
9890 buf1 = PyUnicode_DATA(self);
9891 buf2 = PyUnicode_DATA(substring);
9892 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009893 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009894 if (!buf1)
9895 return NULL;
9896 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009897 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009898 if (!buf2) {
9899 if (kind1 != kind) PyMem_Free(buf1);
9900 return NULL;
9901 }
9902 len1 = PyUnicode_GET_LENGTH(self);
9903 len2 = PyUnicode_GET_LENGTH(substring);
9904
9905 switch(kind) {
9906 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009907 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9908 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009909 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009910 else
9911 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009912 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 break;
9914 case PyUnicode_2BYTE_KIND:
9915 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009916 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 break;
9918 case PyUnicode_4BYTE_KIND:
9919 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009920 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009921 break;
9922 default:
9923 out = NULL;
9924 }
9925 if (kind1 != kind)
9926 PyMem_Free(buf1);
9927 if (kind2 != kind)
9928 PyMem_Free(buf2);
9929 return out;
9930}
9931
9932static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009933anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9934 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935{
9936 switch(kind) {
9937 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009938 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9939 return asciilib_find(buf1, len1, buf2, len2, offset);
9940 else
9941 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 case PyUnicode_2BYTE_KIND:
9943 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9944 case PyUnicode_4BYTE_KIND:
9945 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9946 }
9947 assert(0);
9948 return -1;
9949}
9950
9951static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009952anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9953 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954{
9955 switch(kind) {
9956 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009957 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9958 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9959 else
9960 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 case PyUnicode_2BYTE_KIND:
9962 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9963 case PyUnicode_4BYTE_KIND:
9964 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9965 }
9966 assert(0);
9967 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009968}
9969
Alexander Belopolsky40018472011-02-26 01:02:56 +00009970static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971replace(PyObject *self, PyObject *str1,
9972 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009973{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 PyObject *u;
9975 char *sbuf = PyUnicode_DATA(self);
9976 char *buf1 = PyUnicode_DATA(str1);
9977 char *buf2 = PyUnicode_DATA(str2);
9978 int srelease = 0, release1 = 0, release2 = 0;
9979 int skind = PyUnicode_KIND(self);
9980 int kind1 = PyUnicode_KIND(str1);
9981 int kind2 = PyUnicode_KIND(str2);
9982 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9983 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9984 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009985 int mayshrink;
9986 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009987
9988 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009989 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009991 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992
Victor Stinner59de0ee2011-10-07 10:01:28 +02009993 if (str1 == str2)
9994 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 if (skind < kind1)
9996 /* substring too wide to be present */
9997 goto nothing;
9998
Victor Stinner49a0a212011-10-12 23:46:10 +02009999 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10000 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10001 /* Replacing str1 with str2 may cause a maxchar reduction in the
10002 result string. */
10003 mayshrink = (maxchar_str2 < maxchar);
10004 maxchar = Py_MAX(maxchar, maxchar_str2);
10005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010007 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010008 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010010 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010012 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010013 Py_UCS4 u1, u2;
10014 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010016 if (findchar(sbuf, PyUnicode_KIND(self),
10017 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010018 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010021 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010023 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024 rkind = PyUnicode_KIND(u);
10025 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10026 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010027 if (--maxcount < 0)
10028 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010030 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010031 }
10032 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 int rkind = skind;
10034 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 if (kind1 < rkind) {
10037 /* widen substring */
10038 buf1 = _PyUnicode_AsKind(str1, rkind);
10039 if (!buf1) goto error;
10040 release1 = 1;
10041 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010042 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010043 if (i < 0)
10044 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 if (rkind > kind2) {
10046 /* widen replacement */
10047 buf2 = _PyUnicode_AsKind(str2, rkind);
10048 if (!buf2) goto error;
10049 release2 = 1;
10050 }
10051 else if (rkind < kind2) {
10052 /* widen self and buf1 */
10053 rkind = kind2;
10054 if (release1) PyMem_Free(buf1);
10055 sbuf = _PyUnicode_AsKind(self, rkind);
10056 if (!sbuf) goto error;
10057 srelease = 1;
10058 buf1 = _PyUnicode_AsKind(str1, rkind);
10059 if (!buf1) goto error;
10060 release1 = 1;
10061 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010062 u = PyUnicode_New(slen, maxchar);
10063 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010065 assert(PyUnicode_KIND(u) == rkind);
10066 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010067
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010068 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010069 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010070 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010072 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010074
10075 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010076 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010077 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010078 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010079 if (i == -1)
10080 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010081 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010083 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010085 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010086 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010087 }
10088 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 Py_ssize_t n, i, j, ires;
10090 Py_ssize_t product, new_size;
10091 int rkind = skind;
10092 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010095 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 buf1 = _PyUnicode_AsKind(str1, rkind);
10097 if (!buf1) goto error;
10098 release1 = 1;
10099 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010101 if (n == 0)
10102 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010104 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 buf2 = _PyUnicode_AsKind(str2, rkind);
10106 if (!buf2) goto error;
10107 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010108 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010110 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 rkind = kind2;
10112 sbuf = _PyUnicode_AsKind(self, rkind);
10113 if (!sbuf) goto error;
10114 srelease = 1;
10115 if (release1) PyMem_Free(buf1);
10116 buf1 = _PyUnicode_AsKind(str1, rkind);
10117 if (!buf1) goto error;
10118 release1 = 1;
10119 }
10120 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10121 PyUnicode_GET_LENGTH(str1))); */
10122 product = n * (len2-len1);
10123 if ((product / (len2-len1)) != n) {
10124 PyErr_SetString(PyExc_OverflowError,
10125 "replace string is too long");
10126 goto error;
10127 }
10128 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010129 if (new_size == 0) {
10130 Py_INCREF(unicode_empty);
10131 u = unicode_empty;
10132 goto done;
10133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10135 PyErr_SetString(PyExc_OverflowError,
10136 "replace string is too long");
10137 goto error;
10138 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010139 u = PyUnicode_New(new_size, maxchar);
10140 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010142 assert(PyUnicode_KIND(u) == rkind);
10143 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 ires = i = 0;
10145 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010146 while (n-- > 0) {
10147 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010149 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010151 if (j == -1)
10152 break;
10153 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010154 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010155 memcpy(res + rkind * ires,
10156 sbuf + rkind * i,
10157 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010159 }
10160 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010162 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010164 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010166 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010168 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010170 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010171 memcpy(res + rkind * ires,
10172 sbuf + rkind * i,
10173 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010174 }
10175 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010176 /* interleave */
10177 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010178 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010180 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010182 if (--n <= 0)
10183 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010184 memcpy(res + rkind * ires,
10185 sbuf + rkind * i,
10186 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 ires++;
10188 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010189 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010190 memcpy(res + rkind * ires,
10191 sbuf + rkind * i,
10192 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010193 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010194 }
10195
10196 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010197 unicode_adjust_maxchar(&u);
10198 if (u == NULL)
10199 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010200 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010201
10202 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 if (srelease)
10204 PyMem_FREE(sbuf);
10205 if (release1)
10206 PyMem_FREE(buf1);
10207 if (release2)
10208 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010209 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010211
Benjamin Peterson29060642009-01-31 22:14:21 +000010212 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010213 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 if (srelease)
10215 PyMem_FREE(sbuf);
10216 if (release1)
10217 PyMem_FREE(buf1);
10218 if (release2)
10219 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010220 if (PyUnicode_CheckExact(self)) {
10221 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010222 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010224 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 error:
10226 if (srelease && sbuf)
10227 PyMem_FREE(sbuf);
10228 if (release1 && buf1)
10229 PyMem_FREE(buf1);
10230 if (release2 && buf2)
10231 PyMem_FREE(buf2);
10232 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010233}
10234
10235/* --- Unicode Object Methods --------------------------------------------- */
10236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010237PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010238 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010239\n\
10240Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010241characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242
10243static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010244unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010245{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010246 return fixup(self, fixtitle);
10247}
10248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010249PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010250 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010251\n\
10252Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010253have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254
10255static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010256unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010258 return fixup(self, fixcapitalize);
10259}
10260
10261#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010262PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010263 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010264\n\
10265Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010266normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010267
10268static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010269unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010270{
10271 PyObject *list;
10272 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010273 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274
Guido van Rossumd57fd912000-03-10 22:53:23 +000010275 /* Split into words */
10276 list = split(self, NULL, -1);
10277 if (!list)
10278 return NULL;
10279
10280 /* Capitalize each word */
10281 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010282 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010283 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284 if (item == NULL)
10285 goto onError;
10286 Py_DECREF(PyList_GET_ITEM(list, i));
10287 PyList_SET_ITEM(list, i, item);
10288 }
10289
10290 /* Join the words to form a new string */
10291 item = PyUnicode_Join(NULL, list);
10292
Benjamin Peterson29060642009-01-31 22:14:21 +000010293 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010295 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010296}
10297#endif
10298
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010299/* Argument converter. Coerces to a single unicode character */
10300
10301static int
10302convert_uc(PyObject *obj, void *addr)
10303{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010305 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010306
Benjamin Peterson14339b62009-01-31 16:36:08 +000010307 uniobj = PyUnicode_FromObject(obj);
10308 if (uniobj == NULL) {
10309 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010310 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010311 return 0;
10312 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010314 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010315 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010316 Py_DECREF(uniobj);
10317 return 0;
10318 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010320 Py_DECREF(uniobj);
10321 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010322}
10323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010324PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010325 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010326\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010327Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010328done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010329
10330static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010331unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010332{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010333 Py_ssize_t marg, left;
10334 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 Py_UCS4 fillchar = ' ';
10336
Victor Stinnere9a29352011-10-01 02:14:59 +020010337 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010339
Victor Stinnere9a29352011-10-01 02:14:59 +020010340 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341 return NULL;
10342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010344 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010345 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010346 }
10347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010349 left = marg / 2 + (marg & width & 1);
10350
Victor Stinner9310abb2011-10-05 00:59:23 +020010351 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010352}
10353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354/* This function assumes that str1 and str2 are readied by the caller. */
10355
Marc-André Lemburge5034372000-08-08 08:04:29 +000010356static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010357unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010358{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 int kind1, kind2;
10360 void *data1, *data2;
10361 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 kind1 = PyUnicode_KIND(str1);
10364 kind2 = PyUnicode_KIND(str2);
10365 data1 = PyUnicode_DATA(str1);
10366 data2 = PyUnicode_DATA(str2);
10367 len1 = PyUnicode_GET_LENGTH(str1);
10368 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 for (i = 0; i < len1 && i < len2; ++i) {
10371 Py_UCS4 c1, c2;
10372 c1 = PyUnicode_READ(kind1, data1, i);
10373 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010374
10375 if (c1 != c2)
10376 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010377 }
10378
10379 return (len1 < len2) ? -1 : (len1 != len2);
10380}
10381
Alexander Belopolsky40018472011-02-26 01:02:56 +000010382int
10383PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10386 if (PyUnicode_READY(left) == -1 ||
10387 PyUnicode_READY(right) == -1)
10388 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010389 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010391 PyErr_Format(PyExc_TypeError,
10392 "Can't compare %.100s and %.100s",
10393 left->ob_type->tp_name,
10394 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395 return -1;
10396}
10397
Martin v. Löwis5b222132007-06-10 09:51:05 +000010398int
10399PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10400{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 Py_ssize_t i;
10402 int kind;
10403 void *data;
10404 Py_UCS4 chr;
10405
Victor Stinner910337b2011-10-03 03:20:16 +020010406 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 if (PyUnicode_READY(uni) == -1)
10408 return -1;
10409 kind = PyUnicode_KIND(uni);
10410 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010411 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10413 if (chr != str[i])
10414 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010415 /* This check keeps Python strings that end in '\0' from comparing equal
10416 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010418 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010419 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010420 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010421 return 0;
10422}
10423
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010424
Benjamin Peterson29060642009-01-31 22:14:21 +000010425#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010426 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010427
Alexander Belopolsky40018472011-02-26 01:02:56 +000010428PyObject *
10429PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010430{
10431 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010432
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010433 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10434 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 if (PyUnicode_READY(left) == -1 ||
10436 PyUnicode_READY(right) == -1)
10437 return NULL;
10438 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10439 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010440 if (op == Py_EQ) {
10441 Py_INCREF(Py_False);
10442 return Py_False;
10443 }
10444 if (op == Py_NE) {
10445 Py_INCREF(Py_True);
10446 return Py_True;
10447 }
10448 }
10449 if (left == right)
10450 result = 0;
10451 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010452 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010453
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010454 /* Convert the return value to a Boolean */
10455 switch (op) {
10456 case Py_EQ:
10457 v = TEST_COND(result == 0);
10458 break;
10459 case Py_NE:
10460 v = TEST_COND(result != 0);
10461 break;
10462 case Py_LE:
10463 v = TEST_COND(result <= 0);
10464 break;
10465 case Py_GE:
10466 v = TEST_COND(result >= 0);
10467 break;
10468 case Py_LT:
10469 v = TEST_COND(result == -1);
10470 break;
10471 case Py_GT:
10472 v = TEST_COND(result == 1);
10473 break;
10474 default:
10475 PyErr_BadArgument();
10476 return NULL;
10477 }
10478 Py_INCREF(v);
10479 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010480 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010481
Brian Curtindfc80e32011-08-10 20:28:54 -050010482 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010483}
10484
Alexander Belopolsky40018472011-02-26 01:02:56 +000010485int
10486PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010487{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010488 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 int kind1, kind2, kind;
10490 void *buf1, *buf2;
10491 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010492 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010493
10494 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010495 sub = PyUnicode_FromObject(element);
10496 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010497 PyErr_Format(PyExc_TypeError,
10498 "'in <string>' requires string as left operand, not %s",
10499 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010501 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 if (PyUnicode_READY(sub) == -1)
10503 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010504
Thomas Wouters477c8d52006-05-27 19:21:47 +000010505 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010506 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010507 Py_DECREF(sub);
10508 return -1;
10509 }
10510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 kind1 = PyUnicode_KIND(str);
10512 kind2 = PyUnicode_KIND(sub);
10513 kind = kind1 > kind2 ? kind1 : kind2;
10514 buf1 = PyUnicode_DATA(str);
10515 buf2 = PyUnicode_DATA(sub);
10516 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010517 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 if (!buf1) {
10519 Py_DECREF(sub);
10520 return -1;
10521 }
10522 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010523 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 if (!buf2) {
10525 Py_DECREF(sub);
10526 if (kind1 != kind) PyMem_Free(buf1);
10527 return -1;
10528 }
10529 len1 = PyUnicode_GET_LENGTH(str);
10530 len2 = PyUnicode_GET_LENGTH(sub);
10531
10532 switch(kind) {
10533 case PyUnicode_1BYTE_KIND:
10534 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10535 break;
10536 case PyUnicode_2BYTE_KIND:
10537 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10538 break;
10539 case PyUnicode_4BYTE_KIND:
10540 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10541 break;
10542 default:
10543 result = -1;
10544 assert(0);
10545 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010546
10547 Py_DECREF(str);
10548 Py_DECREF(sub);
10549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 if (kind1 != kind)
10551 PyMem_Free(buf1);
10552 if (kind2 != kind)
10553 PyMem_Free(buf2);
10554
Guido van Rossum403d68b2000-03-13 15:55:09 +000010555 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010556}
10557
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558/* Concat to string or Unicode object giving a new Unicode object. */
10559
Alexander Belopolsky40018472011-02-26 01:02:56 +000010560PyObject *
10561PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010562{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010564 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010565
10566 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010568 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010569 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010571 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010572 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573
10574 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010575 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010576 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010578 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010579 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010580 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010582 }
10583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010585 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10586 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587
Guido van Rossumd57fd912000-03-10 22:53:23 +000010588 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 w = PyUnicode_New(
10590 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10591 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010592 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010593 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010594 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10595 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596 Py_DECREF(u);
10597 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010598 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600
Benjamin Peterson29060642009-01-31 22:14:21 +000010601 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602 Py_XDECREF(u);
10603 Py_XDECREF(v);
10604 return NULL;
10605}
10606
Victor Stinnerb0923652011-10-04 01:17:31 +020010607static void
10608unicode_append_inplace(PyObject **p_left, PyObject *right)
10609{
10610 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010611
10612 assert(PyUnicode_IS_READY(*p_left));
10613 assert(PyUnicode_IS_READY(right));
10614
10615 left_len = PyUnicode_GET_LENGTH(*p_left);
10616 right_len = PyUnicode_GET_LENGTH(right);
10617 if (left_len > PY_SSIZE_T_MAX - right_len) {
10618 PyErr_SetString(PyExc_OverflowError,
10619 "strings are too large to concat");
10620 goto error;
10621 }
10622 new_len = left_len + right_len;
10623
10624 /* Now we own the last reference to 'left', so we can resize it
10625 * in-place.
10626 */
10627 if (unicode_resize(p_left, new_len) != 0) {
10628 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10629 * deallocated so it cannot be put back into
10630 * 'variable'. The MemoryError is raised when there
10631 * is no value in 'variable', which might (very
10632 * remotely) be a cause of incompatibilities.
10633 */
10634 goto error;
10635 }
10636 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010637 copy_characters(*p_left, left_len, right, 0, right_len);
10638 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010639 return;
10640
10641error:
10642 Py_DECREF(*p_left);
10643 *p_left = NULL;
10644}
10645
Walter Dörwald1ab83302007-05-18 17:15:44 +000010646void
Victor Stinner23e56682011-10-03 03:54:37 +020010647PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010648{
Victor Stinner23e56682011-10-03 03:54:37 +020010649 PyObject *left, *res;
10650
10651 if (p_left == NULL) {
10652 if (!PyErr_Occurred())
10653 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010654 return;
10655 }
Victor Stinner23e56682011-10-03 03:54:37 +020010656 left = *p_left;
10657 if (right == NULL || !PyUnicode_Check(left)) {
10658 if (!PyErr_Occurred())
10659 PyErr_BadInternalCall();
10660 goto error;
10661 }
10662
Victor Stinnere1335c72011-10-04 20:53:03 +020010663 if (PyUnicode_READY(left))
10664 goto error;
10665 if (PyUnicode_READY(right))
10666 goto error;
10667
Victor Stinner23e56682011-10-03 03:54:37 +020010668 if (PyUnicode_CheckExact(left) && left != unicode_empty
10669 && PyUnicode_CheckExact(right) && right != unicode_empty
10670 && unicode_resizable(left)
10671 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10672 || _PyUnicode_WSTR(left) != NULL))
10673 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010674 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10675 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010676 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010677 not so different than duplicating the string. */
10678 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010679 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010680 unicode_append_inplace(p_left, right);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010681 assert(p_left == NULL || _PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010682 return;
10683 }
10684 }
10685
10686 res = PyUnicode_Concat(left, right);
10687 if (res == NULL)
10688 goto error;
10689 Py_DECREF(left);
10690 *p_left = res;
10691 return;
10692
10693error:
10694 Py_DECREF(*p_left);
10695 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010696}
10697
10698void
10699PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10700{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010701 PyUnicode_Append(pleft, right);
10702 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010703}
10704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010705PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010706 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010708Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010709string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010710interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711
10712static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010713unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010715 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010716 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010717 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 int kind1, kind2, kind;
10720 void *buf1, *buf2;
10721 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722
Jesus Ceaac451502011-04-20 17:09:23 +020010723 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10724 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010725 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 kind1 = PyUnicode_KIND(self);
10728 kind2 = PyUnicode_KIND(substring);
10729 kind = kind1 > kind2 ? kind1 : kind2;
10730 buf1 = PyUnicode_DATA(self);
10731 buf2 = PyUnicode_DATA(substring);
10732 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010733 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010734 if (!buf1) {
10735 Py_DECREF(substring);
10736 return NULL;
10737 }
10738 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010739 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010740 if (!buf2) {
10741 Py_DECREF(substring);
10742 if (kind1 != kind) PyMem_Free(buf1);
10743 return NULL;
10744 }
10745 len1 = PyUnicode_GET_LENGTH(self);
10746 len2 = PyUnicode_GET_LENGTH(substring);
10747
10748 ADJUST_INDICES(start, end, len1);
10749 switch(kind) {
10750 case PyUnicode_1BYTE_KIND:
10751 iresult = ucs1lib_count(
10752 ((Py_UCS1*)buf1) + start, end - start,
10753 buf2, len2, PY_SSIZE_T_MAX
10754 );
10755 break;
10756 case PyUnicode_2BYTE_KIND:
10757 iresult = ucs2lib_count(
10758 ((Py_UCS2*)buf1) + start, end - start,
10759 buf2, len2, PY_SSIZE_T_MAX
10760 );
10761 break;
10762 case PyUnicode_4BYTE_KIND:
10763 iresult = ucs4lib_count(
10764 ((Py_UCS4*)buf1) + start, end - start,
10765 buf2, len2, PY_SSIZE_T_MAX
10766 );
10767 break;
10768 default:
10769 assert(0); iresult = 0;
10770 }
10771
10772 result = PyLong_FromSsize_t(iresult);
10773
10774 if (kind1 != kind)
10775 PyMem_Free(buf1);
10776 if (kind2 != kind)
10777 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778
10779 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010780
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781 return result;
10782}
10783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010784PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010785 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010787Encode S using the codec registered for encoding. Default encoding\n\
10788is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010789handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010790a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10791'xmlcharrefreplace' as well as any other name registered with\n\
10792codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010793
10794static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010795unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010797 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 char *encoding = NULL;
10799 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010800
Benjamin Peterson308d6372009-09-18 21:42:35 +000010801 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10802 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010803 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010804 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010805}
10806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010807PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010808 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809\n\
10810Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010811If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812
10813static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010814unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010816 Py_ssize_t i, j, line_pos, src_len, incr;
10817 Py_UCS4 ch;
10818 PyObject *u;
10819 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010821 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010822 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010823
10824 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010825 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826
Antoine Pitrou22425222011-10-04 19:10:51 +020010827 if (PyUnicode_READY(self) == -1)
10828 return NULL;
10829
Thomas Wouters7e474022000-07-16 12:04:32 +000010830 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010831 src_len = PyUnicode_GET_LENGTH(self);
10832 i = j = line_pos = 0;
10833 kind = PyUnicode_KIND(self);
10834 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010835 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010836 for (; i < src_len; i++) {
10837 ch = PyUnicode_READ(kind, src_data, i);
10838 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010839 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010840 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010841 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010842 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010843 goto overflow;
10844 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010845 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010846 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010847 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010848 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010849 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010850 goto overflow;
10851 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010853 if (ch == '\n' || ch == '\r')
10854 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010856 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010857 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010858 Py_INCREF(self);
10859 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010860 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010861
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010863 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864 if (!u)
10865 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010866 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867
Antoine Pitroue71d5742011-10-04 15:55:09 +020010868 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869
Antoine Pitroue71d5742011-10-04 15:55:09 +020010870 for (; i < src_len; i++) {
10871 ch = PyUnicode_READ(kind, src_data, i);
10872 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010873 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010874 incr = tabsize - (line_pos % tabsize);
10875 line_pos += incr;
10876 while (incr--) {
10877 PyUnicode_WRITE(kind, dest_data, j, ' ');
10878 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010879 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010880 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010881 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010882 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010883 line_pos++;
10884 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010885 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010886 if (ch == '\n' || ch == '\r')
10887 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010889 }
10890 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010891 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010892
Antoine Pitroue71d5742011-10-04 15:55:09 +020010893 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010894 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10895 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896}
10897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010898PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010899 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900\n\
10901Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010902such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903arguments start and end are interpreted as in slice notation.\n\
10904\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010905Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906
10907static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010908unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010910 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010911 Py_ssize_t start;
10912 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010913 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914
Jesus Ceaac451502011-04-20 17:09:23 +020010915 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10916 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919 if (PyUnicode_READY(self) == -1)
10920 return NULL;
10921 if (PyUnicode_READY(substring) == -1)
10922 return NULL;
10923
Victor Stinner7931d9a2011-11-04 00:22:48 +010010924 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925
10926 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 if (result == -2)
10929 return NULL;
10930
Christian Heimes217cfd12007-12-02 14:31:20 +000010931 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932}
10933
10934static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010935unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010937 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10938 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010940 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941}
10942
Guido van Rossumc2504932007-09-18 19:42:40 +000010943/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010944 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010945static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010946unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010947{
Guido van Rossumc2504932007-09-18 19:42:40 +000010948 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010949 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010951 if (_PyUnicode_HASH(self) != -1)
10952 return _PyUnicode_HASH(self);
10953 if (PyUnicode_READY(self) == -1)
10954 return -1;
10955 len = PyUnicode_GET_LENGTH(self);
10956
10957 /* The hash function as a macro, gets expanded three times below. */
10958#define HASH(P) \
10959 x = (Py_uhash_t)*P << 7; \
10960 while (--len >= 0) \
10961 x = (1000003*x) ^ (Py_uhash_t)*P++;
10962
10963 switch (PyUnicode_KIND(self)) {
10964 case PyUnicode_1BYTE_KIND: {
10965 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10966 HASH(c);
10967 break;
10968 }
10969 case PyUnicode_2BYTE_KIND: {
10970 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10971 HASH(s);
10972 break;
10973 }
10974 default: {
10975 Py_UCS4 *l;
10976 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10977 "Impossible switch case in unicode_hash");
10978 l = PyUnicode_4BYTE_DATA(self);
10979 HASH(l);
10980 break;
10981 }
10982 }
10983 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10984
Guido van Rossumc2504932007-09-18 19:42:40 +000010985 if (x == -1)
10986 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010988 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010989}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010992PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010993 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010995Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996
10997static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011000 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011001 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011002 Py_ssize_t start;
11003 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011004
Jesus Ceaac451502011-04-20 17:09:23 +020011005 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11006 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009 if (PyUnicode_READY(self) == -1)
11010 return NULL;
11011 if (PyUnicode_READY(substring) == -1)
11012 return NULL;
11013
Victor Stinner7931d9a2011-11-04 00:22:48 +010011014 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015
11016 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 if (result == -2)
11019 return NULL;
11020
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021 if (result < 0) {
11022 PyErr_SetString(PyExc_ValueError, "substring not found");
11023 return NULL;
11024 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011025
Christian Heimes217cfd12007-12-02 14:31:20 +000011026 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027}
11028
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011029PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011030 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011032Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011033at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034
11035static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011036unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011038 Py_ssize_t i, length;
11039 int kind;
11040 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041 int cased;
11042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 if (PyUnicode_READY(self) == -1)
11044 return NULL;
11045 length = PyUnicode_GET_LENGTH(self);
11046 kind = PyUnicode_KIND(self);
11047 data = PyUnicode_DATA(self);
11048
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011050 if (length == 1)
11051 return PyBool_FromLong(
11052 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011054 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011056 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011057
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059 for (i = 0; i < length; i++) {
11060 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011061
Benjamin Peterson29060642009-01-31 22:14:21 +000011062 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11063 return PyBool_FromLong(0);
11064 else if (!cased && Py_UNICODE_ISLOWER(ch))
11065 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011067 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068}
11069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011070PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011071 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011073Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011074at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075
11076static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011077unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079 Py_ssize_t i, length;
11080 int kind;
11081 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082 int cased;
11083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011084 if (PyUnicode_READY(self) == -1)
11085 return NULL;
11086 length = PyUnicode_GET_LENGTH(self);
11087 kind = PyUnicode_KIND(self);
11088 data = PyUnicode_DATA(self);
11089
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 if (length == 1)
11092 return PyBool_FromLong(
11093 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011095 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011096 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011097 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011098
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011100 for (i = 0; i < length; i++) {
11101 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011102
Benjamin Peterson29060642009-01-31 22:14:21 +000011103 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11104 return PyBool_FromLong(0);
11105 else if (!cased && Py_UNICODE_ISUPPER(ch))
11106 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011108 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109}
11110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011111PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011112 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011114Return True if S is a titlecased string and there is at least one\n\
11115character in S, i.e. upper- and titlecase characters may only\n\
11116follow uncased characters and lowercase characters only cased ones.\n\
11117Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118
11119static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011120unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122 Py_ssize_t i, length;
11123 int kind;
11124 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125 int cased, previous_is_cased;
11126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 if (PyUnicode_READY(self) == -1)
11128 return NULL;
11129 length = PyUnicode_GET_LENGTH(self);
11130 kind = PyUnicode_KIND(self);
11131 data = PyUnicode_DATA(self);
11132
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 if (length == 1) {
11135 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11136 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11137 (Py_UNICODE_ISUPPER(ch) != 0));
11138 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011140 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011142 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011143
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144 cased = 0;
11145 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 for (i = 0; i < length; i++) {
11147 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011148
Benjamin Peterson29060642009-01-31 22:14:21 +000011149 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11150 if (previous_is_cased)
11151 return PyBool_FromLong(0);
11152 previous_is_cased = 1;
11153 cased = 1;
11154 }
11155 else if (Py_UNICODE_ISLOWER(ch)) {
11156 if (!previous_is_cased)
11157 return PyBool_FromLong(0);
11158 previous_is_cased = 1;
11159 cased = 1;
11160 }
11161 else
11162 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011164 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165}
11166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011167PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011168 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011170Return True if all characters in S are whitespace\n\
11171and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172
11173static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011174unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 Py_ssize_t i, length;
11177 int kind;
11178 void *data;
11179
11180 if (PyUnicode_READY(self) == -1)
11181 return NULL;
11182 length = PyUnicode_GET_LENGTH(self);
11183 kind = PyUnicode_KIND(self);
11184 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011187 if (length == 1)
11188 return PyBool_FromLong(
11189 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011191 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011193 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 for (i = 0; i < length; i++) {
11196 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011197 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011200 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201}
11202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011203PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011205\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011206Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011207and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011208
11209static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011210unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 Py_ssize_t i, length;
11213 int kind;
11214 void *data;
11215
11216 if (PyUnicode_READY(self) == -1)
11217 return NULL;
11218 length = PyUnicode_GET_LENGTH(self);
11219 kind = PyUnicode_KIND(self);
11220 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011221
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011222 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 if (length == 1)
11224 return PyBool_FromLong(
11225 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011226
11227 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011229 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011230
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 for (i = 0; i < length; i++) {
11232 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011234 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011235 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011236}
11237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011238PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011239 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011240\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011241Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011242and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011243
11244static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011245unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011246{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 int kind;
11248 void *data;
11249 Py_ssize_t len, i;
11250
11251 if (PyUnicode_READY(self) == -1)
11252 return NULL;
11253
11254 kind = PyUnicode_KIND(self);
11255 data = PyUnicode_DATA(self);
11256 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011257
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011258 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 if (len == 1) {
11260 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11261 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11262 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011263
11264 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011265 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 for (i = 0; i < len; i++) {
11269 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011270 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011272 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011273 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011274}
11275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011276PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011279Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011280False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
11282static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011283unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285 Py_ssize_t i, length;
11286 int kind;
11287 void *data;
11288
11289 if (PyUnicode_READY(self) == -1)
11290 return NULL;
11291 length = PyUnicode_GET_LENGTH(self);
11292 kind = PyUnicode_KIND(self);
11293 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 if (length == 1)
11297 return PyBool_FromLong(
11298 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011300 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011302 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011303
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 for (i = 0; i < length; i++) {
11305 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011306 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011308 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309}
11310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011311PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011312 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011314Return True if all characters in S are digits\n\
11315and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316
11317static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011318unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 Py_ssize_t i, length;
11321 int kind;
11322 void *data;
11323
11324 if (PyUnicode_READY(self) == -1)
11325 return NULL;
11326 length = PyUnicode_GET_LENGTH(self);
11327 kind = PyUnicode_KIND(self);
11328 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 if (length == 1) {
11332 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11333 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11334 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011336 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 for (i = 0; i < length; i++) {
11341 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011342 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011344 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345}
11346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011347PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011350Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011351False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352
11353static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011354unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 Py_ssize_t i, length;
11357 int kind;
11358 void *data;
11359
11360 if (PyUnicode_READY(self) == -1)
11361 return NULL;
11362 length = PyUnicode_GET_LENGTH(self);
11363 kind = PyUnicode_KIND(self);
11364 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 if (length == 1)
11368 return PyBool_FromLong(
11369 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011371 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 for (i = 0; i < length; i++) {
11376 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011377 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011379 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380}
11381
Martin v. Löwis47383402007-08-15 07:32:56 +000011382int
11383PyUnicode_IsIdentifier(PyObject *self)
11384{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 int kind;
11386 void *data;
11387 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011388 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 if (PyUnicode_READY(self) == -1) {
11391 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011392 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 }
11394
11395 /* Special case for empty strings */
11396 if (PyUnicode_GET_LENGTH(self) == 0)
11397 return 0;
11398 kind = PyUnicode_KIND(self);
11399 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011400
11401 /* PEP 3131 says that the first character must be in
11402 XID_Start and subsequent characters in XID_Continue,
11403 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011404 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011405 letters, digits, underscore). However, given the current
11406 definition of XID_Start and XID_Continue, it is sufficient
11407 to check just for these, except that _ must be allowed
11408 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011410 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011411 return 0;
11412
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011413 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011414 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011415 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011416 return 1;
11417}
11418
11419PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011421\n\
11422Return True if S is a valid identifier according\n\
11423to the language definition.");
11424
11425static PyObject*
11426unicode_isidentifier(PyObject *self)
11427{
11428 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11429}
11430
Georg Brandl559e5d72008-06-11 18:37:52 +000011431PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011433\n\
11434Return True if all characters in S are considered\n\
11435printable in repr() or S is empty, False otherwise.");
11436
11437static PyObject*
11438unicode_isprintable(PyObject *self)
11439{
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);
Georg Brandl559e5d72008-06-11 18:37:52 +000011449
11450 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 if (length == 1)
11452 return PyBool_FromLong(
11453 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011455 for (i = 0; i < length; i++) {
11456 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011457 Py_RETURN_FALSE;
11458 }
11459 }
11460 Py_RETURN_TRUE;
11461}
11462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011463PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011464 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465\n\
11466Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011467iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468
11469static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011470unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011472 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473}
11474
Martin v. Löwis18e16552006-02-15 17:27:45 +000011475static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011476unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 if (PyUnicode_READY(self) == -1)
11479 return -1;
11480 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481}
11482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011483PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011486Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011487done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488
11489static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011490unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011492 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 Py_UCS4 fillchar = ' ';
11494
11495 if (PyUnicode_READY(self) == -1)
11496 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011497
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011498 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 return NULL;
11500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011503 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504 }
11505
Victor Stinner7931d9a2011-11-04 00:22:48 +010011506 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507}
11508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011509PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011510 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011512Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513
11514static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011515unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 return fixup(self, fixlower);
11518}
11519
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011520#define LEFTSTRIP 0
11521#define RIGHTSTRIP 1
11522#define BOTHSTRIP 2
11523
11524/* Arrays indexed by above */
11525static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11526
11527#define STRIPNAME(i) (stripformat[i]+3)
11528
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011529/* externally visible for str.strip(unicode) */
11530PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011531_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 void *data;
11534 int kind;
11535 Py_ssize_t i, j, len;
11536 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11539 return NULL;
11540
11541 kind = PyUnicode_KIND(self);
11542 data = PyUnicode_DATA(self);
11543 len = PyUnicode_GET_LENGTH(self);
11544 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11545 PyUnicode_DATA(sepobj),
11546 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011547
Benjamin Peterson14339b62009-01-31 16:36:08 +000011548 i = 0;
11549 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 while (i < len &&
11551 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 i++;
11553 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011554 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011555
Benjamin Peterson14339b62009-01-31 16:36:08 +000011556 j = len;
11557 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 do {
11559 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 } while (j >= i &&
11561 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011563 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011564
Victor Stinner7931d9a2011-11-04 00:22:48 +010011565 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566}
11567
11568PyObject*
11569PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11570{
11571 unsigned char *data;
11572 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011573 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574
Victor Stinnerde636f32011-10-01 03:55:54 +020011575 if (PyUnicode_READY(self) == -1)
11576 return NULL;
11577
11578 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11579
Victor Stinner12bab6d2011-10-01 01:53:49 +020011580 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011582 if (PyUnicode_CheckExact(self)) {
11583 Py_INCREF(self);
11584 return self;
11585 }
11586 else
11587 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 }
11589
Victor Stinner12bab6d2011-10-01 01:53:49 +020011590 length = end - start;
11591 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011592 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593
Victor Stinnerde636f32011-10-01 03:55:54 +020011594 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011595 PyErr_SetString(PyExc_IndexError, "string index out of range");
11596 return NULL;
11597 }
11598
Victor Stinnerb9275c12011-10-05 14:01:42 +020011599 if (PyUnicode_IS_ASCII(self)) {
11600 kind = PyUnicode_KIND(self);
11601 data = PyUnicode_1BYTE_DATA(self);
11602 return unicode_fromascii(data + start, length);
11603 }
11604 else {
11605 kind = PyUnicode_KIND(self);
11606 data = PyUnicode_1BYTE_DATA(self);
11607 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011608 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011609 length);
11610 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011611}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612
11613static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011614do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 int kind;
11617 void *data;
11618 Py_ssize_t len, i, j;
11619
11620 if (PyUnicode_READY(self) == -1)
11621 return NULL;
11622
11623 kind = PyUnicode_KIND(self);
11624 data = PyUnicode_DATA(self);
11625 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011626
Benjamin Peterson14339b62009-01-31 16:36:08 +000011627 i = 0;
11628 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011630 i++;
11631 }
11632 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011633
Benjamin Peterson14339b62009-01-31 16:36:08 +000011634 j = len;
11635 if (striptype != LEFTSTRIP) {
11636 do {
11637 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011639 j++;
11640 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011641
Victor Stinner7931d9a2011-11-04 00:22:48 +010011642 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643}
11644
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011645
11646static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011647do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011648{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011649 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011650
Benjamin Peterson14339b62009-01-31 16:36:08 +000011651 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11652 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011653
Benjamin Peterson14339b62009-01-31 16:36:08 +000011654 if (sep != NULL && sep != Py_None) {
11655 if (PyUnicode_Check(sep))
11656 return _PyUnicode_XStrip(self, striptype, sep);
11657 else {
11658 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 "%s arg must be None or str",
11660 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011661 return NULL;
11662 }
11663 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011664
Benjamin Peterson14339b62009-01-31 16:36:08 +000011665 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011666}
11667
11668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011669PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011670 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011671\n\
11672Return a copy of the string S with leading and trailing\n\
11673whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011674If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011675
11676static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011677unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011678{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011679 if (PyTuple_GET_SIZE(args) == 0)
11680 return do_strip(self, BOTHSTRIP); /* Common case */
11681 else
11682 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011683}
11684
11685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011686PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011688\n\
11689Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011690If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011691
11692static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011693unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011694{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011695 if (PyTuple_GET_SIZE(args) == 0)
11696 return do_strip(self, LEFTSTRIP); /* Common case */
11697 else
11698 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011699}
11700
11701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011702PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011703 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011704\n\
11705Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011706If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011707
11708static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011709unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011711 if (PyTuple_GET_SIZE(args) == 0)
11712 return do_strip(self, RIGHTSTRIP); /* Common case */
11713 else
11714 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011715}
11716
11717
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011719unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011721 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723
Georg Brandl222de0f2009-04-12 12:01:50 +000011724 if (len < 1) {
11725 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011726 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011727 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728
Tim Peters7a29bd52001-09-12 03:03:31 +000011729 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730 /* no repeat, return original string */
11731 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011732 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733 }
Tim Peters8f422462000-09-09 06:13:41 +000011734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 if (PyUnicode_READY(str) == -1)
11736 return NULL;
11737
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011738 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011739 PyErr_SetString(PyExc_OverflowError,
11740 "repeated string is too long");
11741 return NULL;
11742 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011744
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011745 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 if (!u)
11747 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011748 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011750 if (PyUnicode_GET_LENGTH(str) == 1) {
11751 const int kind = PyUnicode_KIND(str);
11752 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11753 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011754 if (kind == PyUnicode_1BYTE_KIND)
11755 memset(to, (unsigned char)fill_char, len);
11756 else {
11757 for (n = 0; n < len; ++n)
11758 PyUnicode_WRITE(kind, to, n, fill_char);
11759 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 }
11761 else {
11762 /* number of characters copied this far */
11763 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011764 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 char *to = (char *) PyUnicode_DATA(u);
11766 Py_MEMCPY(to, PyUnicode_DATA(str),
11767 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 n = (done <= nchars-done) ? done : nchars-done;
11770 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011771 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011772 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 }
11774
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011775 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011776 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777}
11778
Alexander Belopolsky40018472011-02-26 01:02:56 +000011779PyObject *
11780PyUnicode_Replace(PyObject *obj,
11781 PyObject *subobj,
11782 PyObject *replobj,
11783 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784{
11785 PyObject *self;
11786 PyObject *str1;
11787 PyObject *str2;
11788 PyObject *result;
11789
11790 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011791 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011794 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011795 Py_DECREF(self);
11796 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797 }
11798 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011799 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011800 Py_DECREF(self);
11801 Py_DECREF(str1);
11802 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805 Py_DECREF(self);
11806 Py_DECREF(str1);
11807 Py_DECREF(str2);
11808 return result;
11809}
11810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011811PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011812 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813\n\
11814Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011815old replaced by new. If the optional argument count is\n\
11816given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817
11818static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 PyObject *str1;
11822 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011823 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824 PyObject *result;
11825
Martin v. Löwis18e16552006-02-15 17:27:45 +000011826 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011828 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 str1 = PyUnicode_FromObject(str1);
11831 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11832 return NULL;
11833 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011834 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011835 Py_DECREF(str1);
11836 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011837 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838
11839 result = replace(self, str1, str2, maxcount);
11840
11841 Py_DECREF(str1);
11842 Py_DECREF(str2);
11843 return result;
11844}
11845
Alexander Belopolsky40018472011-02-26 01:02:56 +000011846static PyObject *
11847unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011849 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 Py_ssize_t isize;
11851 Py_ssize_t osize, squote, dquote, i, o;
11852 Py_UCS4 max, quote;
11853 int ikind, okind;
11854 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011857 return NULL;
11858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 isize = PyUnicode_GET_LENGTH(unicode);
11860 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 /* Compute length of output, quote characters, and
11863 maximum character */
11864 osize = 2; /* quotes */
11865 max = 127;
11866 squote = dquote = 0;
11867 ikind = PyUnicode_KIND(unicode);
11868 for (i = 0; i < isize; i++) {
11869 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11870 switch (ch) {
11871 case '\'': squote++; osize++; break;
11872 case '"': dquote++; osize++; break;
11873 case '\\': case '\t': case '\r': case '\n':
11874 osize += 2; break;
11875 default:
11876 /* Fast-path ASCII */
11877 if (ch < ' ' || ch == 0x7f)
11878 osize += 4; /* \xHH */
11879 else if (ch < 0x7f)
11880 osize++;
11881 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11882 osize++;
11883 max = ch > max ? ch : max;
11884 }
11885 else if (ch < 0x100)
11886 osize += 4; /* \xHH */
11887 else if (ch < 0x10000)
11888 osize += 6; /* \uHHHH */
11889 else
11890 osize += 10; /* \uHHHHHHHH */
11891 }
11892 }
11893
11894 quote = '\'';
11895 if (squote) {
11896 if (dquote)
11897 /* Both squote and dquote present. Use squote,
11898 and escape them */
11899 osize += squote;
11900 else
11901 quote = '"';
11902 }
11903
11904 repr = PyUnicode_New(osize, max);
11905 if (repr == NULL)
11906 return NULL;
11907 okind = PyUnicode_KIND(repr);
11908 odata = PyUnicode_DATA(repr);
11909
11910 PyUnicode_WRITE(okind, odata, 0, quote);
11911 PyUnicode_WRITE(okind, odata, osize-1, quote);
11912
11913 for (i = 0, o = 1; i < isize; i++) {
11914 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011915
11916 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 if ((ch == quote) || (ch == '\\')) {
11918 PyUnicode_WRITE(okind, odata, o++, '\\');
11919 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011920 continue;
11921 }
11922
Benjamin Peterson29060642009-01-31 22:14:21 +000011923 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011924 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 PyUnicode_WRITE(okind, odata, o++, '\\');
11926 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011927 }
11928 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 PyUnicode_WRITE(okind, odata, o++, '\\');
11930 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011931 }
11932 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 PyUnicode_WRITE(okind, odata, o++, '\\');
11934 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011935 }
11936
11937 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011938 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 PyUnicode_WRITE(okind, odata, o++, '\\');
11940 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011941 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11942 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011943 }
11944
Georg Brandl559e5d72008-06-11 18:37:52 +000011945 /* Copy ASCII characters as-is */
11946 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011948 }
11949
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011951 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011952 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011953 (categories Z* and C* except ASCII space)
11954 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011956 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011957 if (ch <= 0xff) {
11958 PyUnicode_WRITE(okind, odata, o++, '\\');
11959 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011960 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11961 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011962 }
11963 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 else if (ch >= 0x10000) {
11965 PyUnicode_WRITE(okind, odata, o++, '\\');
11966 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011967 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
11968 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
11969 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
11970 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
11971 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
11972 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
11973 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
11974 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011975 }
11976 /* Map 16-bit characters to '\uxxxx' */
11977 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011978 PyUnicode_WRITE(okind, odata, o++, '\\');
11979 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011980 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
11981 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
11982 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
11983 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011984 }
11985 }
11986 /* Copy characters as-is */
11987 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011989 }
11990 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011991 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011993 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011994 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995}
11996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011997PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011998 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999\n\
12000Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012001such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002arguments start and end are interpreted as in slice notation.\n\
12003\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012004Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005
12006static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012008{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012009 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012010 Py_ssize_t start;
12011 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012012 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013
Jesus Ceaac451502011-04-20 17:09:23 +020012014 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12015 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012016 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 if (PyUnicode_READY(self) == -1)
12019 return NULL;
12020 if (PyUnicode_READY(substring) == -1)
12021 return NULL;
12022
Victor Stinner7931d9a2011-11-04 00:22:48 +010012023 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024
12025 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012027 if (result == -2)
12028 return NULL;
12029
Christian Heimes217cfd12007-12-02 14:31:20 +000012030 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031}
12032
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012033PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012034 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012036Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037
12038static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012041 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012042 Py_ssize_t start;
12043 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012044 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045
Jesus Ceaac451502011-04-20 17:09:23 +020012046 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12047 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012048 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 if (PyUnicode_READY(self) == -1)
12051 return NULL;
12052 if (PyUnicode_READY(substring) == -1)
12053 return NULL;
12054
Victor Stinner7931d9a2011-11-04 00:22:48 +010012055 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056
12057 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 if (result == -2)
12060 return NULL;
12061
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062 if (result < 0) {
12063 PyErr_SetString(PyExc_ValueError, "substring not found");
12064 return NULL;
12065 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066
Christian Heimes217cfd12007-12-02 14:31:20 +000012067 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068}
12069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012070PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012071 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012073Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012074done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075
12076static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012077unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012079 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 Py_UCS4 fillchar = ' ';
12081
Victor Stinnere9a29352011-10-01 02:14:59 +020012082 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012084
Victor Stinnere9a29352011-10-01 02:14:59 +020012085 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086 return NULL;
12087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012089 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012090 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091 }
12092
Victor Stinner7931d9a2011-11-04 00:22:48 +010012093 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094}
12095
Alexander Belopolsky40018472011-02-26 01:02:56 +000012096PyObject *
12097PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098{
12099 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012100
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101 s = PyUnicode_FromObject(s);
12102 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012103 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012104 if (sep != NULL) {
12105 sep = PyUnicode_FromObject(sep);
12106 if (sep == NULL) {
12107 Py_DECREF(s);
12108 return NULL;
12109 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110 }
12111
Victor Stinner9310abb2011-10-05 00:59:23 +020012112 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
12114 Py_DECREF(s);
12115 Py_XDECREF(sep);
12116 return result;
12117}
12118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012119PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012120 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121\n\
12122Return a list of the words in S, using sep as the\n\
12123delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012124splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012125whitespace string is a separator and empty strings are\n\
12126removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
12128static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012129unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130{
12131 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012132 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133
Martin v. Löwis18e16552006-02-15 17:27:45 +000012134 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012135 return NULL;
12136
12137 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012138 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012140 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012142 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143}
12144
Thomas Wouters477c8d52006-05-27 19:21:47 +000012145PyObject *
12146PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12147{
12148 PyObject* str_obj;
12149 PyObject* sep_obj;
12150 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 int kind1, kind2, kind;
12152 void *buf1 = NULL, *buf2 = NULL;
12153 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012154
12155 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012156 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012158 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012160 Py_DECREF(str_obj);
12161 return NULL;
12162 }
12163
Victor Stinner14f8f022011-10-05 20:58:25 +020012164 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012165 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012166 kind = Py_MAX(kind1, kind2);
12167 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012169 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 if (!buf1)
12171 goto onError;
12172 buf2 = PyUnicode_DATA(sep_obj);
12173 if (kind2 != kind)
12174 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12175 if (!buf2)
12176 goto onError;
12177 len1 = PyUnicode_GET_LENGTH(str_obj);
12178 len2 = PyUnicode_GET_LENGTH(sep_obj);
12179
Victor Stinner14f8f022011-10-05 20:58:25 +020012180 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012181 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012182 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12183 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12184 else
12185 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012186 break;
12187 case PyUnicode_2BYTE_KIND:
12188 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12189 break;
12190 case PyUnicode_4BYTE_KIND:
12191 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12192 break;
12193 default:
12194 assert(0);
12195 out = 0;
12196 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012197
12198 Py_DECREF(sep_obj);
12199 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 if (kind1 != kind)
12201 PyMem_Free(buf1);
12202 if (kind2 != kind)
12203 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012204
12205 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 onError:
12207 Py_DECREF(sep_obj);
12208 Py_DECREF(str_obj);
12209 if (kind1 != kind && buf1)
12210 PyMem_Free(buf1);
12211 if (kind2 != kind && buf2)
12212 PyMem_Free(buf2);
12213 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012214}
12215
12216
12217PyObject *
12218PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12219{
12220 PyObject* str_obj;
12221 PyObject* sep_obj;
12222 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 int kind1, kind2, kind;
12224 void *buf1 = NULL, *buf2 = NULL;
12225 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012226
12227 str_obj = PyUnicode_FromObject(str_in);
12228 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012229 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012230 sep_obj = PyUnicode_FromObject(sep_in);
12231 if (!sep_obj) {
12232 Py_DECREF(str_obj);
12233 return NULL;
12234 }
12235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 kind1 = PyUnicode_KIND(str_in);
12237 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012238 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 buf1 = PyUnicode_DATA(str_in);
12240 if (kind1 != kind)
12241 buf1 = _PyUnicode_AsKind(str_in, kind);
12242 if (!buf1)
12243 goto onError;
12244 buf2 = PyUnicode_DATA(sep_obj);
12245 if (kind2 != kind)
12246 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12247 if (!buf2)
12248 goto onError;
12249 len1 = PyUnicode_GET_LENGTH(str_obj);
12250 len2 = PyUnicode_GET_LENGTH(sep_obj);
12251
12252 switch(PyUnicode_KIND(str_in)) {
12253 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012254 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12255 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12256 else
12257 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258 break;
12259 case PyUnicode_2BYTE_KIND:
12260 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12261 break;
12262 case PyUnicode_4BYTE_KIND:
12263 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12264 break;
12265 default:
12266 assert(0);
12267 out = 0;
12268 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012269
12270 Py_DECREF(sep_obj);
12271 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 if (kind1 != kind)
12273 PyMem_Free(buf1);
12274 if (kind2 != kind)
12275 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012276
12277 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 onError:
12279 Py_DECREF(sep_obj);
12280 Py_DECREF(str_obj);
12281 if (kind1 != kind && buf1)
12282 PyMem_Free(buf1);
12283 if (kind2 != kind && buf2)
12284 PyMem_Free(buf2);
12285 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012286}
12287
12288PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012289 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012290\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012291Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012293found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012294
12295static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012296unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012297{
Victor Stinner9310abb2011-10-05 00:59:23 +020012298 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012299}
12300
12301PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012302 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012303\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012304Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012305the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012306separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012307
12308static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012309unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012310{
Victor Stinner9310abb2011-10-05 00:59:23 +020012311 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012312}
12313
Alexander Belopolsky40018472011-02-26 01:02:56 +000012314PyObject *
12315PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012316{
12317 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012318
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012319 s = PyUnicode_FromObject(s);
12320 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012321 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012322 if (sep != NULL) {
12323 sep = PyUnicode_FromObject(sep);
12324 if (sep == NULL) {
12325 Py_DECREF(s);
12326 return NULL;
12327 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012328 }
12329
Victor Stinner9310abb2011-10-05 00:59:23 +020012330 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012331
12332 Py_DECREF(s);
12333 Py_XDECREF(sep);
12334 return result;
12335}
12336
12337PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012338 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012339\n\
12340Return a list of the words in S, using sep as the\n\
12341delimiter string, starting at the end of the string and\n\
12342working to the front. If maxsplit is given, at most maxsplit\n\
12343splits are done. If sep is not specified, any whitespace string\n\
12344is a separator.");
12345
12346static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012347unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012348{
12349 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012350 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012351
Martin v. Löwis18e16552006-02-15 17:27:45 +000012352 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012353 return NULL;
12354
12355 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012356 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012357 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012358 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012359 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012360 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012361}
12362
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012363PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012364 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365\n\
12366Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012367Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012368is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369
12370static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012371unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012373 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012374 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012376 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12377 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378 return NULL;
12379
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012380 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012381}
12382
12383static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012384PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385{
Walter Dörwald346737f2007-05-31 10:44:43 +000012386 if (PyUnicode_CheckExact(self)) {
12387 Py_INCREF(self);
12388 return self;
12389 } else
12390 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012391 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012392}
12393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012394PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012395 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012396\n\
12397Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012398and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012399
12400static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012401unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012402{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403 return fixup(self, fixswapcase);
12404}
12405
Georg Brandlceee0772007-11-27 23:48:05 +000012406PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012407 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012408\n\
12409Return a translation table usable for str.translate().\n\
12410If there is only one argument, it must be a dictionary mapping Unicode\n\
12411ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012412Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012413If there are two arguments, they must be strings of equal length, and\n\
12414in the resulting dictionary, each character in x will be mapped to the\n\
12415character at the same position in y. If there is a third argument, it\n\
12416must be a string, whose characters will be mapped to None in the result.");
12417
12418static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012419unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012420{
12421 PyObject *x, *y = NULL, *z = NULL;
12422 PyObject *new = NULL, *key, *value;
12423 Py_ssize_t i = 0;
12424 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012425
Georg Brandlceee0772007-11-27 23:48:05 +000012426 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12427 return NULL;
12428 new = PyDict_New();
12429 if (!new)
12430 return NULL;
12431 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 int x_kind, y_kind, z_kind;
12433 void *x_data, *y_data, *z_data;
12434
Georg Brandlceee0772007-11-27 23:48:05 +000012435 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012436 if (!PyUnicode_Check(x)) {
12437 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12438 "be a string if there is a second argument");
12439 goto err;
12440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012442 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12443 "arguments must have equal length");
12444 goto err;
12445 }
12446 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012447 x_kind = PyUnicode_KIND(x);
12448 y_kind = PyUnicode_KIND(y);
12449 x_data = PyUnicode_DATA(x);
12450 y_data = PyUnicode_DATA(y);
12451 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12452 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12453 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012454 if (!key || !value)
12455 goto err;
12456 res = PyDict_SetItem(new, key, value);
12457 Py_DECREF(key);
12458 Py_DECREF(value);
12459 if (res < 0)
12460 goto err;
12461 }
12462 /* create entries for deleting chars in z */
12463 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464 z_kind = PyUnicode_KIND(z);
12465 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012466 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012467 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012468 if (!key)
12469 goto err;
12470 res = PyDict_SetItem(new, key, Py_None);
12471 Py_DECREF(key);
12472 if (res < 0)
12473 goto err;
12474 }
12475 }
12476 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 int kind;
12478 void *data;
12479
Georg Brandlceee0772007-11-27 23:48:05 +000012480 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012481 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012482 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12483 "to maketrans it must be a dict");
12484 goto err;
12485 }
12486 /* copy entries into the new dict, converting string keys to int keys */
12487 while (PyDict_Next(x, &i, &key, &value)) {
12488 if (PyUnicode_Check(key)) {
12489 /* convert string keys to integer keys */
12490 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012491 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012492 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12493 "table must be of length 1");
12494 goto err;
12495 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496 kind = PyUnicode_KIND(key);
12497 data = PyUnicode_DATA(key);
12498 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012499 if (!newkey)
12500 goto err;
12501 res = PyDict_SetItem(new, newkey, value);
12502 Py_DECREF(newkey);
12503 if (res < 0)
12504 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012505 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012506 /* just keep integer keys */
12507 if (PyDict_SetItem(new, key, value) < 0)
12508 goto err;
12509 } else {
12510 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12511 "be strings or integers");
12512 goto err;
12513 }
12514 }
12515 }
12516 return new;
12517 err:
12518 Py_DECREF(new);
12519 return NULL;
12520}
12521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012522PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012523 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524\n\
12525Return a copy of the string S, where all characters have been mapped\n\
12526through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012527Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012528Unmapped characters are left untouched. Characters mapped to None\n\
12529are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530
12531static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535}
12536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012537PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012538 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012540Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541
12542static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012543unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545 return fixup(self, fixupper);
12546}
12547
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012548PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012549 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012550\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012551Pad a numeric string S with zeros on the left, to fill a field\n\
12552of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012553
12554static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012555unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012556{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012557 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012558 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012559 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 int kind;
12561 void *data;
12562 Py_UCS4 chr;
12563
12564 if (PyUnicode_READY(self) == -1)
12565 return NULL;
12566
Martin v. Löwis18e16552006-02-15 17:27:45 +000012567 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568 return NULL;
12569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012571 if (PyUnicode_CheckExact(self)) {
12572 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012573 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012574 }
12575 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012576 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577 }
12578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580
12581 u = pad(self, fill, 0, '0');
12582
Walter Dörwald068325e2002-04-15 13:36:47 +000012583 if (u == NULL)
12584 return NULL;
12585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 kind = PyUnicode_KIND(u);
12587 data = PyUnicode_DATA(u);
12588 chr = PyUnicode_READ(kind, data, fill);
12589
12590 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 PyUnicode_WRITE(kind, data, 0, chr);
12593 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594 }
12595
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012596 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012597 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599
12600#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012601static PyObject *
12602unicode__decimal2ascii(PyObject *self)
12603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012605}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606#endif
12607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012608PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012609 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012611Return True if S starts with the specified prefix, False otherwise.\n\
12612With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012613With optional end, stop comparing S at that position.\n\
12614prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615
12616static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012617unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012618 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012620 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012621 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012622 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012623 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012624 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625
Jesus Ceaac451502011-04-20 17:09:23 +020012626 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012627 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012628 if (PyTuple_Check(subobj)) {
12629 Py_ssize_t i;
12630 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012631 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012632 if (substring == NULL)
12633 return NULL;
12634 result = tailmatch(self, substring, start, end, -1);
12635 Py_DECREF(substring);
12636 if (result) {
12637 Py_RETURN_TRUE;
12638 }
12639 }
12640 /* nothing matched */
12641 Py_RETURN_FALSE;
12642 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012643 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012644 if (substring == NULL) {
12645 if (PyErr_ExceptionMatches(PyExc_TypeError))
12646 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12647 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012648 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012649 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012650 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012652 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653}
12654
12655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012656PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012657 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012659Return True if S ends with the specified suffix, False otherwise.\n\
12660With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012661With optional end, stop comparing S at that position.\n\
12662suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663
12664static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012665unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012666 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012668 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012669 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012670 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012671 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012672 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673
Jesus Ceaac451502011-04-20 17:09:23 +020012674 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012675 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012676 if (PyTuple_Check(subobj)) {
12677 Py_ssize_t i;
12678 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012679 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012680 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012681 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012682 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012683 result = tailmatch(self, substring, start, end, +1);
12684 Py_DECREF(substring);
12685 if (result) {
12686 Py_RETURN_TRUE;
12687 }
12688 }
12689 Py_RETURN_FALSE;
12690 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012691 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012692 if (substring == NULL) {
12693 if (PyErr_ExceptionMatches(PyExc_TypeError))
12694 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12695 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012696 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012697 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012698 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012700 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701}
12702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012704
12705PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012706 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012707\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012708Return a formatted version of S, using substitutions from args and kwargs.\n\
12709The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012710
Eric Smith27bbca62010-11-04 17:06:58 +000012711PyDoc_STRVAR(format_map__doc__,
12712 "S.format_map(mapping) -> str\n\
12713\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012714Return a formatted version of S, using substitutions from mapping.\n\
12715The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012716
Eric Smith4a7d76d2008-05-30 18:10:19 +000012717static PyObject *
12718unicode__format__(PyObject* self, PyObject* args)
12719{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012720 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012721
12722 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12723 return NULL;
12724
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012725 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012727 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012728}
12729
Eric Smith8c663262007-08-25 02:26:07 +000012730PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012731 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012732\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012733Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012734
12735static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012736unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012737{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 Py_ssize_t size;
12739
12740 /* If it's a compact object, account for base structure +
12741 character data. */
12742 if (PyUnicode_IS_COMPACT_ASCII(v))
12743 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12744 else if (PyUnicode_IS_COMPACT(v))
12745 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012746 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 else {
12748 /* If it is a two-block object, account for base object, and
12749 for character block if present. */
12750 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012751 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012752 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012753 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754 }
12755 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012756 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012757 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012759 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012760 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761
12762 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012763}
12764
12765PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012767
12768static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012769unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012770{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012771 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772 if (!copy)
12773 return NULL;
12774 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012775}
12776
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777static PyMethodDef unicode_methods[] = {
12778
12779 /* Order is according to common usage: often used methods should
12780 appear first, since lookup is done sequentially. */
12781
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012782 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012783 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12784 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012785 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012786 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12787 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12788 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12789 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12790 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12791 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12792 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012793 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012794 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12795 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12796 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012797 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012798 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12799 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12800 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012801 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012803 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012804 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012805 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12806 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12807 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12808 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12809 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12810 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12811 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12812 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12813 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12814 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12815 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12816 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12817 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12818 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012819 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012820 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012821 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012822 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012823 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012824 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012825 {"maketrans", (PyCFunction) unicode_maketrans,
12826 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012827 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012828#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012829 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830#endif
12831
12832#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012833 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012834 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012835#endif
12836
Benjamin Peterson14339b62009-01-31 16:36:08 +000012837 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838 {NULL, NULL}
12839};
12840
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012841static PyObject *
12842unicode_mod(PyObject *v, PyObject *w)
12843{
Brian Curtindfc80e32011-08-10 20:28:54 -050012844 if (!PyUnicode_Check(v))
12845 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012846 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012847}
12848
12849static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012850 0, /*nb_add*/
12851 0, /*nb_subtract*/
12852 0, /*nb_multiply*/
12853 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012854};
12855
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012857 (lenfunc) unicode_length, /* sq_length */
12858 PyUnicode_Concat, /* sq_concat */
12859 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12860 (ssizeargfunc) unicode_getitem, /* sq_item */
12861 0, /* sq_slice */
12862 0, /* sq_ass_item */
12863 0, /* sq_ass_slice */
12864 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865};
12866
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012867static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012868unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012869{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012870 if (PyUnicode_READY(self) == -1)
12871 return NULL;
12872
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012873 if (PyIndex_Check(item)) {
12874 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012875 if (i == -1 && PyErr_Occurred())
12876 return NULL;
12877 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012879 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012880 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012881 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012882 PyObject *result;
12883 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012884 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012885 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012887 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012888 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012889 return NULL;
12890 }
12891
12892 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010012893 Py_INCREF(unicode_empty);
12894 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 } else if (start == 0 && step == 1 &&
12896 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012897 PyUnicode_CheckExact(self)) {
12898 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012899 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000012900 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012901 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020012902 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012903 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012904 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012905 src_kind = PyUnicode_KIND(self);
12906 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020012907 if (!PyUnicode_IS_ASCII(self)) {
12908 kind_limit = kind_maxchar_limit(src_kind);
12909 max_char = 0;
12910 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12911 ch = PyUnicode_READ(src_kind, src_data, cur);
12912 if (ch > max_char) {
12913 max_char = ch;
12914 if (max_char >= kind_limit)
12915 break;
12916 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012917 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012918 }
Victor Stinner55c99112011-10-13 01:17:06 +020012919 else
12920 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012921 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012922 if (result == NULL)
12923 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012924 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012925 dest_data = PyUnicode_DATA(result);
12926
12927 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012928 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12929 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012930 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012931 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012932 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012933 } else {
12934 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12935 return NULL;
12936 }
12937}
12938
12939static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012940 (lenfunc)unicode_length, /* mp_length */
12941 (binaryfunc)unicode_subscript, /* mp_subscript */
12942 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012943};
12944
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945
Guido van Rossumd57fd912000-03-10 22:53:23 +000012946/* Helpers for PyUnicode_Format() */
12947
12948static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012949getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012951 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 (*p_argidx)++;
12954 if (arglen < 0)
12955 return args;
12956 else
12957 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012958 }
12959 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012960 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012961 return NULL;
12962}
12963
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012964/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012965
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012966static PyObject *
12967formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012968{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012969 char *p;
12970 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012971 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012972
Guido van Rossumd57fd912000-03-10 22:53:23 +000012973 x = PyFloat_AsDouble(v);
12974 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012975 return NULL;
12976
Guido van Rossumd57fd912000-03-10 22:53:23 +000012977 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012978 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012979
Eric Smith0923d1d2009-04-16 20:16:10 +000012980 p = PyOS_double_to_string(x, type, prec,
12981 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012982 if (p == NULL)
12983 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012985 PyMem_Free(p);
12986 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012987}
12988
Tim Peters38fd5b62000-09-21 05:43:11 +000012989static PyObject*
12990formatlong(PyObject *val, int flags, int prec, int type)
12991{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012992 char *buf;
12993 int len;
12994 PyObject *str; /* temporary string object. */
12995 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012996
Benjamin Peterson14339b62009-01-31 16:36:08 +000012997 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12998 if (!str)
12999 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013001 Py_DECREF(str);
13002 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013003}
13004
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013005static Py_UCS4
13006formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013007{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013008 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013009 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013011 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013012 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013013 goto onError;
13014 }
13015 else {
13016 /* Integer input truncated to a character */
13017 long x;
13018 x = PyLong_AsLong(v);
13019 if (x == -1 && PyErr_Occurred())
13020 goto onError;
13021
Victor Stinner8faf8212011-12-08 22:14:11 +010013022 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013023 PyErr_SetString(PyExc_OverflowError,
13024 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013025 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013026 }
13027
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013028 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013029 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013030
Benjamin Peterson29060642009-01-31 22:14:21 +000013031 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013032 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013033 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013034 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013035}
13036
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013037static int
13038repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13039{
13040 int r;
13041 assert(count > 0);
13042 assert(PyUnicode_Check(obj));
13043 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013044 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013045 if (repeated == NULL)
13046 return -1;
13047 r = _PyAccu_Accumulate(acc, repeated);
13048 Py_DECREF(repeated);
13049 return r;
13050 }
13051 else {
13052 do {
13053 if (_PyAccu_Accumulate(acc, obj))
13054 return -1;
13055 } while (--count);
13056 return 0;
13057 }
13058}
13059
Alexander Belopolsky40018472011-02-26 01:02:56 +000013060PyObject *
13061PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013063 void *fmt;
13064 int fmtkind;
13065 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013066 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013067 int r;
13068 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013070 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013071 PyObject *temp = NULL;
13072 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013073 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013074 _PyAccu acc;
13075 static PyObject *plus, *minus, *blank, *zero, *percent;
13076
13077 if (!plus && !(plus = get_latin1_char('+')))
13078 return NULL;
13079 if (!minus && !(minus = get_latin1_char('-')))
13080 return NULL;
13081 if (!blank && !(blank = get_latin1_char(' ')))
13082 return NULL;
13083 if (!zero && !(zero = get_latin1_char('0')))
13084 return NULL;
13085 if (!percent && !(percent = get_latin1_char('%')))
13086 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013087
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013089 PyErr_BadInternalCall();
13090 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013092 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013093 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013094 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013095 if (_PyAccu_Init(&acc))
13096 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013097 fmt = PyUnicode_DATA(uformat);
13098 fmtkind = PyUnicode_KIND(uformat);
13099 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13100 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013103 arglen = PyTuple_Size(args);
13104 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105 }
13106 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 arglen = -1;
13108 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013110 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013111 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013112 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113
13114 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013115 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013116 PyObject *nonfmt;
13117 Py_ssize_t nonfmtpos;
13118 nonfmtpos = fmtpos++;
13119 while (fmtcnt >= 0 &&
13120 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13121 fmtpos++;
13122 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013123 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013124 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013125 if (nonfmt == NULL)
13126 goto onError;
13127 r = _PyAccu_Accumulate(&acc, nonfmt);
13128 Py_DECREF(nonfmt);
13129 if (r)
13130 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013131 }
13132 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013133 /* Got a format specifier */
13134 int flags = 0;
13135 Py_ssize_t width = -1;
13136 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013137 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013138 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013139 int isnumok;
13140 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013141 void *pbuf = NULL;
13142 Py_ssize_t pindex, len;
13143 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 fmtpos++;
13146 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13147 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013148 Py_ssize_t keylen;
13149 PyObject *key;
13150 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013151
Benjamin Peterson29060642009-01-31 22:14:21 +000013152 if (dict == NULL) {
13153 PyErr_SetString(PyExc_TypeError,
13154 "format requires a mapping");
13155 goto onError;
13156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013158 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013160 /* Skip over balanced parentheses */
13161 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013162 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013166 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013168 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 if (fmtcnt < 0 || pcount > 0) {
13170 PyErr_SetString(PyExc_ValueError,
13171 "incomplete format key");
13172 goto onError;
13173 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013174 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013175 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 if (key == NULL)
13177 goto onError;
13178 if (args_owned) {
13179 Py_DECREF(args);
13180 args_owned = 0;
13181 }
13182 args = PyObject_GetItem(dict, key);
13183 Py_DECREF(key);
13184 if (args == NULL) {
13185 goto onError;
13186 }
13187 args_owned = 1;
13188 arglen = -1;
13189 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013190 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013191 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013192 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013193 case '-': flags |= F_LJUST; continue;
13194 case '+': flags |= F_SIGN; continue;
13195 case ' ': flags |= F_BLANK; continue;
13196 case '#': flags |= F_ALT; continue;
13197 case '0': flags |= F_ZERO; continue;
13198 }
13199 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013200 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013201 if (c == '*') {
13202 v = getnextarg(args, arglen, &argidx);
13203 if (v == NULL)
13204 goto onError;
13205 if (!PyLong_Check(v)) {
13206 PyErr_SetString(PyExc_TypeError,
13207 "* wants int");
13208 goto onError;
13209 }
13210 width = PyLong_AsLong(v);
13211 if (width == -1 && PyErr_Occurred())
13212 goto onError;
13213 if (width < 0) {
13214 flags |= F_LJUST;
13215 width = -width;
13216 }
13217 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 }
13220 else if (c >= '0' && c <= '9') {
13221 width = c - '0';
13222 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013223 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013224 if (c < '0' || c > '9')
13225 break;
13226 if ((width*10) / 10 != width) {
13227 PyErr_SetString(PyExc_ValueError,
13228 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013229 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 }
13231 width = width*10 + (c - '0');
13232 }
13233 }
13234 if (c == '.') {
13235 prec = 0;
13236 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013237 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013238 if (c == '*') {
13239 v = getnextarg(args, arglen, &argidx);
13240 if (v == NULL)
13241 goto onError;
13242 if (!PyLong_Check(v)) {
13243 PyErr_SetString(PyExc_TypeError,
13244 "* wants int");
13245 goto onError;
13246 }
13247 prec = PyLong_AsLong(v);
13248 if (prec == -1 && PyErr_Occurred())
13249 goto onError;
13250 if (prec < 0)
13251 prec = 0;
13252 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013253 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 }
13255 else if (c >= '0' && c <= '9') {
13256 prec = c - '0';
13257 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013258 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013259 if (c < '0' || c > '9')
13260 break;
13261 if ((prec*10) / 10 != prec) {
13262 PyErr_SetString(PyExc_ValueError,
13263 "prec too big");
13264 goto onError;
13265 }
13266 prec = prec*10 + (c - '0');
13267 }
13268 }
13269 } /* prec */
13270 if (fmtcnt >= 0) {
13271 if (c == 'h' || c == 'l' || c == 'L') {
13272 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 }
13275 }
13276 if (fmtcnt < 0) {
13277 PyErr_SetString(PyExc_ValueError,
13278 "incomplete format");
13279 goto onError;
13280 }
13281 if (c != '%') {
13282 v = getnextarg(args, arglen, &argidx);
13283 if (v == NULL)
13284 goto onError;
13285 }
13286 sign = 0;
13287 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013288 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 switch (c) {
13290
13291 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013292 _PyAccu_Accumulate(&acc, percent);
13293 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013294
13295 case 's':
13296 case 'r':
13297 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013298 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013299 temp = v;
13300 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013301 }
13302 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013303 if (c == 's')
13304 temp = PyObject_Str(v);
13305 else if (c == 'r')
13306 temp = PyObject_Repr(v);
13307 else
13308 temp = PyObject_ASCII(v);
13309 if (temp == NULL)
13310 goto onError;
13311 if (PyUnicode_Check(temp))
13312 /* nothing to do */;
13313 else {
13314 Py_DECREF(temp);
13315 PyErr_SetString(PyExc_TypeError,
13316 "%s argument has non-string str()");
13317 goto onError;
13318 }
13319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013320 if (PyUnicode_READY(temp) == -1) {
13321 Py_CLEAR(temp);
13322 goto onError;
13323 }
13324 pbuf = PyUnicode_DATA(temp);
13325 kind = PyUnicode_KIND(temp);
13326 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013327 if (prec >= 0 && len > prec)
13328 len = prec;
13329 break;
13330
13331 case 'i':
13332 case 'd':
13333 case 'u':
13334 case 'o':
13335 case 'x':
13336 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013337 isnumok = 0;
13338 if (PyNumber_Check(v)) {
13339 PyObject *iobj=NULL;
13340
13341 if (PyLong_Check(v)) {
13342 iobj = v;
13343 Py_INCREF(iobj);
13344 }
13345 else {
13346 iobj = PyNumber_Long(v);
13347 }
13348 if (iobj!=NULL) {
13349 if (PyLong_Check(iobj)) {
13350 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013351 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 Py_DECREF(iobj);
13353 if (!temp)
13354 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013355 if (PyUnicode_READY(temp) == -1) {
13356 Py_CLEAR(temp);
13357 goto onError;
13358 }
13359 pbuf = PyUnicode_DATA(temp);
13360 kind = PyUnicode_KIND(temp);
13361 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 sign = 1;
13363 }
13364 else {
13365 Py_DECREF(iobj);
13366 }
13367 }
13368 }
13369 if (!isnumok) {
13370 PyErr_Format(PyExc_TypeError,
13371 "%%%c format: a number is required, "
13372 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13373 goto onError;
13374 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013375 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013377 fillobj = zero;
13378 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013379 break;
13380
13381 case 'e':
13382 case 'E':
13383 case 'f':
13384 case 'F':
13385 case 'g':
13386 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013387 temp = formatfloat(v, flags, prec, c);
13388 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013389 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013390 if (PyUnicode_READY(temp) == -1) {
13391 Py_CLEAR(temp);
13392 goto onError;
13393 }
13394 pbuf = PyUnicode_DATA(temp);
13395 kind = PyUnicode_KIND(temp);
13396 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013397 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013400 fillobj = zero;
13401 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 break;
13403
13404 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013405 {
13406 Py_UCS4 ch = formatchar(v);
13407 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013409 temp = _PyUnicode_FromUCS4(&ch, 1);
13410 if (temp == NULL)
13411 goto onError;
13412 pbuf = PyUnicode_DATA(temp);
13413 kind = PyUnicode_KIND(temp);
13414 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013416 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013417
13418 default:
13419 PyErr_Format(PyExc_ValueError,
13420 "unsupported format character '%c' (0x%x) "
13421 "at index %zd",
13422 (31<=c && c<=126) ? (char)c : '?',
13423 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013424 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 goto onError;
13426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013427 /* pbuf is initialized here. */
13428 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013429 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013430 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13431 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013433 pindex++;
13434 }
13435 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13436 signobj = plus;
13437 len--;
13438 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013439 }
13440 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013441 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013443 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013444 else
13445 sign = 0;
13446 }
13447 if (width < len)
13448 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013449 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013450 if (fill != ' ') {
13451 assert(signobj != NULL);
13452 if (_PyAccu_Accumulate(&acc, signobj))
13453 goto onError;
13454 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013455 if (width > len)
13456 width--;
13457 }
13458 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013459 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013460 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013461 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013462 second = get_latin1_char(
13463 PyUnicode_READ(kind, pbuf, pindex + 1));
13464 pindex += 2;
13465 if (second == NULL ||
13466 _PyAccu_Accumulate(&acc, zero) ||
13467 _PyAccu_Accumulate(&acc, second))
13468 goto onError;
13469 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013471 width -= 2;
13472 if (width < 0)
13473 width = 0;
13474 len -= 2;
13475 }
13476 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013477 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013478 if (repeat_accumulate(&acc, fillobj, width - len))
13479 goto onError;
13480 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 }
13482 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013483 if (sign) {
13484 assert(signobj != NULL);
13485 if (_PyAccu_Accumulate(&acc, signobj))
13486 goto onError;
13487 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013488 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013489 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13490 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013491 second = get_latin1_char(
13492 PyUnicode_READ(kind, pbuf, pindex + 1));
13493 pindex += 2;
13494 if (second == NULL ||
13495 _PyAccu_Accumulate(&acc, zero) ||
13496 _PyAccu_Accumulate(&acc, second))
13497 goto onError;
13498 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013499 }
13500 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013501 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013502 if (temp != NULL) {
13503 assert(pbuf == PyUnicode_DATA(temp));
13504 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013505 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013506 else {
13507 const char *p = (const char *) pbuf;
13508 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013509 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013510 v = PyUnicode_FromKindAndData(kind, p, len);
13511 }
13512 if (v == NULL)
13513 goto onError;
13514 r = _PyAccu_Accumulate(&acc, v);
13515 Py_DECREF(v);
13516 if (r)
13517 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013518 if (width > len && repeat_accumulate(&acc, blank, width - len))
13519 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 if (dict && (argidx < arglen) && c != '%') {
13521 PyErr_SetString(PyExc_TypeError,
13522 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 goto onError;
13524 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013525 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013527 } /* until end */
13528 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013529 PyErr_SetString(PyExc_TypeError,
13530 "not all arguments converted during string formatting");
13531 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013532 }
13533
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013534 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013535 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013536 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013537 }
13538 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013539 Py_XDECREF(temp);
13540 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013541 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013542
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013544 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013545 Py_XDECREF(temp);
13546 Py_XDECREF(second);
13547 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013548 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013549 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013550 }
13551 return NULL;
13552}
13553
Jeremy Hylton938ace62002-07-17 16:30:39 +000013554static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013555unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13556
Tim Peters6d6c1a32001-08-02 04:15:00 +000013557static PyObject *
13558unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13559{
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013561 static char *kwlist[] = {"object", "encoding", "errors", 0};
13562 char *encoding = NULL;
13563 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013564
Benjamin Peterson14339b62009-01-31 16:36:08 +000013565 if (type != &PyUnicode_Type)
13566 return unicode_subtype_new(type, args, kwds);
13567 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013568 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013569 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013570 if (x == NULL) {
13571 Py_INCREF(unicode_empty);
13572 return unicode_empty;
13573 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013574 if (encoding == NULL && errors == NULL)
13575 return PyObject_Str(x);
13576 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013577 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013578}
13579
Guido van Rossume023fe02001-08-30 03:12:59 +000013580static PyObject *
13581unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13582{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013583 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013584 Py_ssize_t length, char_size;
13585 int share_wstr, share_utf8;
13586 unsigned int kind;
13587 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013588
Benjamin Peterson14339b62009-01-31 16:36:08 +000013589 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013590
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013591 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013592 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013593 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013594 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013595 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013596 return NULL;
13597
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013598 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013599 if (self == NULL) {
13600 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013601 return NULL;
13602 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013603 kind = PyUnicode_KIND(unicode);
13604 length = PyUnicode_GET_LENGTH(unicode);
13605
13606 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013607#ifdef Py_DEBUG
13608 _PyUnicode_HASH(self) = -1;
13609#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013610 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013611#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013612 _PyUnicode_STATE(self).interned = 0;
13613 _PyUnicode_STATE(self).kind = kind;
13614 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013615 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013616 _PyUnicode_STATE(self).ready = 1;
13617 _PyUnicode_WSTR(self) = NULL;
13618 _PyUnicode_UTF8_LENGTH(self) = 0;
13619 _PyUnicode_UTF8(self) = NULL;
13620 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013621 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013622
13623 share_utf8 = 0;
13624 share_wstr = 0;
13625 if (kind == PyUnicode_1BYTE_KIND) {
13626 char_size = 1;
13627 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13628 share_utf8 = 1;
13629 }
13630 else if (kind == PyUnicode_2BYTE_KIND) {
13631 char_size = 2;
13632 if (sizeof(wchar_t) == 2)
13633 share_wstr = 1;
13634 }
13635 else {
13636 assert(kind == PyUnicode_4BYTE_KIND);
13637 char_size = 4;
13638 if (sizeof(wchar_t) == 4)
13639 share_wstr = 1;
13640 }
13641
13642 /* Ensure we won't overflow the length. */
13643 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13644 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013645 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013646 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013647 data = PyObject_MALLOC((length + 1) * char_size);
13648 if (data == NULL) {
13649 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013650 goto onError;
13651 }
13652
Victor Stinnerc3c74152011-10-02 20:39:55 +020013653 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013654 if (share_utf8) {
13655 _PyUnicode_UTF8_LENGTH(self) = length;
13656 _PyUnicode_UTF8(self) = data;
13657 }
13658 if (share_wstr) {
13659 _PyUnicode_WSTR_LENGTH(self) = length;
13660 _PyUnicode_WSTR(self) = (wchar_t *)data;
13661 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013662
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013663 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013664 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013665 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013666#ifdef Py_DEBUG
13667 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13668#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013669 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013670 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013671
13672onError:
13673 Py_DECREF(unicode);
13674 Py_DECREF(self);
13675 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013676}
13677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013678PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013679 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013680\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013681Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013682encoding defaults to the current default string encoding.\n\
13683errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013684
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013685static PyObject *unicode_iter(PyObject *seq);
13686
Guido van Rossumd57fd912000-03-10 22:53:23 +000013687PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013688 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013689 "str", /* tp_name */
13690 sizeof(PyUnicodeObject), /* tp_size */
13691 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013692 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013693 (destructor)unicode_dealloc, /* tp_dealloc */
13694 0, /* tp_print */
13695 0, /* tp_getattr */
13696 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013697 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 unicode_repr, /* tp_repr */
13699 &unicode_as_number, /* tp_as_number */
13700 &unicode_as_sequence, /* tp_as_sequence */
13701 &unicode_as_mapping, /* tp_as_mapping */
13702 (hashfunc) unicode_hash, /* tp_hash*/
13703 0, /* tp_call*/
13704 (reprfunc) unicode_str, /* tp_str */
13705 PyObject_GenericGetAttr, /* tp_getattro */
13706 0, /* tp_setattro */
13707 0, /* tp_as_buffer */
13708 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013709 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 unicode_doc, /* tp_doc */
13711 0, /* tp_traverse */
13712 0, /* tp_clear */
13713 PyUnicode_RichCompare, /* tp_richcompare */
13714 0, /* tp_weaklistoffset */
13715 unicode_iter, /* tp_iter */
13716 0, /* tp_iternext */
13717 unicode_methods, /* tp_methods */
13718 0, /* tp_members */
13719 0, /* tp_getset */
13720 &PyBaseObject_Type, /* tp_base */
13721 0, /* tp_dict */
13722 0, /* tp_descr_get */
13723 0, /* tp_descr_set */
13724 0, /* tp_dictoffset */
13725 0, /* tp_init */
13726 0, /* tp_alloc */
13727 unicode_new, /* tp_new */
13728 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013729};
13730
13731/* Initialize the Unicode implementation */
13732
Victor Stinner3a50e702011-10-18 21:21:00 +020013733int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013734{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013735 int i;
13736
Thomas Wouters477c8d52006-05-27 19:21:47 +000013737 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013738 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013739 0x000A, /* LINE FEED */
13740 0x000D, /* CARRIAGE RETURN */
13741 0x001C, /* FILE SEPARATOR */
13742 0x001D, /* GROUP SEPARATOR */
13743 0x001E, /* RECORD SEPARATOR */
13744 0x0085, /* NEXT LINE */
13745 0x2028, /* LINE SEPARATOR */
13746 0x2029, /* PARAGRAPH SEPARATOR */
13747 };
13748
Fred Drakee4315f52000-05-09 19:53:39 +000013749 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013750 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013751 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013752 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013753 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013754
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013755 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013756 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013757 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013759
13760 /* initialize the linebreak bloom filter */
13761 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013762 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013763 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013764
13765 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013766
13767#ifdef HAVE_MBCS
13768 winver.dwOSVersionInfoSize = sizeof(winver);
13769 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13770 PyErr_SetFromWindowsErr(0);
13771 return -1;
13772 }
13773#endif
13774 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013775}
13776
13777/* Finalize the Unicode implementation */
13778
Christian Heimesa156e092008-02-16 07:38:31 +000013779int
13780PyUnicode_ClearFreeList(void)
13781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013782 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013783}
13784
Guido van Rossumd57fd912000-03-10 22:53:23 +000013785void
Thomas Wouters78890102000-07-22 19:25:51 +000013786_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013787{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013788 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013789
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013790 Py_XDECREF(unicode_empty);
13791 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013792
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013793 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013794 if (unicode_latin1[i]) {
13795 Py_DECREF(unicode_latin1[i]);
13796 unicode_latin1[i] = NULL;
13797 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013798 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013799 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013800 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013801}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013802
Walter Dörwald16807132007-05-25 13:52:07 +000013803void
13804PyUnicode_InternInPlace(PyObject **p)
13805{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013806 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013807 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013808#ifdef Py_DEBUG
13809 assert(s != NULL);
13810 assert(_PyUnicode_CHECK(s));
13811#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013812 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013813 return;
13814#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013815 /* If it's a subclass, we don't really know what putting
13816 it in the interned dict might do. */
13817 if (!PyUnicode_CheckExact(s))
13818 return;
13819 if (PyUnicode_CHECK_INTERNED(s))
13820 return;
13821 if (interned == NULL) {
13822 interned = PyDict_New();
13823 if (interned == NULL) {
13824 PyErr_Clear(); /* Don't leave an exception */
13825 return;
13826 }
13827 }
13828 /* It might be that the GetItem call fails even
13829 though the key is present in the dictionary,
13830 namely when this happens during a stack overflow. */
13831 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013832 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013833 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013834
Benjamin Peterson29060642009-01-31 22:14:21 +000013835 if (t) {
13836 Py_INCREF(t);
13837 Py_DECREF(*p);
13838 *p = t;
13839 return;
13840 }
Walter Dörwald16807132007-05-25 13:52:07 +000013841
Benjamin Peterson14339b62009-01-31 16:36:08 +000013842 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013843 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013844 PyErr_Clear();
13845 PyThreadState_GET()->recursion_critical = 0;
13846 return;
13847 }
13848 PyThreadState_GET()->recursion_critical = 0;
13849 /* The two references in interned are not counted by refcnt.
13850 The deallocator will take care of this */
13851 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013852 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013853}
13854
13855void
13856PyUnicode_InternImmortal(PyObject **p)
13857{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013858 PyUnicode_InternInPlace(p);
13859 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013860 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013861 Py_INCREF(*p);
13862 }
Walter Dörwald16807132007-05-25 13:52:07 +000013863}
13864
13865PyObject *
13866PyUnicode_InternFromString(const char *cp)
13867{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013868 PyObject *s = PyUnicode_FromString(cp);
13869 if (s == NULL)
13870 return NULL;
13871 PyUnicode_InternInPlace(&s);
13872 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013873}
13874
Alexander Belopolsky40018472011-02-26 01:02:56 +000013875void
13876_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013877{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013878 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013879 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013880 Py_ssize_t i, n;
13881 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013882
Benjamin Peterson14339b62009-01-31 16:36:08 +000013883 if (interned == NULL || !PyDict_Check(interned))
13884 return;
13885 keys = PyDict_Keys(interned);
13886 if (keys == NULL || !PyList_Check(keys)) {
13887 PyErr_Clear();
13888 return;
13889 }
Walter Dörwald16807132007-05-25 13:52:07 +000013890
Benjamin Peterson14339b62009-01-31 16:36:08 +000013891 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13892 detector, interned unicode strings are not forcibly deallocated;
13893 rather, we give them their stolen references back, and then clear
13894 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013895
Benjamin Peterson14339b62009-01-31 16:36:08 +000013896 n = PyList_GET_SIZE(keys);
13897 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013899 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013900 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013901 if (PyUnicode_READY(s) == -1) {
13902 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013905 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013906 case SSTATE_NOT_INTERNED:
13907 /* XXX Shouldn't happen */
13908 break;
13909 case SSTATE_INTERNED_IMMORTAL:
13910 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013911 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013912 break;
13913 case SSTATE_INTERNED_MORTAL:
13914 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013915 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013916 break;
13917 default:
13918 Py_FatalError("Inconsistent interned string state.");
13919 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013920 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013921 }
13922 fprintf(stderr, "total size of all interned strings: "
13923 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13924 "mortal/immortal\n", mortal_size, immortal_size);
13925 Py_DECREF(keys);
13926 PyDict_Clear(interned);
13927 Py_DECREF(interned);
13928 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013929}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013930
13931
13932/********************* Unicode Iterator **************************/
13933
13934typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013935 PyObject_HEAD
13936 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013937 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013938} unicodeiterobject;
13939
13940static void
13941unicodeiter_dealloc(unicodeiterobject *it)
13942{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013943 _PyObject_GC_UNTRACK(it);
13944 Py_XDECREF(it->it_seq);
13945 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013946}
13947
13948static int
13949unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13950{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013951 Py_VISIT(it->it_seq);
13952 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013953}
13954
13955static PyObject *
13956unicodeiter_next(unicodeiterobject *it)
13957{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013958 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013959
Benjamin Peterson14339b62009-01-31 16:36:08 +000013960 assert(it != NULL);
13961 seq = it->it_seq;
13962 if (seq == NULL)
13963 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013964 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013966 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13967 int kind = PyUnicode_KIND(seq);
13968 void *data = PyUnicode_DATA(seq);
13969 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13970 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013971 if (item != NULL)
13972 ++it->it_index;
13973 return item;
13974 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013975
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 Py_DECREF(seq);
13977 it->it_seq = NULL;
13978 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013979}
13980
13981static PyObject *
13982unicodeiter_len(unicodeiterobject *it)
13983{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013984 Py_ssize_t len = 0;
13985 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013986 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013987 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013988}
13989
13990PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13991
13992static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013993 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013994 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013995 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013996};
13997
13998PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013999 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14000 "str_iterator", /* tp_name */
14001 sizeof(unicodeiterobject), /* tp_basicsize */
14002 0, /* tp_itemsize */
14003 /* methods */
14004 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14005 0, /* tp_print */
14006 0, /* tp_getattr */
14007 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014008 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014009 0, /* tp_repr */
14010 0, /* tp_as_number */
14011 0, /* tp_as_sequence */
14012 0, /* tp_as_mapping */
14013 0, /* tp_hash */
14014 0, /* tp_call */
14015 0, /* tp_str */
14016 PyObject_GenericGetAttr, /* tp_getattro */
14017 0, /* tp_setattro */
14018 0, /* tp_as_buffer */
14019 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14020 0, /* tp_doc */
14021 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14022 0, /* tp_clear */
14023 0, /* tp_richcompare */
14024 0, /* tp_weaklistoffset */
14025 PyObject_SelfIter, /* tp_iter */
14026 (iternextfunc)unicodeiter_next, /* tp_iternext */
14027 unicodeiter_methods, /* tp_methods */
14028 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014029};
14030
14031static PyObject *
14032unicode_iter(PyObject *seq)
14033{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014035
Benjamin Peterson14339b62009-01-31 16:36:08 +000014036 if (!PyUnicode_Check(seq)) {
14037 PyErr_BadInternalCall();
14038 return NULL;
14039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014040 if (PyUnicode_READY(seq) == -1)
14041 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14043 if (it == NULL)
14044 return NULL;
14045 it->it_index = 0;
14046 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014047 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 _PyObject_GC_TRACK(it);
14049 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014050}
14051
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014052
14053size_t
14054Py_UNICODE_strlen(const Py_UNICODE *u)
14055{
14056 int res = 0;
14057 while(*u++)
14058 res++;
14059 return res;
14060}
14061
14062Py_UNICODE*
14063Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14064{
14065 Py_UNICODE *u = s1;
14066 while ((*u++ = *s2++));
14067 return s1;
14068}
14069
14070Py_UNICODE*
14071Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14072{
14073 Py_UNICODE *u = s1;
14074 while ((*u++ = *s2++))
14075 if (n-- == 0)
14076 break;
14077 return s1;
14078}
14079
14080Py_UNICODE*
14081Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14082{
14083 Py_UNICODE *u1 = s1;
14084 u1 += Py_UNICODE_strlen(u1);
14085 Py_UNICODE_strcpy(u1, s2);
14086 return s1;
14087}
14088
14089int
14090Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14091{
14092 while (*s1 && *s2 && *s1 == *s2)
14093 s1++, s2++;
14094 if (*s1 && *s2)
14095 return (*s1 < *s2) ? -1 : +1;
14096 if (*s1)
14097 return 1;
14098 if (*s2)
14099 return -1;
14100 return 0;
14101}
14102
14103int
14104Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14105{
14106 register Py_UNICODE u1, u2;
14107 for (; n != 0; n--) {
14108 u1 = *s1;
14109 u2 = *s2;
14110 if (u1 != u2)
14111 return (u1 < u2) ? -1 : +1;
14112 if (u1 == '\0')
14113 return 0;
14114 s1++;
14115 s2++;
14116 }
14117 return 0;
14118}
14119
14120Py_UNICODE*
14121Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14122{
14123 const Py_UNICODE *p;
14124 for (p = s; *p; p++)
14125 if (*p == c)
14126 return (Py_UNICODE*)p;
14127 return NULL;
14128}
14129
14130Py_UNICODE*
14131Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14132{
14133 const Py_UNICODE *p;
14134 p = s + Py_UNICODE_strlen(s);
14135 while (p != s) {
14136 p--;
14137 if (*p == c)
14138 return (Py_UNICODE*)p;
14139 }
14140 return NULL;
14141}
Victor Stinner331ea922010-08-10 16:37:20 +000014142
Victor Stinner71133ff2010-09-01 23:43:53 +000014143Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014144PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014145{
Victor Stinner577db2c2011-10-11 22:12:48 +020014146 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014147 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014149 if (!PyUnicode_Check(unicode)) {
14150 PyErr_BadArgument();
14151 return NULL;
14152 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014153 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014154 if (u == NULL)
14155 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014156 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014157 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014158 PyErr_NoMemory();
14159 return NULL;
14160 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014161 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014162 size *= sizeof(Py_UNICODE);
14163 copy = PyMem_Malloc(size);
14164 if (copy == NULL) {
14165 PyErr_NoMemory();
14166 return NULL;
14167 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014168 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014169 return copy;
14170}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014171
Georg Brandl66c221e2010-10-14 07:04:07 +000014172/* A _string module, to export formatter_parser and formatter_field_name_split
14173 to the string.Formatter class implemented in Python. */
14174
14175static PyMethodDef _string_methods[] = {
14176 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14177 METH_O, PyDoc_STR("split the argument as a field name")},
14178 {"formatter_parser", (PyCFunction) formatter_parser,
14179 METH_O, PyDoc_STR("parse the argument as a format string")},
14180 {NULL, NULL}
14181};
14182
14183static struct PyModuleDef _string_module = {
14184 PyModuleDef_HEAD_INIT,
14185 "_string",
14186 PyDoc_STR("string helper module"),
14187 0,
14188 _string_methods,
14189 NULL,
14190 NULL,
14191 NULL,
14192 NULL
14193};
14194
14195PyMODINIT_FUNC
14196PyInit__string(void)
14197{
14198 return PyModule_Create(&_string_module);
14199}
14200
14201
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014202#ifdef __cplusplus
14203}
14204#endif