blob: a7ea9c8597a631f07302d68a008c7ab2168738e7 [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"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000050/* --- Globals ------------------------------------------------------------
51
Serhiy Storchaka05997252013-01-26 12:14:02 +020052NOTE: In the interpreter's initialization phase, some globals are currently
53 initialized dynamically as needed. In the process Unicode objects may
54 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055
56*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000057
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058
59#ifdef __cplusplus
60extern "C" {
61#endif
62
Victor Stinner8faf8212011-12-08 22:14:11 +010063/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
64#define MAX_UNICODE 0x10ffff
65
Victor Stinner910337b2011-10-03 03:20:16 +020066#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020067# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020068#else
69# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
70#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020071
Victor Stinnere90fe6a2011-10-01 16:48:13 +020072#define _PyUnicode_UTF8(op) \
73 (((PyCompactUnicodeObject*)(op))->utf8)
74#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020075 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020076 assert(PyUnicode_IS_READY(op)), \
77 PyUnicode_IS_COMPACT_ASCII(op) ? \
78 ((char*)((PyASCIIObject*)(op) + 1)) : \
79 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020080#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 (((PyCompactUnicodeObject*)(op))->utf8_length)
82#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020083 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020084 assert(PyUnicode_IS_READY(op)), \
85 PyUnicode_IS_COMPACT_ASCII(op) ? \
86 ((PyASCIIObject*)(op))->length : \
87 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020088#define _PyUnicode_WSTR(op) \
89 (((PyASCIIObject*)(op))->wstr)
90#define _PyUnicode_WSTR_LENGTH(op) \
91 (((PyCompactUnicodeObject*)(op))->wstr_length)
92#define _PyUnicode_LENGTH(op) \
93 (((PyASCIIObject *)(op))->length)
94#define _PyUnicode_STATE(op) \
95 (((PyASCIIObject *)(op))->state)
96#define _PyUnicode_HASH(op) \
97 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +020098#define _PyUnicode_KIND(op) \
99 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200100 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200101#define _PyUnicode_GET_LENGTH(op) \
102 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200103 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200104#define _PyUnicode_DATA_ANY(op) \
105 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106
Victor Stinner910337b2011-10-03 03:20:16 +0200107#undef PyUnicode_READY
108#define PyUnicode_READY(op) \
109 (assert(_PyUnicode_CHECK(op)), \
110 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200111 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100112 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200113
Victor Stinnerc379ead2011-10-03 12:52:27 +0200114#define _PyUnicode_SHARE_UTF8(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
117 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
118#define _PyUnicode_SHARE_WSTR(op) \
119 (assert(_PyUnicode_CHECK(op)), \
120 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
121
Victor Stinner829c0ad2011-10-03 01:08:02 +0200122/* true if the Unicode object has an allocated UTF-8 memory block
123 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200124#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200125 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200126 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
128
Victor Stinner03490912011-10-03 23:45:12 +0200129/* true if the Unicode object has an allocated wstr memory block
130 (not shared with other data) */
131#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200132 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200133 (!PyUnicode_IS_READY(op) || \
134 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
135
Victor Stinner910337b2011-10-03 03:20:16 +0200136/* Generic helper macro to convert characters of different types.
137 from_type and to_type have to be valid type names, begin and end
138 are pointers to the source characters which should be of type
139 "from_type *". to is a pointer of type "to_type *" and points to the
140 buffer where the result characters are written to. */
141#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
142 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200143 to_type *_to = (to_type *) to; \
144 const from_type *_iter = (begin); \
145 const from_type *_end = (end); \
146 Py_ssize_t n = (_end) - (_iter); \
147 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200148 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200149 while (_iter < (_unrolled_end)) { \
150 _to[0] = (to_type) _iter[0]; \
151 _to[1] = (to_type) _iter[1]; \
152 _to[2] = (to_type) _iter[2]; \
153 _to[3] = (to_type) _iter[3]; \
154 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200155 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200156 while (_iter < (_end)) \
157 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200158 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200159
Walter Dörwald16807132007-05-25 13:52:07 +0000160/* This dictionary holds all interned unicode strings. Note that references
161 to strings in this dictionary are *not* counted in the string's ob_refcnt.
162 When the interned string reaches a refcnt of 0 the string deallocation
163 function will delete the reference from this dictionary.
164
165 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000166 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000167*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200168static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000169
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000170/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200171static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200172
Serhiy Storchaka678db842013-01-26 12:16:36 +0200173#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200174 do { \
175 if (unicode_empty != NULL) \
176 Py_INCREF(unicode_empty); \
177 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178 unicode_empty = PyUnicode_New(0, 0); \
179 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200180 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200181 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
182 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200183 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200184 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000185
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186#define _Py_RETURN_UNICODE_EMPTY() \
187 do { \
188 _Py_INCREF_UNICODE_EMPTY(); \
189 return unicode_empty; \
190 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000191
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200192/* Forward declaration */
193Py_LOCAL_INLINE(int)
194_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
195
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200196/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200197static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200198
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199/* Single character Unicode strings in the Latin-1 range are being
200 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200201static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000202
Christian Heimes190d79e2008-01-30 11:58:22 +0000203/* Fast detection of the most frequent whitespace characters */
204const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000206/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000208/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000209/* case 0x000C: * FORM FEED */
210/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 1, 1, 1, 1, 1, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000213/* case 0x001C: * FILE SEPARATOR */
214/* case 0x001D: * GROUP SEPARATOR */
215/* case 0x001E: * RECORD SEPARATOR */
216/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000217 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 1, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000223
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
228 0, 0, 0, 0, 0, 0, 0, 0,
229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000232};
233
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200234/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200235static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200236static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100237static int unicode_modifiable(PyObject *unicode);
238
Victor Stinnerfe226c02011-10-03 03:52:20 +0200239
Alexander Belopolsky40018472011-02-26 01:02:56 +0000240static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100241_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200242static PyObject *
243_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
244static PyObject *
245_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
246
247static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000248unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000249 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100250 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000251 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
252
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253static void
254raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300255 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100256 PyObject *unicode,
257 Py_ssize_t startpos, Py_ssize_t endpos,
258 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000259
Christian Heimes190d79e2008-01-30 11:58:22 +0000260/* Same for linebreaks */
261static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000262 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000263/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000264/* 0x000B, * LINE TABULATION */
265/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000266/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000267 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* 0x001C, * FILE SEPARATOR */
270/* 0x001D, * GROUP SEPARATOR */
271/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000272 0, 0, 0, 0, 1, 1, 1, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000277
Benjamin Peterson14339b62009-01-31 16:36:08 +0000278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000286};
287
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300288/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
289 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000290Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000291PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000292{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000293#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000294 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000296 /* This is actually an illegal character, so it should
297 not be passed to unichr. */
298 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000299#endif
300}
301
Victor Stinner910337b2011-10-03 03:20:16 +0200302#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200303int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100304_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200305{
306 PyASCIIObject *ascii;
307 unsigned int kind;
308
309 assert(PyUnicode_Check(op));
310
311 ascii = (PyASCIIObject *)op;
312 kind = ascii->state.kind;
313
Victor Stinnera3b334d2011-10-03 13:53:37 +0200314 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200315 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(ascii->state.ready == 1);
317 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200318 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200319 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200320 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200321
Victor Stinnera41463c2011-10-04 01:05:08 +0200322 if (ascii->state.compact == 1) {
323 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200324 assert(kind == PyUnicode_1BYTE_KIND
325 || kind == PyUnicode_2BYTE_KIND
326 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200328 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100330 }
331 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
333
334 data = unicode->data.any;
335 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100336 assert(ascii->length == 0);
337 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200338 assert(ascii->state.compact == 0);
339 assert(ascii->state.ascii == 0);
340 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200342 assert(ascii->wstr != NULL);
343 assert(data == NULL);
344 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200345 }
346 else {
347 assert(kind == PyUnicode_1BYTE_KIND
348 || kind == PyUnicode_2BYTE_KIND
349 || kind == PyUnicode_4BYTE_KIND);
350 assert(ascii->state.compact == 0);
351 assert(ascii->state.ready == 1);
352 assert(data != NULL);
353 if (ascii->state.ascii) {
354 assert (compact->utf8 == data);
355 assert (compact->utf8_length == ascii->length);
356 }
357 else
358 assert (compact->utf8 != data);
359 }
360 }
361 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200362 if (
363#if SIZEOF_WCHAR_T == 2
364 kind == PyUnicode_2BYTE_KIND
365#else
366 kind == PyUnicode_4BYTE_KIND
367#endif
368 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200369 {
370 assert(ascii->wstr == data);
371 assert(compact->wstr_length == ascii->length);
372 } else
373 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200374 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200375
376 if (compact->utf8 == NULL)
377 assert(compact->utf8_length == 0);
378 if (ascii->wstr == NULL)
379 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200380 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200381 /* check that the best kind is used */
382 if (check_content && kind != PyUnicode_WCHAR_KIND)
383 {
384 Py_ssize_t i;
385 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200386 void *data;
387 Py_UCS4 ch;
388
389 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 for (i=0; i < ascii->length; i++)
391 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200392 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200393 if (ch > maxchar)
394 maxchar = ch;
395 }
396 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100397 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100399 assert(maxchar <= 255);
400 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 else
402 assert(maxchar < 128);
403 }
Victor Stinner77faf692011-11-20 18:56:05 +0100404 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200405 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100406 assert(maxchar <= 0xFFFF);
407 }
408 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200409 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100410 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200412 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200413 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400414 return 1;
415}
Victor Stinner910337b2011-10-03 03:20:16 +0200416#endif
417
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100418static PyObject*
419unicode_result_wchar(PyObject *unicode)
420{
421#ifndef Py_DEBUG
422 Py_ssize_t len;
423
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100424 len = _PyUnicode_WSTR_LENGTH(unicode);
425 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100426 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200427 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100428 }
429
430 if (len == 1) {
431 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100432 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
434 Py_DECREF(unicode);
435 return latin1_char;
436 }
437 }
438
439 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200440 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100441 return NULL;
442 }
443#else
Victor Stinneraa771272012-10-04 02:32:58 +0200444 assert(Py_REFCNT(unicode) == 1);
445
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 /* don't make the result ready in debug mode to ensure that the caller
447 makes the string ready before using it */
448 assert(_PyUnicode_CheckConsistency(unicode, 1));
449#endif
450 return unicode;
451}
452
453static PyObject*
454unicode_result_ready(PyObject *unicode)
455{
456 Py_ssize_t length;
457
458 length = PyUnicode_GET_LENGTH(unicode);
459 if (length == 0) {
460 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100461 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200462 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100463 }
464 return unicode_empty;
465 }
466
467 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200468 void *data = PyUnicode_DATA(unicode);
469 int kind = PyUnicode_KIND(unicode);
470 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100471 if (ch < 256) {
472 PyObject *latin1_char = unicode_latin1[ch];
473 if (latin1_char != NULL) {
474 if (unicode != latin1_char) {
475 Py_INCREF(latin1_char);
476 Py_DECREF(unicode);
477 }
478 return latin1_char;
479 }
480 else {
481 assert(_PyUnicode_CheckConsistency(unicode, 1));
482 Py_INCREF(unicode);
483 unicode_latin1[ch] = unicode;
484 return unicode;
485 }
486 }
487 }
488
489 assert(_PyUnicode_CheckConsistency(unicode, 1));
490 return unicode;
491}
492
493static PyObject*
494unicode_result(PyObject *unicode)
495{
496 assert(_PyUnicode_CHECK(unicode));
497 if (PyUnicode_IS_READY(unicode))
498 return unicode_result_ready(unicode);
499 else
500 return unicode_result_wchar(unicode);
501}
502
Victor Stinnerc4b49542011-12-11 22:44:26 +0100503static PyObject*
504unicode_result_unchanged(PyObject *unicode)
505{
506 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500507 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508 return NULL;
509 Py_INCREF(unicode);
510 return unicode;
511 }
512 else
513 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100514 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100515}
516
Victor Stinner3a50e702011-10-18 21:21:00 +0200517#ifdef HAVE_MBCS
518static OSVERSIONINFOEX winver;
519#endif
520
Thomas Wouters477c8d52006-05-27 19:21:47 +0000521/* --- Bloom Filters ----------------------------------------------------- */
522
523/* stuff to implement simple "bloom filters" for Unicode characters.
524 to keep things simple, we use a single bitmask, using the least 5
525 bits from each unicode characters as the bit index. */
526
527/* the linebreak mask is set up by Unicode_Init below */
528
Antoine Pitrouf068f942010-01-13 14:19:12 +0000529#if LONG_BIT >= 128
530#define BLOOM_WIDTH 128
531#elif LONG_BIT >= 64
532#define BLOOM_WIDTH 64
533#elif LONG_BIT >= 32
534#define BLOOM_WIDTH 32
535#else
536#error "LONG_BIT is smaller than 32"
537#endif
538
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539#define BLOOM_MASK unsigned long
540
Serhiy Storchaka05997252013-01-26 12:14:02 +0200541static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542
Antoine Pitrouf068f942010-01-13 14:19:12 +0000543#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544
Benjamin Peterson29060642009-01-31 22:14:21 +0000545#define BLOOM_LINEBREAK(ch) \
546 ((ch) < 128U ? ascii_linebreak[(ch)] : \
547 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
Alexander Belopolsky40018472011-02-26 01:02:56 +0000549Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551{
Victor Stinnera85af502013-04-09 21:53:54 +0200552#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
553 do { \
554 TYPE *data = (TYPE *)PTR; \
555 TYPE *end = data + LEN; \
556 Py_UCS4 ch; \
557 for (; data != end; data++) { \
558 ch = *data; \
559 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
560 } \
561 break; \
562 } while (0)
563
Thomas Wouters477c8d52006-05-27 19:21:47 +0000564 /* calculate simple bloom-style bitmask for a given unicode string */
565
Antoine Pitrouf068f942010-01-13 14:19:12 +0000566 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567
568 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200569 switch (kind) {
570 case PyUnicode_1BYTE_KIND:
571 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
572 break;
573 case PyUnicode_2BYTE_KIND:
574 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
575 break;
576 case PyUnicode_4BYTE_KIND:
577 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
578 break;
579 default:
580 assert(0);
581 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000582 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200583
584#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585}
586
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200587/* Compilation of templated routines */
588
589#include "stringlib/asciilib.h"
590#include "stringlib/fastsearch.h"
591#include "stringlib/partition.h"
592#include "stringlib/split.h"
593#include "stringlib/count.h"
594#include "stringlib/find.h"
595#include "stringlib/find_max_char.h"
596#include "stringlib/localeutil.h"
597#include "stringlib/undef.h"
598
599#include "stringlib/ucs1lib.h"
600#include "stringlib/fastsearch.h"
601#include "stringlib/partition.h"
602#include "stringlib/split.h"
603#include "stringlib/count.h"
604#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300605#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200606#include "stringlib/find_max_char.h"
607#include "stringlib/localeutil.h"
608#include "stringlib/undef.h"
609
610#include "stringlib/ucs2lib.h"
611#include "stringlib/fastsearch.h"
612#include "stringlib/partition.h"
613#include "stringlib/split.h"
614#include "stringlib/count.h"
615#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300616#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200617#include "stringlib/find_max_char.h"
618#include "stringlib/localeutil.h"
619#include "stringlib/undef.h"
620
621#include "stringlib/ucs4lib.h"
622#include "stringlib/fastsearch.h"
623#include "stringlib/partition.h"
624#include "stringlib/split.h"
625#include "stringlib/count.h"
626#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300627#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200628#include "stringlib/find_max_char.h"
629#include "stringlib/localeutil.h"
630#include "stringlib/undef.h"
631
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200632#include "stringlib/unicodedefs.h"
633#include "stringlib/fastsearch.h"
634#include "stringlib/count.h"
635#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100636#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637
Guido van Rossumd57fd912000-03-10 22:53:23 +0000638/* --- Unicode Object ----------------------------------------------------- */
639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200640static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200641fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200642
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200643Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
644 Py_ssize_t size, Py_UCS4 ch,
645 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200646{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200647 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
648
649 switch (kind) {
650 case PyUnicode_1BYTE_KIND:
651 {
652 Py_UCS1 ch1 = (Py_UCS1) ch;
653 if (ch1 == ch)
654 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
655 else
656 return -1;
657 }
658 case PyUnicode_2BYTE_KIND:
659 {
660 Py_UCS2 ch2 = (Py_UCS2) ch;
661 if (ch2 == ch)
662 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
663 else
664 return -1;
665 }
666 case PyUnicode_4BYTE_KIND:
667 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
668 default:
669 assert(0);
670 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672}
673
Victor Stinnerafffce42012-10-03 23:03:17 +0200674#ifdef Py_DEBUG
675/* Fill the data of an Unicode string with invalid characters to detect bugs
676 earlier.
677
678 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
679 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
680 invalid character in Unicode 6.0. */
681static void
682unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
683{
684 int kind = PyUnicode_KIND(unicode);
685 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
686 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
687 if (length <= old_length)
688 return;
689 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
690}
691#endif
692
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693static PyObject*
694resize_compact(PyObject *unicode, Py_ssize_t length)
695{
696 Py_ssize_t char_size;
697 Py_ssize_t struct_size;
698 Py_ssize_t new_size;
699 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100700 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200701#ifdef Py_DEBUG
702 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
703#endif
704
Victor Stinner79891572012-05-03 13:43:07 +0200705 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200706 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100707 assert(PyUnicode_IS_COMPACT(unicode));
708
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200709 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100710 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 struct_size = sizeof(PyASCIIObject);
712 else
713 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200714 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
717 PyErr_NoMemory();
718 return NULL;
719 }
720 new_size = (struct_size + (length + 1) * char_size);
721
Victor Stinner84def372011-12-11 20:04:56 +0100722 _Py_DEC_REFTOTAL;
723 _Py_ForgetReference(unicode);
724
725 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
726 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100727 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200728 PyErr_NoMemory();
729 return NULL;
730 }
Victor Stinner84def372011-12-11 20:04:56 +0100731 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100733
Victor Stinnerfe226c02011-10-03 03:52:20 +0200734 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200735 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100737 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200738 _PyUnicode_WSTR_LENGTH(unicode) = length;
739 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100740 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
741 PyObject_DEL(_PyUnicode_WSTR(unicode));
742 _PyUnicode_WSTR(unicode) = NULL;
743 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200744#ifdef Py_DEBUG
745 unicode_fill_invalid(unicode, old_length);
746#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200747 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
748 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200749 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200750 return unicode;
751}
752
Alexander Belopolsky40018472011-02-26 01:02:56 +0000753static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200754resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000755{
Victor Stinner95663112011-10-04 01:03:50 +0200756 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100757 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200758 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200759 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000760
Victor Stinnerfe226c02011-10-03 03:52:20 +0200761 if (PyUnicode_IS_READY(unicode)) {
762 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200763 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200765#ifdef Py_DEBUG
766 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
767#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768
769 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200770 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200771 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
772 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773
774 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
775 PyErr_NoMemory();
776 return -1;
777 }
778 new_size = (length + 1) * char_size;
779
Victor Stinner7a9105a2011-12-12 00:13:42 +0100780 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
781 {
782 PyObject_DEL(_PyUnicode_UTF8(unicode));
783 _PyUnicode_UTF8(unicode) = NULL;
784 _PyUnicode_UTF8_LENGTH(unicode) = 0;
785 }
786
Victor Stinnerfe226c02011-10-03 03:52:20 +0200787 data = (PyObject *)PyObject_REALLOC(data, new_size);
788 if (data == NULL) {
789 PyErr_NoMemory();
790 return -1;
791 }
792 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200793 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200795 _PyUnicode_WSTR_LENGTH(unicode) = length;
796 }
797 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200798 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200799 _PyUnicode_UTF8_LENGTH(unicode) = length;
800 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200801 _PyUnicode_LENGTH(unicode) = length;
802 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200803#ifdef Py_DEBUG
804 unicode_fill_invalid(unicode, old_length);
805#endif
Victor Stinner95663112011-10-04 01:03:50 +0200806 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200807 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200808 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200809 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200810 }
Victor Stinner95663112011-10-04 01:03:50 +0200811 assert(_PyUnicode_WSTR(unicode) != NULL);
812
813 /* check for integer overflow */
814 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
815 PyErr_NoMemory();
816 return -1;
817 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100818 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200819 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100820 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200821 if (!wstr) {
822 PyErr_NoMemory();
823 return -1;
824 }
825 _PyUnicode_WSTR(unicode) = wstr;
826 _PyUnicode_WSTR(unicode)[length] = 0;
827 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200828 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000829 return 0;
830}
831
Victor Stinnerfe226c02011-10-03 03:52:20 +0200832static PyObject*
833resize_copy(PyObject *unicode, Py_ssize_t length)
834{
835 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100836 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200837 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100838
Benjamin Petersonbac79492012-01-14 13:34:47 -0500839 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100840 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200841
842 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
843 if (copy == NULL)
844 return NULL;
845
846 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200847 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200848 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200849 }
850 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200851 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100852
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200853 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200854 if (w == NULL)
855 return NULL;
856 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
857 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200858 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
859 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200860 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200861 }
862}
863
Guido van Rossumd57fd912000-03-10 22:53:23 +0000864/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000865 Ux0000 terminated; some code (e.g. new_identifier)
866 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000867
868 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000869 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000870
871*/
872
Alexander Belopolsky40018472011-02-26 01:02:56 +0000873static PyUnicodeObject *
874_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200876 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000878
Thomas Wouters477c8d52006-05-27 19:21:47 +0000879 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880 if (length == 0 && unicode_empty != NULL) {
881 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200882 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883 }
884
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000885 /* Ensure we won't overflow the size. */
886 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
887 return (PyUnicodeObject *)PyErr_NoMemory();
888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200889 if (length < 0) {
890 PyErr_SetString(PyExc_SystemError,
891 "Negative size passed to _PyUnicode_New");
892 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000893 }
894
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200895 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
896 if (unicode == NULL)
897 return NULL;
898 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
899 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
900 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100901 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000902 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100903 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905
Jeremy Hyltond8082792003-09-16 19:41:39 +0000906 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000907 * the caller fails before initializing str -- unicode_resize()
908 * reads str[0], and the Keep-Alive optimization can keep memory
909 * allocated for str alive across a call to unicode_dealloc(unicode).
910 * We don't want unicode_resize to read uninitialized memory in
911 * that case.
912 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 _PyUnicode_WSTR(unicode)[0] = 0;
914 _PyUnicode_WSTR(unicode)[length] = 0;
915 _PyUnicode_WSTR_LENGTH(unicode) = length;
916 _PyUnicode_HASH(unicode) = -1;
917 _PyUnicode_STATE(unicode).interned = 0;
918 _PyUnicode_STATE(unicode).kind = 0;
919 _PyUnicode_STATE(unicode).compact = 0;
920 _PyUnicode_STATE(unicode).ready = 0;
921 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200922 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200924 _PyUnicode_UTF8(unicode) = NULL;
925 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100926 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000927 return unicode;
928}
929
Victor Stinnerf42dc442011-10-02 23:33:16 +0200930static const char*
931unicode_kind_name(PyObject *unicode)
932{
Victor Stinner42dfd712011-10-03 14:41:45 +0200933 /* don't check consistency: unicode_kind_name() is called from
934 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200935 if (!PyUnicode_IS_COMPACT(unicode))
936 {
937 if (!PyUnicode_IS_READY(unicode))
938 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600939 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200940 {
941 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200942 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 return "legacy ascii";
944 else
945 return "legacy latin1";
946 case PyUnicode_2BYTE_KIND:
947 return "legacy UCS2";
948 case PyUnicode_4BYTE_KIND:
949 return "legacy UCS4";
950 default:
951 return "<legacy invalid kind>";
952 }
953 }
954 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600955 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200956 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200957 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200958 return "ascii";
959 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200960 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200961 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200962 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200963 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965 default:
966 return "<invalid compact kind>";
967 }
968}
969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200970#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200971/* Functions wrapping macros for use in debugger */
972char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200973 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974}
975
976void *_PyUnicode_compact_data(void *unicode) {
977 return _PyUnicode_COMPACT_DATA(unicode);
978}
979void *_PyUnicode_data(void *unicode){
980 printf("obj %p\n", unicode);
981 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
982 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
983 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
984 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
985 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
986 return PyUnicode_DATA(unicode);
987}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200988
989void
990_PyUnicode_Dump(PyObject *op)
991{
992 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200993 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
994 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
995 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200996
Victor Stinnera849a4b2011-10-03 12:12:11 +0200997 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200998 {
999 if (ascii->state.ascii)
1000 data = (ascii + 1);
1001 else
1002 data = (compact + 1);
1003 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001004 else
1005 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
1007
Victor Stinnera849a4b2011-10-03 12:12:11 +02001008 if (ascii->wstr == data)
1009 printf("shared ");
1010 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001011
Victor Stinnera3b334d2011-10-03 13:53:37 +02001012 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +02001013 printf(" (%zu), ", compact->wstr_length);
1014 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1015 printf("shared ");
1016 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001017 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001018 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001019}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001020#endif
1021
1022PyObject *
1023PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1024{
1025 PyObject *obj;
1026 PyCompactUnicodeObject *unicode;
1027 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001028 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001029 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030 Py_ssize_t char_size;
1031 Py_ssize_t struct_size;
1032
1033 /* Optimization for empty strings */
1034 if (size == 0 && unicode_empty != NULL) {
1035 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001036 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001037 }
1038
Victor Stinner9e9d6892011-10-04 01:02:02 +02001039 is_ascii = 0;
1040 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001041 struct_size = sizeof(PyCompactUnicodeObject);
1042 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001043 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 char_size = 1;
1045 is_ascii = 1;
1046 struct_size = sizeof(PyASCIIObject);
1047 }
1048 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001049 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 char_size = 1;
1051 }
1052 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001053 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 char_size = 2;
1055 if (sizeof(wchar_t) == 2)
1056 is_sharing = 1;
1057 }
1058 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001059 if (maxchar > MAX_UNICODE) {
1060 PyErr_SetString(PyExc_SystemError,
1061 "invalid maximum character passed to PyUnicode_New");
1062 return NULL;
1063 }
Victor Stinner8f825062012-04-27 13:55:39 +02001064 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001065 char_size = 4;
1066 if (sizeof(wchar_t) == 4)
1067 is_sharing = 1;
1068 }
1069
1070 /* Ensure we won't overflow the size. */
1071 if (size < 0) {
1072 PyErr_SetString(PyExc_SystemError,
1073 "Negative size passed to PyUnicode_New");
1074 return NULL;
1075 }
1076 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1077 return PyErr_NoMemory();
1078
1079 /* Duplicated allocation code from _PyObject_New() instead of a call to
1080 * PyObject_New() so we are able to allocate space for the object and
1081 * it's data buffer.
1082 */
1083 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1084 if (obj == NULL)
1085 return PyErr_NoMemory();
1086 obj = PyObject_INIT(obj, &PyUnicode_Type);
1087 if (obj == NULL)
1088 return NULL;
1089
1090 unicode = (PyCompactUnicodeObject *)obj;
1091 if (is_ascii)
1092 data = ((PyASCIIObject*)obj) + 1;
1093 else
1094 data = unicode + 1;
1095 _PyUnicode_LENGTH(unicode) = size;
1096 _PyUnicode_HASH(unicode) = -1;
1097 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001098 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099 _PyUnicode_STATE(unicode).compact = 1;
1100 _PyUnicode_STATE(unicode).ready = 1;
1101 _PyUnicode_STATE(unicode).ascii = is_ascii;
1102 if (is_ascii) {
1103 ((char*)data)[size] = 0;
1104 _PyUnicode_WSTR(unicode) = NULL;
1105 }
Victor Stinner8f825062012-04-27 13:55:39 +02001106 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107 ((char*)data)[size] = 0;
1108 _PyUnicode_WSTR(unicode) = NULL;
1109 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001111 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001112 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001113 else {
1114 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001115 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001116 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001118 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 ((Py_UCS4*)data)[size] = 0;
1120 if (is_sharing) {
1121 _PyUnicode_WSTR_LENGTH(unicode) = size;
1122 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1123 }
1124 else {
1125 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1126 _PyUnicode_WSTR(unicode) = NULL;
1127 }
1128 }
Victor Stinner8f825062012-04-27 13:55:39 +02001129#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001130 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001131#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001132 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001133 return obj;
1134}
1135
1136#if SIZEOF_WCHAR_T == 2
1137/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1138 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001139 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001140
1141 This function assumes that unicode can hold one more code point than wstr
1142 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001143static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001145 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146{
1147 const wchar_t *iter;
1148 Py_UCS4 *ucs4_out;
1149
Victor Stinner910337b2011-10-03 03:20:16 +02001150 assert(unicode != NULL);
1151 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1153 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1154
1155 for (iter = begin; iter < end; ) {
1156 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1157 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001158 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1159 && (iter+1) < end
1160 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161 {
Victor Stinner551ac952011-11-29 22:58:13 +01001162 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001163 iter += 2;
1164 }
1165 else {
1166 *ucs4_out++ = *iter;
1167 iter++;
1168 }
1169 }
1170 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1171 _PyUnicode_GET_LENGTH(unicode)));
1172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173}
1174#endif
1175
Victor Stinnercd9950f2011-10-02 00:34:53 +02001176static int
Victor Stinner488fa492011-12-12 00:01:39 +01001177unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001178{
Victor Stinner488fa492011-12-12 00:01:39 +01001179 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001180 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001181 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001182 return -1;
1183 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001184 return 0;
1185}
1186
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001187static int
1188_copy_characters(PyObject *to, Py_ssize_t to_start,
1189 PyObject *from, Py_ssize_t from_start,
1190 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001191{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001192 unsigned int from_kind, to_kind;
1193 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001194
Victor Stinneree4544c2012-05-09 22:24:08 +02001195 assert(0 <= how_many);
1196 assert(0 <= from_start);
1197 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001198 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001199 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001200 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201
Victor Stinnerd3f08822012-05-29 12:57:52 +02001202 assert(PyUnicode_Check(to));
1203 assert(PyUnicode_IS_READY(to));
1204 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1205
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001206 if (how_many == 0)
1207 return 0;
1208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001210 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001212 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001213
Victor Stinnerf1852262012-06-16 16:38:26 +02001214#ifdef Py_DEBUG
1215 if (!check_maxchar
1216 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1217 {
1218 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1219 Py_UCS4 ch;
1220 Py_ssize_t i;
1221 for (i=0; i < how_many; i++) {
1222 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1223 assert(ch <= to_maxchar);
1224 }
1225 }
1226#endif
1227
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001228 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001229 if (check_maxchar
1230 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1231 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001232 /* Writing Latin-1 characters into an ASCII string requires to
1233 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001234 Py_UCS4 max_char;
1235 max_char = ucs1lib_find_max_char(from_data,
1236 (Py_UCS1*)from_data + how_many);
1237 if (max_char >= 128)
1238 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001239 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001240 Py_MEMCPY((char*)to_data + to_kind * to_start,
1241 (char*)from_data + from_kind * from_start,
1242 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001243 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001244 else if (from_kind == PyUnicode_1BYTE_KIND
1245 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001246 {
1247 _PyUnicode_CONVERT_BYTES(
1248 Py_UCS1, Py_UCS2,
1249 PyUnicode_1BYTE_DATA(from) + from_start,
1250 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1251 PyUnicode_2BYTE_DATA(to) + to_start
1252 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001253 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001254 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001255 && to_kind == PyUnicode_4BYTE_KIND)
1256 {
1257 _PyUnicode_CONVERT_BYTES(
1258 Py_UCS1, Py_UCS4,
1259 PyUnicode_1BYTE_DATA(from) + from_start,
1260 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1261 PyUnicode_4BYTE_DATA(to) + to_start
1262 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001263 }
1264 else if (from_kind == PyUnicode_2BYTE_KIND
1265 && to_kind == PyUnicode_4BYTE_KIND)
1266 {
1267 _PyUnicode_CONVERT_BYTES(
1268 Py_UCS2, Py_UCS4,
1269 PyUnicode_2BYTE_DATA(from) + from_start,
1270 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1271 PyUnicode_4BYTE_DATA(to) + to_start
1272 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001273 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001274 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001275 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1276
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001277 if (!check_maxchar) {
1278 if (from_kind == PyUnicode_2BYTE_KIND
1279 && to_kind == PyUnicode_1BYTE_KIND)
1280 {
1281 _PyUnicode_CONVERT_BYTES(
1282 Py_UCS2, Py_UCS1,
1283 PyUnicode_2BYTE_DATA(from) + from_start,
1284 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1285 PyUnicode_1BYTE_DATA(to) + to_start
1286 );
1287 }
1288 else if (from_kind == PyUnicode_4BYTE_KIND
1289 && to_kind == PyUnicode_1BYTE_KIND)
1290 {
1291 _PyUnicode_CONVERT_BYTES(
1292 Py_UCS4, Py_UCS1,
1293 PyUnicode_4BYTE_DATA(from) + from_start,
1294 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1295 PyUnicode_1BYTE_DATA(to) + to_start
1296 );
1297 }
1298 else if (from_kind == PyUnicode_4BYTE_KIND
1299 && to_kind == PyUnicode_2BYTE_KIND)
1300 {
1301 _PyUnicode_CONVERT_BYTES(
1302 Py_UCS4, Py_UCS2,
1303 PyUnicode_4BYTE_DATA(from) + from_start,
1304 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1305 PyUnicode_2BYTE_DATA(to) + to_start
1306 );
1307 }
1308 else {
1309 assert(0);
1310 return -1;
1311 }
1312 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001313 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001314 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001315 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001316 Py_ssize_t i;
1317
Victor Stinnera0702ab2011-09-29 14:14:38 +02001318 for (i=0; i < how_many; i++) {
1319 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001320 if (ch > to_maxchar)
1321 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001322 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1323 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 }
1325 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001326 return 0;
1327}
1328
Victor Stinnerd3f08822012-05-29 12:57:52 +02001329void
1330_PyUnicode_FastCopyCharacters(
1331 PyObject *to, Py_ssize_t to_start,
1332 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001333{
1334 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1335}
1336
1337Py_ssize_t
1338PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1339 PyObject *from, Py_ssize_t from_start,
1340 Py_ssize_t how_many)
1341{
1342 int err;
1343
1344 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1345 PyErr_BadInternalCall();
1346 return -1;
1347 }
1348
Benjamin Petersonbac79492012-01-14 13:34:47 -05001349 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001350 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001351 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001352 return -1;
1353
Victor Stinnerd3f08822012-05-29 12:57:52 +02001354 if (from_start < 0) {
1355 PyErr_SetString(PyExc_IndexError, "string index out of range");
1356 return -1;
1357 }
1358 if (to_start < 0) {
1359 PyErr_SetString(PyExc_IndexError, "string index out of range");
1360 return -1;
1361 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001362 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1363 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1364 PyErr_Format(PyExc_SystemError,
1365 "Cannot write %zi characters at %zi "
1366 "in a string of %zi characters",
1367 how_many, to_start, PyUnicode_GET_LENGTH(to));
1368 return -1;
1369 }
1370
1371 if (how_many == 0)
1372 return 0;
1373
Victor Stinner488fa492011-12-12 00:01:39 +01001374 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001375 return -1;
1376
1377 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1378 if (err) {
1379 PyErr_Format(PyExc_SystemError,
1380 "Cannot copy %s characters "
1381 "into a string of %s characters",
1382 unicode_kind_name(from),
1383 unicode_kind_name(to));
1384 return -1;
1385 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001386 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387}
1388
Victor Stinner17222162011-09-28 22:15:37 +02001389/* Find the maximum code point and count the number of surrogate pairs so a
1390 correct string length can be computed before converting a string to UCS4.
1391 This function counts single surrogates as a character and not as a pair.
1392
1393 Return 0 on success, or -1 on error. */
1394static int
1395find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1396 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397{
1398 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001399 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400
Victor Stinnerc53be962011-10-02 21:33:54 +02001401 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402 *num_surrogates = 0;
1403 *maxchar = 0;
1404
1405 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001407 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1408 && (iter+1) < end
1409 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1410 {
1411 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1412 ++(*num_surrogates);
1413 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 }
1415 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001417 {
1418 ch = *iter;
1419 iter++;
1420 }
1421 if (ch > *maxchar) {
1422 *maxchar = ch;
1423 if (*maxchar > MAX_UNICODE) {
1424 PyErr_Format(PyExc_ValueError,
1425 "character U+%x is not in range [U+0000; U+10ffff]",
1426 ch);
1427 return -1;
1428 }
1429 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 }
1431 return 0;
1432}
1433
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001434int
1435_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001436{
1437 wchar_t *end;
1438 Py_UCS4 maxchar = 0;
1439 Py_ssize_t num_surrogates;
1440#if SIZEOF_WCHAR_T == 2
1441 Py_ssize_t length_wo_surrogates;
1442#endif
1443
Georg Brandl7597add2011-10-05 16:36:47 +02001444 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001445 strings were created using _PyObject_New() and where no canonical
1446 representation (the str field) has been set yet aka strings
1447 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001448 assert(_PyUnicode_CHECK(unicode));
1449 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001451 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001453 /* Actually, it should neither be interned nor be anything else: */
1454 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001457 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001458 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460
1461 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1463 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 PyErr_NoMemory();
1465 return -1;
1466 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001467 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 _PyUnicode_WSTR(unicode), end,
1469 PyUnicode_1BYTE_DATA(unicode));
1470 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1471 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1472 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1473 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001474 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001475 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001476 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 }
1478 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001479 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001480 _PyUnicode_UTF8(unicode) = NULL;
1481 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001482 }
1483 PyObject_FREE(_PyUnicode_WSTR(unicode));
1484 _PyUnicode_WSTR(unicode) = NULL;
1485 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1486 }
1487 /* In this case we might have to convert down from 4-byte native
1488 wchar_t to 2-byte unicode. */
1489 else if (maxchar < 65536) {
1490 assert(num_surrogates == 0 &&
1491 "FindMaxCharAndNumSurrogatePairs() messed up");
1492
Victor Stinner506f5922011-09-28 22:34:18 +02001493#if SIZEOF_WCHAR_T == 2
1494 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001495 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001496 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1497 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1498 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001499 _PyUnicode_UTF8(unicode) = NULL;
1500 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001501#else
1502 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001503 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001504 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001505 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001506 PyErr_NoMemory();
1507 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001508 }
Victor Stinner506f5922011-09-28 22:34:18 +02001509 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1510 _PyUnicode_WSTR(unicode), end,
1511 PyUnicode_2BYTE_DATA(unicode));
1512 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1513 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1514 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001515 _PyUnicode_UTF8(unicode) = NULL;
1516 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001517 PyObject_FREE(_PyUnicode_WSTR(unicode));
1518 _PyUnicode_WSTR(unicode) = NULL;
1519 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1520#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 }
1522 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1523 else {
1524#if SIZEOF_WCHAR_T == 2
1525 /* in case the native representation is 2-bytes, we need to allocate a
1526 new normalized 4-byte version. */
1527 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001528 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1529 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001530 PyErr_NoMemory();
1531 return -1;
1532 }
1533 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1534 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001535 _PyUnicode_UTF8(unicode) = NULL;
1536 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001537 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1538 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001539 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyObject_FREE(_PyUnicode_WSTR(unicode));
1541 _PyUnicode_WSTR(unicode) = NULL;
1542 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1543#else
1544 assert(num_surrogates == 0);
1545
Victor Stinnerc3c74152011-10-02 20:39:55 +02001546 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001547 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001548 _PyUnicode_UTF8(unicode) = NULL;
1549 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1551#endif
1552 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1553 }
1554 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001555 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001556 return 0;
1557}
1558
Alexander Belopolsky40018472011-02-26 01:02:56 +00001559static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001560unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001561{
Walter Dörwald16807132007-05-25 13:52:07 +00001562 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001563 case SSTATE_NOT_INTERNED:
1564 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001565
Benjamin Peterson29060642009-01-31 22:14:21 +00001566 case SSTATE_INTERNED_MORTAL:
1567 /* revive dead object temporarily for DelItem */
1568 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001569 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001570 Py_FatalError(
1571 "deletion of interned string failed");
1572 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001573
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 case SSTATE_INTERNED_IMMORTAL:
1575 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001576
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 default:
1578 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001579 }
1580
Victor Stinner03490912011-10-03 23:45:12 +02001581 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001582 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001583 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001584 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001585 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1586 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001587
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001588 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001589}
1590
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001591#ifdef Py_DEBUG
1592static int
1593unicode_is_singleton(PyObject *unicode)
1594{
1595 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1596 if (unicode == unicode_empty)
1597 return 1;
1598 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1599 {
1600 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1601 if (ch < 256 && unicode_latin1[ch] == unicode)
1602 return 1;
1603 }
1604 return 0;
1605}
1606#endif
1607
Alexander Belopolsky40018472011-02-26 01:02:56 +00001608static int
Victor Stinner488fa492011-12-12 00:01:39 +01001609unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001610{
Victor Stinner488fa492011-12-12 00:01:39 +01001611 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001612 if (Py_REFCNT(unicode) != 1)
1613 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001614 if (_PyUnicode_HASH(unicode) != -1)
1615 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001616 if (PyUnicode_CHECK_INTERNED(unicode))
1617 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001618 if (!PyUnicode_CheckExact(unicode))
1619 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001620#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001621 /* singleton refcount is greater than 1 */
1622 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001623#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001624 return 1;
1625}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001626
Victor Stinnerfe226c02011-10-03 03:52:20 +02001627static int
1628unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1629{
1630 PyObject *unicode;
1631 Py_ssize_t old_length;
1632
1633 assert(p_unicode != NULL);
1634 unicode = *p_unicode;
1635
1636 assert(unicode != NULL);
1637 assert(PyUnicode_Check(unicode));
1638 assert(0 <= length);
1639
Victor Stinner910337b2011-10-03 03:20:16 +02001640 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641 old_length = PyUnicode_WSTR_LENGTH(unicode);
1642 else
1643 old_length = PyUnicode_GET_LENGTH(unicode);
1644 if (old_length == length)
1645 return 0;
1646
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001647 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001648 _Py_INCREF_UNICODE_EMPTY();
1649 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001650 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001651 Py_DECREF(*p_unicode);
1652 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001653 return 0;
1654 }
1655
Victor Stinner488fa492011-12-12 00:01:39 +01001656 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001657 PyObject *copy = resize_copy(unicode, length);
1658 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001659 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001660 Py_DECREF(*p_unicode);
1661 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001662 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001663 }
1664
Victor Stinnerfe226c02011-10-03 03:52:20 +02001665 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001666 PyObject *new_unicode = resize_compact(unicode, length);
1667 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001668 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001669 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001671 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001672 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673}
1674
Alexander Belopolsky40018472011-02-26 01:02:56 +00001675int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001676PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001677{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 PyObject *unicode;
1679 if (p_unicode == NULL) {
1680 PyErr_BadInternalCall();
1681 return -1;
1682 }
1683 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001684 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001685 {
1686 PyErr_BadInternalCall();
1687 return -1;
1688 }
1689 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001690}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001691
Victor Stinnerc5166102012-02-22 13:55:02 +01001692/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001693
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001694 WARNING: The function doesn't copy the terminating null character and
1695 doesn't check the maximum character (may write a latin1 character in an
1696 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001697static void
1698unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1699 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001700{
1701 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1702 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001703 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001704
1705 switch (kind) {
1706 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001707 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001708#ifdef Py_DEBUG
1709 if (PyUnicode_IS_ASCII(unicode)) {
1710 Py_UCS4 maxchar = ucs1lib_find_max_char(
1711 (const Py_UCS1*)str,
1712 (const Py_UCS1*)str + len);
1713 assert(maxchar < 128);
1714 }
1715#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001716 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001717 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001718 }
1719 case PyUnicode_2BYTE_KIND: {
1720 Py_UCS2 *start = (Py_UCS2 *)data + index;
1721 Py_UCS2 *ucs2 = start;
1722 assert(index <= PyUnicode_GET_LENGTH(unicode));
1723
Victor Stinner184252a2012-06-16 02:57:41 +02001724 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001725 *ucs2 = (Py_UCS2)*str;
1726
1727 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001728 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001729 }
1730 default: {
1731 Py_UCS4 *start = (Py_UCS4 *)data + index;
1732 Py_UCS4 *ucs4 = start;
1733 assert(kind == PyUnicode_4BYTE_KIND);
1734 assert(index <= PyUnicode_GET_LENGTH(unicode));
1735
Victor Stinner184252a2012-06-16 02:57:41 +02001736 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001737 *ucs4 = (Py_UCS4)*str;
1738
1739 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001740 }
1741 }
1742}
1743
1744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745static PyObject*
1746get_latin1_char(unsigned char ch)
1747{
Victor Stinnera464fc12011-10-02 20:39:30 +02001748 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001749 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001750 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 if (!unicode)
1752 return NULL;
1753 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001754 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 unicode_latin1[ch] = unicode;
1756 }
1757 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001758 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759}
1760
Alexander Belopolsky40018472011-02-26 01:02:56 +00001761PyObject *
1762PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001763{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001764 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765 Py_UCS4 maxchar = 0;
1766 Py_ssize_t num_surrogates;
1767
1768 if (u == NULL)
1769 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001770
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001771 /* If the Unicode data is known at construction time, we can apply
1772 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001774 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001775 if (size == 0)
1776 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 /* Single character Unicode objects in the Latin-1 range are
1779 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001780 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001781 return get_latin1_char((unsigned char)*u);
1782
1783 /* If not empty and not single character, copy the Unicode data
1784 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001785 if (find_maxchar_surrogates(u, u + size,
1786 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 return NULL;
1788
Victor Stinner8faf8212011-12-08 22:14:11 +01001789 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001790 if (!unicode)
1791 return NULL;
1792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793 switch (PyUnicode_KIND(unicode)) {
1794 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001795 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1797 break;
1798 case PyUnicode_2BYTE_KIND:
1799#if Py_UNICODE_SIZE == 2
1800 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1801#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001802 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001803 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1804#endif
1805 break;
1806 case PyUnicode_4BYTE_KIND:
1807#if SIZEOF_WCHAR_T == 2
1808 /* This is the only case which has to process surrogates, thus
1809 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001810 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811#else
1812 assert(num_surrogates == 0);
1813 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1814#endif
1815 break;
1816 default:
1817 assert(0 && "Impossible state");
1818 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001819
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001820 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001821}
1822
Alexander Belopolsky40018472011-02-26 01:02:56 +00001823PyObject *
1824PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001825{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001826 if (size < 0) {
1827 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001828 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001829 return NULL;
1830 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001831 if (u != NULL)
1832 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1833 else
1834 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001835}
1836
Alexander Belopolsky40018472011-02-26 01:02:56 +00001837PyObject *
1838PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001839{
1840 size_t size = strlen(u);
1841 if (size > PY_SSIZE_T_MAX) {
1842 PyErr_SetString(PyExc_OverflowError, "input too long");
1843 return NULL;
1844 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001845 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001846}
1847
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001848PyObject *
1849_PyUnicode_FromId(_Py_Identifier *id)
1850{
1851 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001852 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1853 strlen(id->string),
1854 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001855 if (!id->object)
1856 return NULL;
1857 PyUnicode_InternInPlace(&id->object);
1858 assert(!id->next);
1859 id->next = static_strings;
1860 static_strings = id;
1861 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001862 return id->object;
1863}
1864
1865void
1866_PyUnicode_ClearStaticStrings()
1867{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001868 _Py_Identifier *tmp, *s = static_strings;
1869 while (s) {
1870 Py_DECREF(s->object);
1871 s->object = NULL;
1872 tmp = s->next;
1873 s->next = NULL;
1874 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001875 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001876 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001877}
1878
Benjamin Peterson0df54292012-03-26 14:50:32 -04001879/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001880
Victor Stinnerd3f08822012-05-29 12:57:52 +02001881PyObject*
1882_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001883{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001884 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001885 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001886 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001887#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001888 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001889#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001890 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001891 }
Victor Stinner785938e2011-12-11 20:09:03 +01001892 unicode = PyUnicode_New(size, 127);
1893 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001894 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001895 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1896 assert(_PyUnicode_CheckConsistency(unicode, 1));
1897 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001898}
1899
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001900static Py_UCS4
1901kind_maxchar_limit(unsigned int kind)
1902{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001903 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001904 case PyUnicode_1BYTE_KIND:
1905 return 0x80;
1906 case PyUnicode_2BYTE_KIND:
1907 return 0x100;
1908 case PyUnicode_4BYTE_KIND:
1909 return 0x10000;
1910 default:
1911 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001912 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001913 }
1914}
1915
Victor Stinnere6abb482012-05-02 01:15:40 +02001916Py_LOCAL_INLINE(Py_UCS4)
1917align_maxchar(Py_UCS4 maxchar)
1918{
1919 if (maxchar <= 127)
1920 return 127;
1921 else if (maxchar <= 255)
1922 return 255;
1923 else if (maxchar <= 65535)
1924 return 65535;
1925 else
1926 return MAX_UNICODE;
1927}
1928
Victor Stinner702c7342011-10-05 13:50:52 +02001929static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001930_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001932 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001933 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001934
Serhiy Storchaka678db842013-01-26 12:16:36 +02001935 if (size == 0)
1936 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001937 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001938 if (size == 1)
1939 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001940
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001941 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001942 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 if (!res)
1944 return NULL;
1945 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001946 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001948}
1949
Victor Stinnere57b1c02011-09-28 22:20:48 +02001950static PyObject*
1951_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952{
1953 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001954 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001955
Serhiy Storchaka678db842013-01-26 12:16:36 +02001956 if (size == 0)
1957 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001958 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001959 if (size == 1) {
1960 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001961 int kind;
1962 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001963 if (ch < 256)
1964 return get_latin1_char((unsigned char)ch);
1965
1966 res = PyUnicode_New(1, ch);
1967 if (res == NULL)
1968 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001969 kind = PyUnicode_KIND(res);
1970 data = PyUnicode_DATA(res);
1971 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001972 assert(_PyUnicode_CheckConsistency(res, 1));
1973 return res;
1974 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001975
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001976 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001977 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 if (!res)
1979 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001980 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001981 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001982 else {
1983 _PyUnicode_CONVERT_BYTES(
1984 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1985 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001986 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987 return res;
1988}
1989
Victor Stinnere57b1c02011-09-28 22:20:48 +02001990static PyObject*
1991_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992{
1993 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001995
Serhiy Storchaka678db842013-01-26 12:16:36 +02001996 if (size == 0)
1997 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001998 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001999 if (size == 1) {
2000 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002001 int kind;
2002 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002003 if (ch < 256)
2004 return get_latin1_char((unsigned char)ch);
2005
2006 res = PyUnicode_New(1, ch);
2007 if (res == NULL)
2008 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002009 kind = PyUnicode_KIND(res);
2010 data = PyUnicode_DATA(res);
2011 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002012 assert(_PyUnicode_CheckConsistency(res, 1));
2013 return res;
2014 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002015
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002016 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 if (!res)
2019 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002020 if (max_char < 256)
2021 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2022 PyUnicode_1BYTE_DATA(res));
2023 else if (max_char < 0x10000)
2024 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2025 PyUnicode_2BYTE_DATA(res));
2026 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002027 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002028 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 return res;
2030}
2031
2032PyObject*
2033PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2034{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002035 if (size < 0) {
2036 PyErr_SetString(PyExc_ValueError, "size must be positive");
2037 return NULL;
2038 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002039 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002041 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002042 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002043 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002045 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002046 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002047 PyErr_SetString(PyExc_SystemError, "invalid kind");
2048 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050}
2051
Victor Stinnerece58de2012-04-23 23:36:38 +02002052Py_UCS4
2053_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2054{
2055 enum PyUnicode_Kind kind;
2056 void *startptr, *endptr;
2057
2058 assert(PyUnicode_IS_READY(unicode));
2059 assert(0 <= start);
2060 assert(end <= PyUnicode_GET_LENGTH(unicode));
2061 assert(start <= end);
2062
2063 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2064 return PyUnicode_MAX_CHAR_VALUE(unicode);
2065
2066 if (start == end)
2067 return 127;
2068
Victor Stinner94d558b2012-04-27 22:26:58 +02002069 if (PyUnicode_IS_ASCII(unicode))
2070 return 127;
2071
Victor Stinnerece58de2012-04-23 23:36:38 +02002072 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002073 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002074 endptr = (char *)startptr + end * kind;
2075 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002076 switch(kind) {
2077 case PyUnicode_1BYTE_KIND:
2078 return ucs1lib_find_max_char(startptr, endptr);
2079 case PyUnicode_2BYTE_KIND:
2080 return ucs2lib_find_max_char(startptr, endptr);
2081 case PyUnicode_4BYTE_KIND:
2082 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002083 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 assert(0);
2085 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002086 }
2087}
2088
Victor Stinner25a4b292011-10-06 12:31:55 +02002089/* Ensure that a string uses the most efficient storage, if it is not the
2090 case: create a new string with of the right kind. Write NULL into *p_unicode
2091 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002092static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002093unicode_adjust_maxchar(PyObject **p_unicode)
2094{
2095 PyObject *unicode, *copy;
2096 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002097 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002098 unsigned int kind;
2099
2100 assert(p_unicode != NULL);
2101 unicode = *p_unicode;
2102 assert(PyUnicode_IS_READY(unicode));
2103 if (PyUnicode_IS_ASCII(unicode))
2104 return;
2105
2106 len = PyUnicode_GET_LENGTH(unicode);
2107 kind = PyUnicode_KIND(unicode);
2108 if (kind == PyUnicode_1BYTE_KIND) {
2109 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002110 max_char = ucs1lib_find_max_char(u, u + len);
2111 if (max_char >= 128)
2112 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002113 }
2114 else if (kind == PyUnicode_2BYTE_KIND) {
2115 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002116 max_char = ucs2lib_find_max_char(u, u + len);
2117 if (max_char >= 256)
2118 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002119 }
2120 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002121 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002122 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002123 max_char = ucs4lib_find_max_char(u, u + len);
2124 if (max_char >= 0x10000)
2125 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002126 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002128 if (copy != NULL)
2129 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 Py_DECREF(unicode);
2131 *p_unicode = copy;
2132}
2133
Victor Stinner034f6cf2011-09-30 02:26:44 +02002134PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002135_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002136{
Victor Stinner87af4f22011-11-21 23:03:47 +01002137 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002138 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002139
Victor Stinner034f6cf2011-09-30 02:26:44 +02002140 if (!PyUnicode_Check(unicode)) {
2141 PyErr_BadInternalCall();
2142 return NULL;
2143 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002144 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002145 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146
Victor Stinner87af4f22011-11-21 23:03:47 +01002147 length = PyUnicode_GET_LENGTH(unicode);
2148 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002149 if (!copy)
2150 return NULL;
2151 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2152
Victor Stinner87af4f22011-11-21 23:03:47 +01002153 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2154 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002155 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002156 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002157}
2158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002159
Victor Stinnerbc603d12011-10-02 01:00:40 +02002160/* Widen Unicode objects to larger buffers. Don't write terminating null
2161 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162
2163void*
2164_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2165{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002166 Py_ssize_t len;
2167 void *result;
2168 unsigned int skind;
2169
Benjamin Petersonbac79492012-01-14 13:34:47 -05002170 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002171 return NULL;
2172
2173 len = PyUnicode_GET_LENGTH(s);
2174 skind = PyUnicode_KIND(s);
2175 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002176 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 return NULL;
2178 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002179 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002180 case PyUnicode_2BYTE_KIND:
2181 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2182 if (!result)
2183 return PyErr_NoMemory();
2184 assert(skind == PyUnicode_1BYTE_KIND);
2185 _PyUnicode_CONVERT_BYTES(
2186 Py_UCS1, Py_UCS2,
2187 PyUnicode_1BYTE_DATA(s),
2188 PyUnicode_1BYTE_DATA(s) + len,
2189 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002191 case PyUnicode_4BYTE_KIND:
2192 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2193 if (!result)
2194 return PyErr_NoMemory();
2195 if (skind == PyUnicode_2BYTE_KIND) {
2196 _PyUnicode_CONVERT_BYTES(
2197 Py_UCS2, Py_UCS4,
2198 PyUnicode_2BYTE_DATA(s),
2199 PyUnicode_2BYTE_DATA(s) + len,
2200 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002202 else {
2203 assert(skind == PyUnicode_1BYTE_KIND);
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS1, Py_UCS4,
2206 PyUnicode_1BYTE_DATA(s),
2207 PyUnicode_1BYTE_DATA(s) + len,
2208 result);
2209 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002211 default:
2212 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002213 }
Victor Stinner01698042011-10-04 00:04:26 +02002214 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 return NULL;
2216}
2217
2218static Py_UCS4*
2219as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2220 int copy_null)
2221{
2222 int kind;
2223 void *data;
2224 Py_ssize_t len, targetlen;
2225 if (PyUnicode_READY(string) == -1)
2226 return NULL;
2227 kind = PyUnicode_KIND(string);
2228 data = PyUnicode_DATA(string);
2229 len = PyUnicode_GET_LENGTH(string);
2230 targetlen = len;
2231 if (copy_null)
2232 targetlen++;
2233 if (!target) {
2234 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2235 PyErr_NoMemory();
2236 return NULL;
2237 }
2238 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2239 if (!target) {
2240 PyErr_NoMemory();
2241 return NULL;
2242 }
2243 }
2244 else {
2245 if (targetsize < targetlen) {
2246 PyErr_Format(PyExc_SystemError,
2247 "string is longer than the buffer");
2248 if (copy_null && 0 < targetsize)
2249 target[0] = 0;
2250 return NULL;
2251 }
2252 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002253 if (kind == PyUnicode_1BYTE_KIND) {
2254 Py_UCS1 *start = (Py_UCS1 *) data;
2255 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002256 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002257 else if (kind == PyUnicode_2BYTE_KIND) {
2258 Py_UCS2 *start = (Py_UCS2 *) data;
2259 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2260 }
2261 else {
2262 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002263 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002264 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 if (copy_null)
2266 target[len] = 0;
2267 return target;
2268}
2269
2270Py_UCS4*
2271PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2272 int copy_null)
2273{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002274 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 PyErr_BadInternalCall();
2276 return NULL;
2277 }
2278 return as_ucs4(string, target, targetsize, copy_null);
2279}
2280
2281Py_UCS4*
2282PyUnicode_AsUCS4Copy(PyObject *string)
2283{
2284 return as_ucs4(string, NULL, 0, 1);
2285}
2286
2287#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002288
Alexander Belopolsky40018472011-02-26 01:02:56 +00002289PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002290PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002291{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002292 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002293 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002294 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002295 PyErr_BadInternalCall();
2296 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002297 }
2298
Martin v. Löwis790465f2008-04-05 20:41:37 +00002299 if (size == -1) {
2300 size = wcslen(w);
2301 }
2302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002303 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304}
2305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002306#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002307
Walter Dörwald346737f2007-05-31 10:44:43 +00002308static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002309makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002310 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002311{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002312 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002313 if (longflag)
2314 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002315 else if (longlongflag) {
2316 /* longlongflag should only ever be nonzero on machines with
2317 HAVE_LONG_LONG defined */
2318#ifdef HAVE_LONG_LONG
2319 char *f = PY_FORMAT_LONG_LONG;
2320 while (*f)
2321 *fmt++ = *f++;
2322#else
2323 /* we shouldn't ever get here */
2324 assert(0);
2325 *fmt++ = 'l';
2326#endif
2327 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002328 else if (size_tflag) {
2329 char *f = PY_FORMAT_SIZE_T;
2330 while (*f)
2331 *fmt++ = *f++;
2332 }
2333 *fmt++ = c;
2334 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002335}
2336
Victor Stinner15a11362012-10-06 23:48:20 +02002337/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002338 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2339 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2340#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002341
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002342static int
2343unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2344 Py_ssize_t width, Py_ssize_t precision)
2345{
2346 Py_ssize_t length, fill, arglen;
2347 Py_UCS4 maxchar;
2348
2349 if (PyUnicode_READY(str) == -1)
2350 return -1;
2351
2352 length = PyUnicode_GET_LENGTH(str);
2353 if ((precision == -1 || precision >= length)
2354 && width <= length)
2355 return _PyUnicodeWriter_WriteStr(writer, str);
2356
2357 if (precision != -1)
2358 length = Py_MIN(precision, length);
2359
2360 arglen = Py_MAX(length, width);
2361 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2362 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2363 else
2364 maxchar = writer->maxchar;
2365
2366 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2367 return -1;
2368
2369 if (width > length) {
2370 fill = width - length;
2371 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2372 return -1;
2373 writer->pos += fill;
2374 }
2375
2376 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2377 str, 0, length);
2378 writer->pos += length;
2379 return 0;
2380}
2381
2382static int
2383unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2384 Py_ssize_t width, Py_ssize_t precision)
2385{
2386 /* UTF-8 */
2387 Py_ssize_t length;
2388 PyObject *unicode;
2389 int res;
2390
2391 length = strlen(str);
2392 if (precision != -1)
2393 length = Py_MIN(length, precision);
2394 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2395 if (unicode == NULL)
2396 return -1;
2397
2398 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2399 Py_DECREF(unicode);
2400 return res;
2401}
2402
Victor Stinner96865452011-03-01 23:44:09 +00002403static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002404unicode_fromformat_arg(_PyUnicodeWriter *writer,
2405 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002406{
Victor Stinnere215d962012-10-06 23:03:36 +02002407 const char *p;
2408 Py_ssize_t len;
2409 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002410 Py_ssize_t width;
2411 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002412 int longflag;
2413 int longlongflag;
2414 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002415 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002416
2417 p = f;
2418 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002419 zeropad = 0;
2420 if (*f == '0') {
2421 zeropad = 1;
2422 f++;
2423 }
Victor Stinner96865452011-03-01 23:44:09 +00002424
2425 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002426 width = -1;
2427 if (Py_ISDIGIT((unsigned)*f)) {
2428 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002429 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002430 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002431 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002432 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002433 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002434 return NULL;
2435 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002436 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002437 f++;
2438 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 }
2440 precision = -1;
2441 if (*f == '.') {
2442 f++;
2443 if (Py_ISDIGIT((unsigned)*f)) {
2444 precision = (*f - '0');
2445 f++;
2446 while (Py_ISDIGIT((unsigned)*f)) {
2447 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2448 PyErr_SetString(PyExc_ValueError,
2449 "precision too big");
2450 return NULL;
2451 }
2452 precision = (precision * 10) + (*f - '0');
2453 f++;
2454 }
2455 }
Victor Stinner96865452011-03-01 23:44:09 +00002456 if (*f == '%') {
2457 /* "%.3%s" => f points to "3" */
2458 f--;
2459 }
2460 }
2461 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002462 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002463 f--;
2464 }
Victor Stinner96865452011-03-01 23:44:09 +00002465
2466 /* Handle %ld, %lu, %lld and %llu. */
2467 longflag = 0;
2468 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002469 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002470 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002471 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002472 longflag = 1;
2473 ++f;
2474 }
2475#ifdef HAVE_LONG_LONG
2476 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002477 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002478 longlongflag = 1;
2479 f += 2;
2480 }
2481#endif
2482 }
2483 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002484 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002485 size_tflag = 1;
2486 ++f;
2487 }
Victor Stinnere215d962012-10-06 23:03:36 +02002488
2489 if (f[1] == '\0')
2490 writer->overallocate = 0;
2491
2492 switch (*f) {
2493 case 'c':
2494 {
2495 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002496 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002497 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002498 "character argument not in range(0x110000)");
2499 return NULL;
2500 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002501 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002502 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002503 break;
2504 }
2505
2506 case 'i':
2507 case 'd':
2508 case 'u':
2509 case 'x':
2510 {
2511 /* used by sprintf */
2512 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002513 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002514 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002515
2516 if (*f == 'u') {
2517 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2518
2519 if (longflag)
2520 len = sprintf(buffer, fmt,
2521 va_arg(*vargs, unsigned long));
2522#ifdef HAVE_LONG_LONG
2523 else if (longlongflag)
2524 len = sprintf(buffer, fmt,
2525 va_arg(*vargs, unsigned PY_LONG_LONG));
2526#endif
2527 else if (size_tflag)
2528 len = sprintf(buffer, fmt,
2529 va_arg(*vargs, size_t));
2530 else
2531 len = sprintf(buffer, fmt,
2532 va_arg(*vargs, unsigned int));
2533 }
2534 else if (*f == 'x') {
2535 makefmt(fmt, 0, 0, 0, 'x');
2536 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2537 }
2538 else {
2539 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2540
2541 if (longflag)
2542 len = sprintf(buffer, fmt,
2543 va_arg(*vargs, long));
2544#ifdef HAVE_LONG_LONG
2545 else if (longlongflag)
2546 len = sprintf(buffer, fmt,
2547 va_arg(*vargs, PY_LONG_LONG));
2548#endif
2549 else if (size_tflag)
2550 len = sprintf(buffer, fmt,
2551 va_arg(*vargs, Py_ssize_t));
2552 else
2553 len = sprintf(buffer, fmt,
2554 va_arg(*vargs, int));
2555 }
2556 assert(len >= 0);
2557
Victor Stinnere215d962012-10-06 23:03:36 +02002558 if (precision < len)
2559 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002560
2561 arglen = Py_MAX(precision, width);
2562 assert(ucs1lib_find_max_char((Py_UCS1*)buffer, (Py_UCS1*)buffer + len) <= 127);
2563 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2564 return NULL;
2565
Victor Stinnere215d962012-10-06 23:03:36 +02002566 if (width > precision) {
2567 Py_UCS4 fillchar;
2568 fill = width - precision;
2569 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002570 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2571 return NULL;
2572 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002573 }
Victor Stinner15a11362012-10-06 23:48:20 +02002574 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002575 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002576 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2577 return NULL;
2578 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002579 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002580
2581 unicode_write_cstr(writer->buffer, writer->pos, buffer, len);
2582 writer->pos += len;
Victor Stinnere215d962012-10-06 23:03:36 +02002583 break;
2584 }
2585
2586 case 'p':
2587 {
2588 char number[MAX_LONG_LONG_CHARS];
2589
2590 len = sprintf(number, "%p", va_arg(*vargs, void*));
2591 assert(len >= 0);
2592
2593 /* %p is ill-defined: ensure leading 0x. */
2594 if (number[1] == 'X')
2595 number[1] = 'x';
2596 else if (number[1] != 'x') {
2597 memmove(number + 2, number,
2598 strlen(number) + 1);
2599 number[0] = '0';
2600 number[1] = 'x';
2601 len += 2;
2602 }
2603
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002604 assert(ucs1lib_find_max_char((Py_UCS1*)number, (Py_UCS1*)number + len) <= 127);
2605 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002606 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002607 unicode_write_cstr(writer->buffer, writer->pos, number, len);
2608 writer->pos += len;
Victor Stinnere215d962012-10-06 23:03:36 +02002609 break;
2610 }
2611
2612 case 's':
2613 {
2614 /* UTF-8 */
2615 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002616 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002617 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002618 break;
2619 }
2620
2621 case 'U':
2622 {
2623 PyObject *obj = va_arg(*vargs, PyObject *);
2624 assert(obj && _PyUnicode_CHECK(obj));
2625
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002626 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002627 return NULL;
2628 break;
2629 }
2630
2631 case 'V':
2632 {
2633 PyObject *obj = va_arg(*vargs, PyObject *);
2634 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002635 if (obj) {
2636 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002637 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002638 return NULL;
2639 }
2640 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 assert(str != NULL);
2642 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002643 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002644 }
2645 break;
2646 }
2647
2648 case 'S':
2649 {
2650 PyObject *obj = va_arg(*vargs, PyObject *);
2651 PyObject *str;
2652 assert(obj);
2653 str = PyObject_Str(obj);
2654 if (!str)
2655 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002656 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002657 Py_DECREF(str);
2658 return NULL;
2659 }
2660 Py_DECREF(str);
2661 break;
2662 }
2663
2664 case 'R':
2665 {
2666 PyObject *obj = va_arg(*vargs, PyObject *);
2667 PyObject *repr;
2668 assert(obj);
2669 repr = PyObject_Repr(obj);
2670 if (!repr)
2671 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002672 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002673 Py_DECREF(repr);
2674 return NULL;
2675 }
2676 Py_DECREF(repr);
2677 break;
2678 }
2679
2680 case 'A':
2681 {
2682 PyObject *obj = va_arg(*vargs, PyObject *);
2683 PyObject *ascii;
2684 assert(obj);
2685 ascii = PyObject_ASCII(obj);
2686 if (!ascii)
2687 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002688 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002689 Py_DECREF(ascii);
2690 return NULL;
2691 }
2692 Py_DECREF(ascii);
2693 break;
2694 }
2695
2696 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002697 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002698 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002699 break;
2700
2701 default:
2702 /* if we stumble upon an unknown formatting code, copy the rest
2703 of the format string to the output string. (we cannot just
2704 skip the code, since there's no way to know what's in the
2705 argument list) */
2706 len = strlen(p);
2707 if (_PyUnicodeWriter_WriteCstr(writer, p, len) == -1)
2708 return NULL;
2709 f = p+len;
2710 return f;
2711 }
2712
2713 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002714 return f;
2715}
2716
Walter Dörwaldd2034312007-05-18 16:29:38 +00002717PyObject *
2718PyUnicode_FromFormatV(const char *format, va_list vargs)
2719{
Victor Stinnere215d962012-10-06 23:03:36 +02002720 va_list vargs2;
2721 const char *f;
2722 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002723
Victor Stinner8f674cc2013-04-17 23:02:17 +02002724 _PyUnicodeWriter_Init(&writer);
2725 writer.min_length = strlen(format) + 100;
2726 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002727
2728 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2729 Copy it to be able to pass a reference to a subfunction. */
2730 Py_VA_COPY(vargs2, vargs);
2731
2732 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002733 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002734 f = unicode_fromformat_arg(&writer, f, &vargs2);
2735 if (f == NULL)
2736 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002738 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002739 const char *p;
2740 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002741
Victor Stinnere215d962012-10-06 23:03:36 +02002742 p = f;
2743 do
2744 {
2745 if ((unsigned char)*p > 127) {
2746 PyErr_Format(PyExc_ValueError,
2747 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2748 "string, got a non-ASCII byte: 0x%02x",
2749 (unsigned char)*p);
2750 return NULL;
2751 }
2752 p++;
2753 }
2754 while (*p != '\0' && *p != '%');
2755 len = p - f;
2756
2757 if (*p == '\0')
2758 writer.overallocate = 0;
2759 if (_PyUnicodeWriter_Prepare(&writer, len, 127) == -1)
2760 goto fail;
2761 unicode_write_cstr(writer.buffer, writer.pos, f, len);
2762 writer.pos += len;
2763
2764 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002766 }
Victor Stinnere215d962012-10-06 23:03:36 +02002767 return _PyUnicodeWriter_Finish(&writer);
2768
2769 fail:
2770 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002771 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002772}
2773
Walter Dörwaldd2034312007-05-18 16:29:38 +00002774PyObject *
2775PyUnicode_FromFormat(const char *format, ...)
2776{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002777 PyObject* ret;
2778 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002779
2780#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002781 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002783 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002784#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002785 ret = PyUnicode_FromFormatV(format, vargs);
2786 va_end(vargs);
2787 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002788}
2789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790#ifdef HAVE_WCHAR_H
2791
Victor Stinner5593d8a2010-10-02 11:11:27 +00002792/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2793 convert a Unicode object to a wide character string.
2794
Victor Stinnerd88d9832011-09-06 02:00:05 +02002795 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002796 character) required to convert the unicode object. Ignore size argument.
2797
Victor Stinnerd88d9832011-09-06 02:00:05 +02002798 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002800 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002801static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002802unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002803 wchar_t *w,
2804 Py_ssize_t size)
2805{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002806 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002807 const wchar_t *wstr;
2808
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002809 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 if (wstr == NULL)
2811 return -1;
2812
Victor Stinner5593d8a2010-10-02 11:11:27 +00002813 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002814 if (size > res)
2815 size = res + 1;
2816 else
2817 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002818 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002819 return res;
2820 }
2821 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002822 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002823}
2824
2825Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002826PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002827 wchar_t *w,
2828 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002829{
2830 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002831 PyErr_BadInternalCall();
2832 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002834 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002835}
2836
Victor Stinner137c34c2010-09-29 10:25:54 +00002837wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002838PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002839 Py_ssize_t *size)
2840{
2841 wchar_t* buffer;
2842 Py_ssize_t buflen;
2843
2844 if (unicode == NULL) {
2845 PyErr_BadInternalCall();
2846 return NULL;
2847 }
2848
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002849 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850 if (buflen == -1)
2851 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002852 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002853 PyErr_NoMemory();
2854 return NULL;
2855 }
2856
Victor Stinner137c34c2010-09-29 10:25:54 +00002857 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2858 if (buffer == NULL) {
2859 PyErr_NoMemory();
2860 return NULL;
2861 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002862 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002863 if (buflen == -1) {
2864 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002866 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002867 if (size != NULL)
2868 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002869 return buffer;
2870}
2871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002872#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002873
Alexander Belopolsky40018472011-02-26 01:02:56 +00002874PyObject *
2875PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002876{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002877 PyObject *v;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002878 void *data;
2879 int kind;
2880
Victor Stinner8faf8212011-12-08 22:14:11 +01002881 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002882 PyErr_SetString(PyExc_ValueError,
2883 "chr() arg not in range(0x110000)");
2884 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002885 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002886
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002887 if ((Py_UCS4)ordinal < 256)
2888 return get_latin1_char((unsigned char)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002890 v = PyUnicode_New(1, ordinal);
2891 if (v == NULL)
2892 return NULL;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002893 kind = PyUnicode_KIND(v);
2894 data = PyUnicode_DATA(v);
2895 PyUnicode_WRITE(kind, data, 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002896 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002897 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002898}
2899
Alexander Belopolsky40018472011-02-26 01:02:56 +00002900PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002901PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002902{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002903 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002904 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002905 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002906 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002907 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002908 Py_INCREF(obj);
2909 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002910 }
2911 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002912 /* For a Unicode subtype that's not a Unicode object,
2913 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002914 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002915 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002916 PyErr_Format(PyExc_TypeError,
2917 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002918 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002919 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002920}
2921
Alexander Belopolsky40018472011-02-26 01:02:56 +00002922PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002923PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002924 const char *encoding,
2925 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002926{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002927 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002928 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002929
Guido van Rossumd57fd912000-03-10 22:53:23 +00002930 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002931 PyErr_BadInternalCall();
2932 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002933 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002934
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002935 /* Decoding bytes objects is the most common case and should be fast */
2936 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002937 if (PyBytes_GET_SIZE(obj) == 0)
2938 _Py_RETURN_UNICODE_EMPTY();
2939 v = PyUnicode_Decode(
2940 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2941 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002942 return v;
2943 }
2944
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002945 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002946 PyErr_SetString(PyExc_TypeError,
2947 "decoding str is not supported");
2948 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002949 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002950
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002951 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2952 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2953 PyErr_Format(PyExc_TypeError,
2954 "coercing to str: need bytes, bytearray "
2955 "or buffer-like object, %.80s found",
2956 Py_TYPE(obj)->tp_name);
2957 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002958 }
Tim Petersced69f82003-09-16 20:30:58 +00002959
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002960 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002961 PyBuffer_Release(&buffer);
2962 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002964
Serhiy Storchaka05997252013-01-26 12:14:02 +02002965 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002966 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002967 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002968}
2969
Victor Stinner600d3be2010-06-10 12:00:55 +00002970/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002971 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2972 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002973int
2974_Py_normalize_encoding(const char *encoding,
2975 char *lower,
2976 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002977{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002978 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002979 char *l;
2980 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002981
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002982 if (encoding == NULL) {
2983 strcpy(lower, "utf-8");
2984 return 1;
2985 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002986 e = encoding;
2987 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002988 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002989 while (*e) {
2990 if (l == l_end)
2991 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002992 if (Py_ISUPPER(*e)) {
2993 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002994 }
2995 else if (*e == '_') {
2996 *l++ = '-';
2997 e++;
2998 }
2999 else {
3000 *l++ = *e++;
3001 }
3002 }
3003 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003004 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003005}
3006
Alexander Belopolsky40018472011-02-26 01:02:56 +00003007PyObject *
3008PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003009 Py_ssize_t size,
3010 const char *encoding,
3011 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003012{
3013 PyObject *buffer = NULL, *unicode;
3014 Py_buffer info;
3015 char lower[11]; /* Enough for any encoding shortcut */
3016
Fred Drakee4315f52000-05-09 19:53:39 +00003017 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003018 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003019 if ((strcmp(lower, "utf-8") == 0) ||
3020 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003021 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003022 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003023 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003024 (strcmp(lower, "iso-8859-1") == 0) ||
3025 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003026 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003027#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003028 else if (strcmp(lower, "mbcs") == 0)
3029 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003030#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003031 else if (strcmp(lower, "ascii") == 0)
3032 return PyUnicode_DecodeASCII(s, size, errors);
3033 else if (strcmp(lower, "utf-16") == 0)
3034 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3035 else if (strcmp(lower, "utf-32") == 0)
3036 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3037 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003038
3039 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003040 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003041 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003042 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003043 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003044 if (buffer == NULL)
3045 goto onError;
3046 unicode = PyCodec_Decode(buffer, encoding, errors);
3047 if (unicode == NULL)
3048 goto onError;
3049 if (!PyUnicode_Check(unicode)) {
3050 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003051 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003052 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003053 Py_DECREF(unicode);
3054 goto onError;
3055 }
3056 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003057 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003058
Benjamin Peterson29060642009-01-31 22:14:21 +00003059 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060 Py_XDECREF(buffer);
3061 return NULL;
3062}
3063
Alexander Belopolsky40018472011-02-26 01:02:56 +00003064PyObject *
3065PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003066 const char *encoding,
3067 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003068{
3069 PyObject *v;
3070
3071 if (!PyUnicode_Check(unicode)) {
3072 PyErr_BadArgument();
3073 goto onError;
3074 }
3075
3076 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003078
3079 /* Decode via the codec registry */
3080 v = PyCodec_Decode(unicode, encoding, errors);
3081 if (v == NULL)
3082 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003083 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003084
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003086 return NULL;
3087}
3088
Alexander Belopolsky40018472011-02-26 01:02:56 +00003089PyObject *
3090PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003091 const char *encoding,
3092 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003093{
3094 PyObject *v;
3095
3096 if (!PyUnicode_Check(unicode)) {
3097 PyErr_BadArgument();
3098 goto onError;
3099 }
3100
3101 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003102 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003103
3104 /* Decode via the codec registry */
3105 v = PyCodec_Decode(unicode, encoding, errors);
3106 if (v == NULL)
3107 goto onError;
3108 if (!PyUnicode_Check(v)) {
3109 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003110 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003111 Py_TYPE(v)->tp_name);
3112 Py_DECREF(v);
3113 goto onError;
3114 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003115 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003116
Benjamin Peterson29060642009-01-31 22:14:21 +00003117 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003118 return NULL;
3119}
3120
Alexander Belopolsky40018472011-02-26 01:02:56 +00003121PyObject *
3122PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003123 Py_ssize_t size,
3124 const char *encoding,
3125 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003126{
3127 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003128
Guido van Rossumd57fd912000-03-10 22:53:23 +00003129 unicode = PyUnicode_FromUnicode(s, size);
3130 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003131 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003132 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3133 Py_DECREF(unicode);
3134 return v;
3135}
3136
Alexander Belopolsky40018472011-02-26 01:02:56 +00003137PyObject *
3138PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003139 const char *encoding,
3140 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003141{
3142 PyObject *v;
3143
3144 if (!PyUnicode_Check(unicode)) {
3145 PyErr_BadArgument();
3146 goto onError;
3147 }
3148
3149 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003150 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003151
3152 /* Encode via the codec registry */
3153 v = PyCodec_Encode(unicode, encoding, errors);
3154 if (v == NULL)
3155 goto onError;
3156 return v;
3157
Benjamin Peterson29060642009-01-31 22:14:21 +00003158 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003159 return NULL;
3160}
3161
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003162static size_t
3163wcstombs_errorpos(const wchar_t *wstr)
3164{
3165 size_t len;
3166#if SIZEOF_WCHAR_T == 2
3167 wchar_t buf[3];
3168#else
3169 wchar_t buf[2];
3170#endif
3171 char outbuf[MB_LEN_MAX];
3172 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003173
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003174#if SIZEOF_WCHAR_T == 2
3175 buf[2] = 0;
3176#else
3177 buf[1] = 0;
3178#endif
3179 start = wstr;
3180 while (*wstr != L'\0')
3181 {
3182 previous = wstr;
3183#if SIZEOF_WCHAR_T == 2
3184 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3185 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3186 {
3187 buf[0] = wstr[0];
3188 buf[1] = wstr[1];
3189 wstr += 2;
3190 }
3191 else {
3192 buf[0] = *wstr;
3193 buf[1] = 0;
3194 wstr++;
3195 }
3196#else
3197 buf[0] = *wstr;
3198 wstr++;
3199#endif
3200 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003201 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003202 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003203 }
3204
3205 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003206 return 0;
3207}
3208
Victor Stinner1b579672011-12-17 05:47:23 +01003209static int
3210locale_error_handler(const char *errors, int *surrogateescape)
3211{
3212 if (errors == NULL) {
3213 *surrogateescape = 0;
3214 return 0;
3215 }
3216
3217 if (strcmp(errors, "strict") == 0) {
3218 *surrogateescape = 0;
3219 return 0;
3220 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003221 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003222 *surrogateescape = 1;
3223 return 0;
3224 }
3225 PyErr_Format(PyExc_ValueError,
3226 "only 'strict' and 'surrogateescape' error handlers "
3227 "are supported, not '%s'",
3228 errors);
3229 return -1;
3230}
3231
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003232PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003233PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003234{
3235 Py_ssize_t wlen, wlen2;
3236 wchar_t *wstr;
3237 PyObject *bytes = NULL;
3238 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003239 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003240 PyObject *exc;
3241 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003242 int surrogateescape;
3243
3244 if (locale_error_handler(errors, &surrogateescape) < 0)
3245 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003246
3247 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3248 if (wstr == NULL)
3249 return NULL;
3250
3251 wlen2 = wcslen(wstr);
3252 if (wlen2 != wlen) {
3253 PyMem_Free(wstr);
3254 PyErr_SetString(PyExc_TypeError, "embedded null character");
3255 return NULL;
3256 }
3257
3258 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003259 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003260 char *str;
3261
3262 str = _Py_wchar2char(wstr, &error_pos);
3263 if (str == NULL) {
3264 if (error_pos == (size_t)-1) {
3265 PyErr_NoMemory();
3266 PyMem_Free(wstr);
3267 return NULL;
3268 }
3269 else {
3270 goto encode_error;
3271 }
3272 }
3273 PyMem_Free(wstr);
3274
3275 bytes = PyBytes_FromString(str);
3276 PyMem_Free(str);
3277 }
3278 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003279 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 size_t len, len2;
3281
3282 len = wcstombs(NULL, wstr, 0);
3283 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003284 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003285 goto encode_error;
3286 }
3287
3288 bytes = PyBytes_FromStringAndSize(NULL, len);
3289 if (bytes == NULL) {
3290 PyMem_Free(wstr);
3291 return NULL;
3292 }
3293
3294 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3295 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003296 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003297 goto encode_error;
3298 }
3299 PyMem_Free(wstr);
3300 }
3301 return bytes;
3302
3303encode_error:
3304 errmsg = strerror(errno);
3305 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003306
3307 if (error_pos == (size_t)-1)
3308 error_pos = wcstombs_errorpos(wstr);
3309
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003310 PyMem_Free(wstr);
3311 Py_XDECREF(bytes);
3312
Victor Stinner2f197072011-12-17 07:08:30 +01003313 if (errmsg != NULL) {
3314 size_t errlen;
3315 wstr = _Py_char2wchar(errmsg, &errlen);
3316 if (wstr != NULL) {
3317 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003318 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003319 } else
3320 errmsg = NULL;
3321 }
3322 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003323 reason = PyUnicode_FromString(
3324 "wcstombs() encountered an unencodable "
3325 "wide character");
3326 if (reason == NULL)
3327 return NULL;
3328
3329 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3330 "locale", unicode,
3331 (Py_ssize_t)error_pos,
3332 (Py_ssize_t)(error_pos+1),
3333 reason);
3334 Py_DECREF(reason);
3335 if (exc != NULL) {
3336 PyCodec_StrictErrors(exc);
3337 Py_XDECREF(exc);
3338 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003339 return NULL;
3340}
3341
Victor Stinnerad158722010-10-27 00:25:46 +00003342PyObject *
3343PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003344{
Victor Stinner99b95382011-07-04 14:23:54 +02003345#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003346 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003347#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003348 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003349#else
Victor Stinner793b5312011-04-27 00:24:21 +02003350 PyInterpreterState *interp = PyThreadState_GET()->interp;
3351 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3352 cannot use it to encode and decode filenames before it is loaded. Load
3353 the Python codec requires to encode at least its own filename. Use the C
3354 version of the locale codec until the codec registry is initialized and
3355 the Python codec is loaded.
3356
3357 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3358 cannot only rely on it: check also interp->fscodec_initialized for
3359 subinterpreters. */
3360 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003361 return PyUnicode_AsEncodedString(unicode,
3362 Py_FileSystemDefaultEncoding,
3363 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003364 }
3365 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003366 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003367 }
Victor Stinnerad158722010-10-27 00:25:46 +00003368#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003369}
3370
Alexander Belopolsky40018472011-02-26 01:02:56 +00003371PyObject *
3372PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003373 const char *encoding,
3374 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003375{
3376 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003377 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003378
Guido van Rossumd57fd912000-03-10 22:53:23 +00003379 if (!PyUnicode_Check(unicode)) {
3380 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003381 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003382 }
Fred Drakee4315f52000-05-09 19:53:39 +00003383
Fred Drakee4315f52000-05-09 19:53:39 +00003384 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003385 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003386 if ((strcmp(lower, "utf-8") == 0) ||
3387 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003388 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003389 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003390 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003391 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003392 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003393 }
Victor Stinner37296e82010-06-10 13:36:23 +00003394 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003395 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003396 (strcmp(lower, "iso-8859-1") == 0) ||
3397 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003398 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003399#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003400 else if (strcmp(lower, "mbcs") == 0)
3401 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003402#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003403 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003404 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003405 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003406
3407 /* Encode via the codec registry */
3408 v = PyCodec_Encode(unicode, encoding, errors);
3409 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003410 return NULL;
3411
3412 /* The normal path */
3413 if (PyBytes_Check(v))
3414 return v;
3415
3416 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003417 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003418 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003419 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003420
3421 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3422 "encoder %s returned bytearray instead of bytes",
3423 encoding);
3424 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003425 Py_DECREF(v);
3426 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003427 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003428
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003429 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3430 Py_DECREF(v);
3431 return b;
3432 }
3433
3434 PyErr_Format(PyExc_TypeError,
3435 "encoder did not return a bytes object (type=%.400s)",
3436 Py_TYPE(v)->tp_name);
3437 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438 return NULL;
3439}
3440
Alexander Belopolsky40018472011-02-26 01:02:56 +00003441PyObject *
3442PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003443 const char *encoding,
3444 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003445{
3446 PyObject *v;
3447
3448 if (!PyUnicode_Check(unicode)) {
3449 PyErr_BadArgument();
3450 goto onError;
3451 }
3452
3453 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003454 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003455
3456 /* Encode via the codec registry */
3457 v = PyCodec_Encode(unicode, encoding, errors);
3458 if (v == NULL)
3459 goto onError;
3460 if (!PyUnicode_Check(v)) {
3461 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003462 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003463 Py_TYPE(v)->tp_name);
3464 Py_DECREF(v);
3465 goto onError;
3466 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003467 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003468
Benjamin Peterson29060642009-01-31 22:14:21 +00003469 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003470 return NULL;
3471}
3472
Victor Stinner2f197072011-12-17 07:08:30 +01003473static size_t
3474mbstowcs_errorpos(const char *str, size_t len)
3475{
3476#ifdef HAVE_MBRTOWC
3477 const char *start = str;
3478 mbstate_t mbs;
3479 size_t converted;
3480 wchar_t ch;
3481
3482 memset(&mbs, 0, sizeof mbs);
3483 while (len)
3484 {
3485 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3486 if (converted == 0)
3487 /* Reached end of string */
3488 break;
3489 if (converted == (size_t)-1 || converted == (size_t)-2) {
3490 /* Conversion error or incomplete character */
3491 return str - start;
3492 }
3493 else {
3494 str += converted;
3495 len -= converted;
3496 }
3497 }
3498 /* failed to find the undecodable byte sequence */
3499 return 0;
3500#endif
3501 return 0;
3502}
3503
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003504PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003505PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003506 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003507{
3508 wchar_t smallbuf[256];
3509 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3510 wchar_t *wstr;
3511 size_t wlen, wlen2;
3512 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003513 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003514 size_t error_pos;
3515 char *errmsg;
3516 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003517
3518 if (locale_error_handler(errors, &surrogateescape) < 0)
3519 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003520
3521 if (str[len] != '\0' || len != strlen(str)) {
3522 PyErr_SetString(PyExc_TypeError, "embedded null character");
3523 return NULL;
3524 }
3525
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003526 if (surrogateescape) {
3527 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003528 wstr = _Py_char2wchar(str, &wlen);
3529 if (wstr == NULL) {
3530 if (wlen == (size_t)-1)
3531 PyErr_NoMemory();
3532 else
3533 PyErr_SetFromErrno(PyExc_OSError);
3534 return NULL;
3535 }
3536
3537 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003538 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003539 }
3540 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003541 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003542#ifndef HAVE_BROKEN_MBSTOWCS
3543 wlen = mbstowcs(NULL, str, 0);
3544#else
3545 wlen = len;
3546#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003547 if (wlen == (size_t)-1)
3548 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549 if (wlen+1 <= smallbuf_len) {
3550 wstr = smallbuf;
3551 }
3552 else {
3553 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3554 return PyErr_NoMemory();
3555
3556 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3557 if (!wstr)
3558 return PyErr_NoMemory();
3559 }
3560
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003561 wlen2 = mbstowcs(wstr, str, wlen+1);
3562 if (wlen2 == (size_t)-1) {
3563 if (wstr != smallbuf)
3564 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003565 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003566 }
3567#ifdef HAVE_BROKEN_MBSTOWCS
3568 assert(wlen2 == wlen);
3569#endif
3570 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3571 if (wstr != smallbuf)
3572 PyMem_Free(wstr);
3573 }
3574 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003575
3576decode_error:
3577 errmsg = strerror(errno);
3578 assert(errmsg != NULL);
3579
3580 error_pos = mbstowcs_errorpos(str, len);
3581 if (errmsg != NULL) {
3582 size_t errlen;
3583 wstr = _Py_char2wchar(errmsg, &errlen);
3584 if (wstr != NULL) {
3585 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003586 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003587 } else
3588 errmsg = NULL;
3589 }
3590 if (errmsg == NULL)
3591 reason = PyUnicode_FromString(
3592 "mbstowcs() encountered an invalid multibyte sequence");
3593 if (reason == NULL)
3594 return NULL;
3595
3596 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3597 "locale", str, len,
3598 (Py_ssize_t)error_pos,
3599 (Py_ssize_t)(error_pos+1),
3600 reason);
3601 Py_DECREF(reason);
3602 if (exc != NULL) {
3603 PyCodec_StrictErrors(exc);
3604 Py_XDECREF(exc);
3605 }
3606 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003607}
3608
3609PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003610PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003611{
3612 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003613 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003614}
3615
3616
3617PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003618PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003619 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003620 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3621}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003622
Christian Heimes5894ba72007-11-04 11:43:14 +00003623PyObject*
3624PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3625{
Victor Stinner99b95382011-07-04 14:23:54 +02003626#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003627 return PyUnicode_DecodeMBCS(s, size, NULL);
3628#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003629 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003630#else
Victor Stinner793b5312011-04-27 00:24:21 +02003631 PyInterpreterState *interp = PyThreadState_GET()->interp;
3632 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3633 cannot use it to encode and decode filenames before it is loaded. Load
3634 the Python codec requires to encode at least its own filename. Use the C
3635 version of the locale codec until the codec registry is initialized and
3636 the Python codec is loaded.
3637
3638 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3639 cannot only rely on it: check also interp->fscodec_initialized for
3640 subinterpreters. */
3641 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003642 return PyUnicode_Decode(s, size,
3643 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003644 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003645 }
3646 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003647 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003648 }
Victor Stinnerad158722010-10-27 00:25:46 +00003649#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003650}
3651
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652
3653int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003654_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003655{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003656 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003657
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003658 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003659 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003660 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3661 PyUnicode_GET_LENGTH(str), '\0', 1);
3662 if (pos == -1)
3663 return 0;
3664 else
3665 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003666}
3667
Antoine Pitrou13348842012-01-29 18:36:34 +01003668int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003669PyUnicode_FSConverter(PyObject* arg, void* addr)
3670{
3671 PyObject *output = NULL;
3672 Py_ssize_t size;
3673 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003674 if (arg == NULL) {
3675 Py_DECREF(*(PyObject**)addr);
3676 return 1;
3677 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003678 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003679 output = arg;
3680 Py_INCREF(output);
3681 }
3682 else {
3683 arg = PyUnicode_FromObject(arg);
3684 if (!arg)
3685 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003686 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003687 Py_DECREF(arg);
3688 if (!output)
3689 return 0;
3690 if (!PyBytes_Check(output)) {
3691 Py_DECREF(output);
3692 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3693 return 0;
3694 }
3695 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003696 size = PyBytes_GET_SIZE(output);
3697 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003698 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003699 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003700 Py_DECREF(output);
3701 return 0;
3702 }
3703 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003704 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003705}
3706
3707
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003708int
3709PyUnicode_FSDecoder(PyObject* arg, void* addr)
3710{
3711 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003712 if (arg == NULL) {
3713 Py_DECREF(*(PyObject**)addr);
3714 return 1;
3715 }
3716 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003717 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003718 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003719 output = arg;
3720 Py_INCREF(output);
3721 }
3722 else {
3723 arg = PyBytes_FromObject(arg);
3724 if (!arg)
3725 return 0;
3726 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3727 PyBytes_GET_SIZE(arg));
3728 Py_DECREF(arg);
3729 if (!output)
3730 return 0;
3731 if (!PyUnicode_Check(output)) {
3732 Py_DECREF(output);
3733 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3734 return 0;
3735 }
3736 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003737 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003738 Py_DECREF(output);
3739 return 0;
3740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003741 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003742 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003743 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3744 Py_DECREF(output);
3745 return 0;
3746 }
3747 *(PyObject**)addr = output;
3748 return Py_CLEANUP_SUPPORTED;
3749}
3750
3751
Martin v. Löwis5b222132007-06-10 09:51:05 +00003752char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003753PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003754{
Christian Heimesf3863112007-11-22 07:46:41 +00003755 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003757 if (!PyUnicode_Check(unicode)) {
3758 PyErr_BadArgument();
3759 return NULL;
3760 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003761 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003762 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003763
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003764 if (PyUnicode_UTF8(unicode) == NULL) {
3765 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3767 if (bytes == NULL)
3768 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003769 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3770 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003771 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003772 Py_DECREF(bytes);
3773 return NULL;
3774 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003775 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3776 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3777 PyBytes_AS_STRING(bytes),
3778 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 Py_DECREF(bytes);
3780 }
3781
3782 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003783 *psize = PyUnicode_UTF8_LENGTH(unicode);
3784 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003785}
3786
3787char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003789{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003790 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3791}
3792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793Py_UNICODE *
3794PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796 const unsigned char *one_byte;
3797#if SIZEOF_WCHAR_T == 4
3798 const Py_UCS2 *two_bytes;
3799#else
3800 const Py_UCS4 *four_bytes;
3801 const Py_UCS4 *ucs4_end;
3802 Py_ssize_t num_surrogates;
3803#endif
3804 wchar_t *w;
3805 wchar_t *wchar_end;
3806
3807 if (!PyUnicode_Check(unicode)) {
3808 PyErr_BadArgument();
3809 return NULL;
3810 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003811 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003813 assert(_PyUnicode_KIND(unicode) != 0);
3814 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003818 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3819 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 num_surrogates = 0;
3821
3822 for (; four_bytes < ucs4_end; ++four_bytes) {
3823 if (*four_bytes > 0xFFFF)
3824 ++num_surrogates;
3825 }
3826
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003827 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3828 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3829 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830 PyErr_NoMemory();
3831 return NULL;
3832 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003833 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 w = _PyUnicode_WSTR(unicode);
3836 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3837 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003838 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3839 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003840 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003842 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3843 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 }
3845 else
3846 *w = *four_bytes;
3847
3848 if (w > wchar_end) {
3849 assert(0 && "Miscalculated string end");
3850 }
3851 }
3852 *w = 0;
3853#else
3854 /* sizeof(wchar_t) == 4 */
3855 Py_FatalError("Impossible unicode object state, wstr and str "
3856 "should share memory already.");
3857 return NULL;
3858#endif
3859 }
3860 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003861 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3862 (_PyUnicode_LENGTH(unicode) + 1));
3863 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003864 PyErr_NoMemory();
3865 return NULL;
3866 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003867 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3868 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3869 w = _PyUnicode_WSTR(unicode);
3870 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003872 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3873 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 for (; w < wchar_end; ++one_byte, ++w)
3875 *w = *one_byte;
3876 /* null-terminate the wstr */
3877 *w = 0;
3878 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003879 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003882 for (; w < wchar_end; ++two_bytes, ++w)
3883 *w = *two_bytes;
3884 /* null-terminate the wstr */
3885 *w = 0;
3886#else
3887 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 PyObject_FREE(_PyUnicode_WSTR(unicode));
3889 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 Py_FatalError("Impossible unicode object state, wstr "
3891 "and str should share memory already.");
3892 return NULL;
3893#endif
3894 }
3895 else {
3896 assert(0 && "This should never happen.");
3897 }
3898 }
3899 }
3900 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003901 *size = PyUnicode_WSTR_LENGTH(unicode);
3902 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003903}
3904
Alexander Belopolsky40018472011-02-26 01:02:56 +00003905Py_UNICODE *
3906PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003909}
3910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911
Alexander Belopolsky40018472011-02-26 01:02:56 +00003912Py_ssize_t
3913PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003914{
3915 if (!PyUnicode_Check(unicode)) {
3916 PyErr_BadArgument();
3917 goto onError;
3918 }
3919 return PyUnicode_GET_SIZE(unicode);
3920
Benjamin Peterson29060642009-01-31 22:14:21 +00003921 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003922 return -1;
3923}
3924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003925Py_ssize_t
3926PyUnicode_GetLength(PyObject *unicode)
3927{
Victor Stinner07621332012-06-16 04:53:46 +02003928 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003929 PyErr_BadArgument();
3930 return -1;
3931 }
Victor Stinner07621332012-06-16 04:53:46 +02003932 if (PyUnicode_READY(unicode) == -1)
3933 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934 return PyUnicode_GET_LENGTH(unicode);
3935}
3936
3937Py_UCS4
3938PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3939{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003940 void *data;
3941 int kind;
3942
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003943 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3944 PyErr_BadArgument();
3945 return (Py_UCS4)-1;
3946 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003947 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003948 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949 return (Py_UCS4)-1;
3950 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003951 data = PyUnicode_DATA(unicode);
3952 kind = PyUnicode_KIND(unicode);
3953 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954}
3955
3956int
3957PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3958{
3959 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003960 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 return -1;
3962 }
Victor Stinner488fa492011-12-12 00:01:39 +01003963 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003964 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003965 PyErr_SetString(PyExc_IndexError, "string index out of range");
3966 return -1;
3967 }
Victor Stinner488fa492011-12-12 00:01:39 +01003968 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003969 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003970 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3971 PyErr_SetString(PyExc_ValueError, "character out of range");
3972 return -1;
3973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3975 index, ch);
3976 return 0;
3977}
3978
Alexander Belopolsky40018472011-02-26 01:02:56 +00003979const char *
3980PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003981{
Victor Stinner42cb4622010-09-01 19:39:01 +00003982 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003983}
3984
Victor Stinner554f3f02010-06-16 23:33:54 +00003985/* create or adjust a UnicodeDecodeError */
3986static void
3987make_decode_exception(PyObject **exceptionObject,
3988 const char *encoding,
3989 const char *input, Py_ssize_t length,
3990 Py_ssize_t startpos, Py_ssize_t endpos,
3991 const char *reason)
3992{
3993 if (*exceptionObject == NULL) {
3994 *exceptionObject = PyUnicodeDecodeError_Create(
3995 encoding, input, length, startpos, endpos, reason);
3996 }
3997 else {
3998 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3999 goto onError;
4000 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4001 goto onError;
4002 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4003 goto onError;
4004 }
4005 return;
4006
4007onError:
4008 Py_DECREF(*exceptionObject);
4009 *exceptionObject = NULL;
4010}
4011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013/* error handling callback helper:
4014 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004015 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 and adjust various state variables.
4017 return 0 on success, -1 on error
4018*/
4019
Alexander Belopolsky40018472011-02-26 01:02:56 +00004020static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004021unicode_decode_call_errorhandler_wchar(
4022 const char *errors, PyObject **errorHandler,
4023 const char *encoding, const char *reason,
4024 const char **input, const char **inend, Py_ssize_t *startinpos,
4025 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4026 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004028 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029
4030 PyObject *restuple = NULL;
4031 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004032 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004033 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004034 Py_ssize_t requiredsize;
4035 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004036 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004037 wchar_t *repwstr;
4038 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004040 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4041 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004042
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004043 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 *errorHandler = PyCodec_LookupError(errors);
4045 if (*errorHandler == NULL)
4046 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004047 }
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049 make_decode_exception(exceptionObject,
4050 encoding,
4051 *input, *inend - *input,
4052 *startinpos, *endinpos,
4053 reason);
4054 if (*exceptionObject == NULL)
4055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056
4057 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4058 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004061 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004062 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 }
4064 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004066
4067 /* Copy back the bytes variables, which might have been modified by the
4068 callback */
4069 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4070 if (!inputobj)
4071 goto onError;
4072 if (!PyBytes_Check(inputobj)) {
4073 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4074 }
4075 *input = PyBytes_AS_STRING(inputobj);
4076 insize = PyBytes_GET_SIZE(inputobj);
4077 *inend = *input + insize;
4078 /* we can DECREF safely, as the exception has another reference,
4079 so the object won't go away. */
4080 Py_DECREF(inputobj);
4081
4082 if (newpos<0)
4083 newpos = insize+newpos;
4084 if (newpos<0 || newpos>insize) {
4085 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4086 goto onError;
4087 }
4088
4089 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4090 if (repwstr == NULL)
4091 goto onError;
4092 /* need more space? (at least enough for what we
4093 have+the replacement+the rest of the string (starting
4094 at the new input position), so we won't have to check space
4095 when there are no errors in the rest of the string) */
4096 requiredsize = *outpos + repwlen + insize-newpos;
4097 if (requiredsize > outsize) {
4098 if (requiredsize < 2*outsize)
4099 requiredsize = 2*outsize;
4100 if (unicode_resize(output, requiredsize) < 0)
4101 goto onError;
4102 }
4103 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4104 *outpos += repwlen;
4105
4106 *endinpos = newpos;
4107 *inptr = *input + newpos;
4108
4109 /* we made it! */
4110 Py_XDECREF(restuple);
4111 return 0;
4112
4113 onError:
4114 Py_XDECREF(restuple);
4115 return -1;
4116}
4117#endif /* HAVE_MBCS */
4118
4119static int
4120unicode_decode_call_errorhandler_writer(
4121 const char *errors, PyObject **errorHandler,
4122 const char *encoding, const char *reason,
4123 const char **input, const char **inend, Py_ssize_t *startinpos,
4124 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4125 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4126{
4127 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4128
4129 PyObject *restuple = NULL;
4130 PyObject *repunicode = NULL;
4131 Py_ssize_t insize;
4132 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004133 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004134 PyObject *inputobj = NULL;
4135
4136 if (*errorHandler == NULL) {
4137 *errorHandler = PyCodec_LookupError(errors);
4138 if (*errorHandler == NULL)
4139 goto onError;
4140 }
4141
4142 make_decode_exception(exceptionObject,
4143 encoding,
4144 *input, *inend - *input,
4145 *startinpos, *endinpos,
4146 reason);
4147 if (*exceptionObject == NULL)
4148 goto onError;
4149
4150 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4151 if (restuple == NULL)
4152 goto onError;
4153 if (!PyTuple_Check(restuple)) {
4154 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4155 goto onError;
4156 }
4157 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004158 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
4160 /* Copy back the bytes variables, which might have been modified by the
4161 callback */
4162 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4163 if (!inputobj)
4164 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004165 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004168 *input = PyBytes_AS_STRING(inputobj);
4169 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004170 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004171 /* we can DECREF safely, as the exception has another reference,
4172 so the object won't go away. */
4173 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004174
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004177 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4179 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004180 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181
Victor Stinner8f674cc2013-04-17 23:02:17 +02004182 if (PyUnicode_READY(repunicode) < 0)
4183 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004184 replen = PyUnicode_GET_LENGTH(repunicode);
4185 writer->min_length += replen;
4186 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004187 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004189 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004191 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004192 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004193
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004195 Py_XDECREF(restuple);
4196 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004200 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201}
4202
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004203/* --- UTF-7 Codec -------------------------------------------------------- */
4204
Antoine Pitrou244651a2009-05-04 18:56:13 +00004205/* See RFC2152 for details. We encode conservatively and decode liberally. */
4206
4207/* Three simple macros defining base-64. */
4208
4209/* Is c a base-64 character? */
4210
4211#define IS_BASE64(c) \
4212 (((c) >= 'A' && (c) <= 'Z') || \
4213 ((c) >= 'a' && (c) <= 'z') || \
4214 ((c) >= '0' && (c) <= '9') || \
4215 (c) == '+' || (c) == '/')
4216
4217/* given that c is a base-64 character, what is its base-64 value? */
4218
4219#define FROM_BASE64(c) \
4220 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4221 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4222 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4223 (c) == '+' ? 62 : 63)
4224
4225/* What is the base-64 character of the bottom 6 bits of n? */
4226
4227#define TO_BASE64(n) \
4228 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4229
4230/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4231 * decoded as itself. We are permissive on decoding; the only ASCII
4232 * byte not decoding to itself is the + which begins a base64
4233 * string. */
4234
4235#define DECODE_DIRECT(c) \
4236 ((c) <= 127 && (c) != '+')
4237
4238/* The UTF-7 encoder treats ASCII characters differently according to
4239 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4240 * the above). See RFC2152. This array identifies these different
4241 * sets:
4242 * 0 : "Set D"
4243 * alphanumeric and '(),-./:?
4244 * 1 : "Set O"
4245 * !"#$%&*;<=>@[]^_`{|}
4246 * 2 : "whitespace"
4247 * ht nl cr sp
4248 * 3 : special (must be base64 encoded)
4249 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4250 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251
Tim Petersced69f82003-09-16 20:30:58 +00004252static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253char utf7_category[128] = {
4254/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4255 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4256/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4257 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4258/* sp ! " # $ % & ' ( ) * + , - . / */
4259 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4260/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4261 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4262/* @ A B C D E F G H I J K L M N O */
4263 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4264/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4266/* ` a b c d e f g h i j k l m n o */
4267 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4268/* p q r s t u v w x y z { | } ~ del */
4269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004270};
4271
Antoine Pitrou244651a2009-05-04 18:56:13 +00004272/* ENCODE_DIRECT: this character should be encoded as itself. The
4273 * answer depends on whether we are encoding set O as itself, and also
4274 * on whether we are encoding whitespace as itself. RFC2152 makes it
4275 * clear that the answers to these questions vary between
4276 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004277
Antoine Pitrou244651a2009-05-04 18:56:13 +00004278#define ENCODE_DIRECT(c, directO, directWS) \
4279 ((c) < 128 && (c) > 0 && \
4280 ((utf7_category[(c)] == 0) || \
4281 (directWS && (utf7_category[(c)] == 2)) || \
4282 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283
Alexander Belopolsky40018472011-02-26 01:02:56 +00004284PyObject *
4285PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004286 Py_ssize_t size,
4287 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4290}
4291
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292/* The decoder. The only state we preserve is our read position,
4293 * i.e. how many characters we have consumed. So if we end in the
4294 * middle of a shift sequence we have to back off the read position
4295 * and the output to the beginning of the sequence, otherwise we lose
4296 * all the shift state (seen bits, number of bits seen, high
4297 * surrogate). */
4298
Alexander Belopolsky40018472011-02-26 01:02:56 +00004299PyObject *
4300PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004301 Py_ssize_t size,
4302 const char *errors,
4303 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004304{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004305 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t startinpos;
4307 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *errmsg = "";
4311 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004312 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313 unsigned int base64bits = 0;
4314 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004315 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 PyObject *errorHandler = NULL;
4317 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004319 if (size == 0) {
4320 if (consumed)
4321 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004322 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004323 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004326 _PyUnicodeWriter_Init(&writer);
4327 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328
4329 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 e = s + size;
4331
4332 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004335 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 if (inShift) { /* in a base-64 section */
4338 if (IS_BASE64(ch)) { /* consume a base-64 character */
4339 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4340 base64bits += 6;
4341 s++;
4342 if (base64bits >= 16) {
4343 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004344 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 base64bits -= 16;
4346 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004347 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 if (surrogate) {
4349 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004350 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4351 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004352 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004355 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 }
4357 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004358 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 }
4362 }
Victor Stinner551ac952011-11-29 22:58:13 +01004363 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 /* first surrogate */
4365 surrogate = outCh;
4366 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004368 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 }
4372 }
4373 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 inShift = 0;
4375 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004377 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004379 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (base64bits > 0) { /* left-over bits */
4382 if (base64bits >= 6) {
4383 /* We've seen at least one base-64 character */
4384 errmsg = "partial character in shift sequence";
4385 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004387 else {
4388 /* Some bits remain; they should be zero */
4389 if (base64buffer != 0) {
4390 errmsg = "non-zero padding bits in shift sequence";
4391 goto utf7Error;
4392 }
4393 }
4394 }
4395 if (ch != '-') {
4396 /* '-' is absorbed; other terminating
4397 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004398 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
4402 }
4403 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004404 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 s++; /* consume '+' */
4406 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004408 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 }
4411 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004413 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004415 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004419 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004420 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004448 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004452 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004462 writer.pos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004463 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 }
4465 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004468 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004469
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004470 Py_XDECREF(errorHandler);
4471 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004472 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004473
Benjamin Peterson29060642009-01-31 22:14:21 +00004474 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004475 Py_XDECREF(errorHandler);
4476 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004477 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478 return NULL;
4479}
4480
4481
Alexander Belopolsky40018472011-02-26 01:02:56 +00004482PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004483_PyUnicode_EncodeUTF7(PyObject *str,
4484 int base64SetO,
4485 int base64WhiteSpace,
4486 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004487{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004488 int kind;
4489 void *data;
4490 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004491 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004493 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004494 unsigned int base64bits = 0;
4495 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496 char * out;
4497 char * start;
4498
Benjamin Petersonbac79492012-01-14 13:34:47 -05004499 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004500 return NULL;
4501 kind = PyUnicode_KIND(str);
4502 data = PyUnicode_DATA(str);
4503 len = PyUnicode_GET_LENGTH(str);
4504
4505 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004506 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004507
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004508 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004509 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004510 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004511 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512 if (v == NULL)
4513 return NULL;
4514
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004515 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004517 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518
Antoine Pitrou244651a2009-05-04 18:56:13 +00004519 if (inShift) {
4520 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4521 /* shifting out */
4522 if (base64bits) { /* output remaining bits */
4523 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4524 base64buffer = 0;
4525 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526 }
4527 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004528 /* Characters not in the BASE64 set implicitly unshift the sequence
4529 so no '-' is required, except if the character is itself a '-' */
4530 if (IS_BASE64(ch) || ch == '-') {
4531 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533 *out++ = (char) ch;
4534 }
4535 else {
4536 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004537 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 else { /* not in a shift sequence */
4540 if (ch == '+') {
4541 *out++ = '+';
4542 *out++ = '-';
4543 }
4544 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4545 *out++ = (char) ch;
4546 }
4547 else {
4548 *out++ = '+';
4549 inShift = 1;
4550 goto encode_char;
4551 }
4552 }
4553 continue;
4554encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004555 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004556 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004557
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558 /* code first surrogate */
4559 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004560 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 while (base64bits >= 6) {
4562 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4563 base64bits -= 6;
4564 }
4565 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004566 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 base64bits += 16;
4569 base64buffer = (base64buffer << 16) | ch;
4570 while (base64bits >= 6) {
4571 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4572 base64bits -= 6;
4573 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004574 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 if (base64bits)
4576 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4577 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004578 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004579 if (_PyBytes_Resize(&v, out - start) < 0)
4580 return NULL;
4581 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004582}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004583PyObject *
4584PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4585 Py_ssize_t size,
4586 int base64SetO,
4587 int base64WhiteSpace,
4588 const char *errors)
4589{
4590 PyObject *result;
4591 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4592 if (tmp == NULL)
4593 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004594 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004595 base64WhiteSpace, errors);
4596 Py_DECREF(tmp);
4597 return result;
4598}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004599
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600#undef IS_BASE64
4601#undef FROM_BASE64
4602#undef TO_BASE64
4603#undef DECODE_DIRECT
4604#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605
Guido van Rossumd57fd912000-03-10 22:53:23 +00004606/* --- UTF-8 Codec -------------------------------------------------------- */
4607
Alexander Belopolsky40018472011-02-26 01:02:56 +00004608PyObject *
4609PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004610 Py_ssize_t size,
4611 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612{
Walter Dörwald69652032004-09-07 20:24:22 +00004613 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4614}
4615
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004616#include "stringlib/asciilib.h"
4617#include "stringlib/codecs.h"
4618#include "stringlib/undef.h"
4619
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004620#include "stringlib/ucs1lib.h"
4621#include "stringlib/codecs.h"
4622#include "stringlib/undef.h"
4623
4624#include "stringlib/ucs2lib.h"
4625#include "stringlib/codecs.h"
4626#include "stringlib/undef.h"
4627
4628#include "stringlib/ucs4lib.h"
4629#include "stringlib/codecs.h"
4630#include "stringlib/undef.h"
4631
Antoine Pitrouab868312009-01-10 15:40:25 +00004632/* Mask to quickly check whether a C 'long' contains a
4633 non-ASCII, UTF8-encoded char. */
4634#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004635# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004636#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004637# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004638#else
4639# error C 'long' size should be either 4 or 8!
4640#endif
4641
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004642static Py_ssize_t
4643ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004644{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004645 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004646 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004647
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004648 /*
4649 * Issue #17237: m68k is a bit different from most architectures in
4650 * that objects do not use "natural alignment" - for example, int and
4651 * long are only aligned at 2-byte boundaries. Therefore the assert()
4652 * won't work; also, tests have shown that skipping the "optimised
4653 * version" will even speed up m68k.
4654 */
4655#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004656#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004657 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4658 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004659 /* Fast path, see in STRINGLIB(utf8_decode) for
4660 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004661 /* Help allocation */
4662 const char *_p = p;
4663 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664 while (_p < aligned_end) {
4665 unsigned long value = *(const unsigned long *) _p;
4666 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004667 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004668 *((unsigned long *)q) = value;
4669 _p += SIZEOF_LONG;
4670 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004671 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672 p = _p;
4673 while (p < end) {
4674 if ((unsigned char)*p & 0x80)
4675 break;
4676 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004677 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004679 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004681#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682 while (p < end) {
4683 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4684 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004685 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004686 /* Help allocation */
4687 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 while (_p < aligned_end) {
4689 unsigned long value = *(unsigned long *) _p;
4690 if (value & ASCII_CHAR_MASK)
4691 break;
4692 _p += SIZEOF_LONG;
4693 }
4694 p = _p;
4695 if (_p == end)
4696 break;
4697 }
4698 if ((unsigned char)*p & 0x80)
4699 break;
4700 ++p;
4701 }
4702 memcpy(dest, start, p - start);
4703 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004704}
Antoine Pitrouab868312009-01-10 15:40:25 +00004705
Victor Stinner785938e2011-12-11 20:09:03 +01004706PyObject *
4707PyUnicode_DecodeUTF8Stateful(const char *s,
4708 Py_ssize_t size,
4709 const char *errors,
4710 Py_ssize_t *consumed)
4711{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004712 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004713 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004714 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004715
4716 Py_ssize_t startinpos;
4717 Py_ssize_t endinpos;
4718 const char *errmsg = "";
4719 PyObject *errorHandler = NULL;
4720 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004721
4722 if (size == 0) {
4723 if (consumed)
4724 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004725 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004726 }
4727
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004728 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4729 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004730 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 *consumed = 1;
4732 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004733 }
4734
Victor Stinner8f674cc2013-04-17 23:02:17 +02004735 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004736 writer.min_length = size;
4737 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004738 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004739
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004740 writer.pos = ascii_decode(s, end, writer.data);
4741 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004742 while (s < end) {
4743 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004744 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004746 if (PyUnicode_IS_ASCII(writer.buffer))
4747 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004749 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004751 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004752 } else {
4753 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 }
4756
4757 switch (ch) {
4758 case 0:
4759 if (s == end || consumed)
4760 goto End;
4761 errmsg = "unexpected end of data";
4762 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004763 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 break;
4765 case 1:
4766 errmsg = "invalid start byte";
4767 startinpos = s - starts;
4768 endinpos = startinpos + 1;
4769 break;
4770 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004771 case 3:
4772 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004773 errmsg = "invalid continuation byte";
4774 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004775 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004776 break;
4777 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004778 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004779 goto onError;
4780 continue;
4781 }
4782
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004783 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784 errors, &errorHandler,
4785 "utf-8", errmsg,
4786 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004787 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004788 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004789 }
4790
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 if (consumed)
4793 *consumed = s - starts;
4794
4795 Py_XDECREF(errorHandler);
4796 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004797 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798
4799onError:
4800 Py_XDECREF(errorHandler);
4801 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004802 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004803 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004804}
4805
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004806#ifdef __APPLE__
4807
4808/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004809 used to decode the command line arguments on Mac OS X.
4810
4811 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004812 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004813
4814wchar_t*
4815_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4816{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 wchar_t *unicode;
4819 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004820
4821 /* Note: size will always be longer than the resulting Unicode
4822 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004823 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004824 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004825 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004826 if (!unicode)
4827 return NULL;
4828
4829 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004830 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004831 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 if (ch > 0xFF) {
4840#if SIZEOF_WCHAR_T == 4
4841 assert(0);
4842#else
4843 assert(Py_UNICODE_IS_SURROGATE(ch));
4844 /* compute and append the two surrogates: */
4845 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4846 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4847#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 else {
4850 if (!ch && s == e)
4851 break;
4852 /* surrogateescape */
4853 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4854 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004855 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004857 return unicode;
4858}
4859
4860#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004862/* Primary internal function which creates utf8 encoded bytes objects.
4863
4864 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004865 and allocate exactly as much space needed at the end. Else allocate the
4866 maximum possible needed (4 result bytes per Unicode character), and return
4867 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004868*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004869PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004870_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871{
Victor Stinner6099a032011-12-18 14:22:26 +01004872 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004873 void *data;
4874 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004876 if (!PyUnicode_Check(unicode)) {
4877 PyErr_BadArgument();
4878 return NULL;
4879 }
4880
4881 if (PyUnicode_READY(unicode) == -1)
4882 return NULL;
4883
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004884 if (PyUnicode_UTF8(unicode))
4885 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4886 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004887
4888 kind = PyUnicode_KIND(unicode);
4889 data = PyUnicode_DATA(unicode);
4890 size = PyUnicode_GET_LENGTH(unicode);
4891
Benjamin Petersonead6b532011-12-20 17:23:42 -06004892 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004893 default:
4894 assert(0);
4895 case PyUnicode_1BYTE_KIND:
4896 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4897 assert(!PyUnicode_IS_ASCII(unicode));
4898 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4899 case PyUnicode_2BYTE_KIND:
4900 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4901 case PyUnicode_4BYTE_KIND:
4902 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004903 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904}
4905
Alexander Belopolsky40018472011-02-26 01:02:56 +00004906PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004907PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4908 Py_ssize_t size,
4909 const char *errors)
4910{
4911 PyObject *v, *unicode;
4912
4913 unicode = PyUnicode_FromUnicode(s, size);
4914 if (unicode == NULL)
4915 return NULL;
4916 v = _PyUnicode_AsUTF8String(unicode, errors);
4917 Py_DECREF(unicode);
4918 return v;
4919}
4920
4921PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004922PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004923{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004924 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004925}
4926
Walter Dörwald41980ca2007-08-16 21:55:45 +00004927/* --- UTF-32 Codec ------------------------------------------------------- */
4928
4929PyObject *
4930PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004931 Py_ssize_t size,
4932 const char *errors,
4933 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004934{
4935 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4936}
4937
4938PyObject *
4939PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004940 Py_ssize_t size,
4941 const char *errors,
4942 int *byteorder,
4943 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004944{
4945 const char *starts = s;
4946 Py_ssize_t startinpos;
4947 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004948 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004949 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004950 int le, bo = 0; /* assume native ordering by default */
Walter Dörwald41980ca2007-08-16 21:55:45 +00004951 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004952 PyObject *errorHandler = NULL;
4953 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004954
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955 q = (unsigned char *)s;
4956 e = q + size;
4957
4958 if (byteorder)
4959 bo = *byteorder;
4960
4961 /* Check for BOM marks (U+FEFF) in the input and adjust current
4962 byte order setting accordingly. In native mode, the leading BOM
4963 mark is skipped, in all other modes, it is copied to the output
4964 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004965 if (bo == 0 && size >= 4) {
4966 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4967 if (bom == 0x0000FEFF) {
4968 bo = -1;
4969 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004970 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004971 else if (bom == 0xFFFE0000) {
4972 bo = 1;
4973 q += 4;
4974 }
4975 if (byteorder)
4976 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 }
4978
Victor Stinnere64322e2012-10-30 23:12:47 +01004979 if (q == e) {
4980 if (consumed)
4981 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004982 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004983 }
4984
Victor Stinnere64322e2012-10-30 23:12:47 +01004985#ifdef WORDS_BIGENDIAN
4986 le = bo < 0;
4987#else
4988 le = bo <= 0;
4989#endif
4990
Victor Stinner8f674cc2013-04-17 23:02:17 +02004991 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004992 writer.min_length = (e - q + 3) / 4;
4993 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004994 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004995
Victor Stinnere64322e2012-10-30 23:12:47 +01004996 while (1) {
4997 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004998 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004999
Victor Stinnere64322e2012-10-30 23:12:47 +01005000 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005001 enum PyUnicode_Kind kind = writer.kind;
5002 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005003 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005004 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005005 if (le) {
5006 do {
5007 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5008 if (ch > maxch)
5009 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005010 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005011 q += 4;
5012 } while (q <= last);
5013 }
5014 else {
5015 do {
5016 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5017 if (ch > maxch)
5018 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005019 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005020 q += 4;
5021 } while (q <= last);
5022 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005023 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 }
5025
5026 if (ch <= maxch) {
5027 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005028 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005029 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005030 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005031 startinpos = ((const char *)q) - starts;
5032 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005034 else {
5035 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005036 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005037 goto onError;
5038 q += 4;
5039 continue;
5040 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005042 startinpos = ((const char *)q) - starts;
5043 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005044 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005045
5046 /* The remaining input chars are ignored if the callback
5047 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005048 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 errors, &errorHandler,
5050 "utf32", errmsg,
5051 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005052 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005053 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054 }
5055
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005058
Walter Dörwald41980ca2007-08-16 21:55:45 +00005059 Py_XDECREF(errorHandler);
5060 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005061 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005064 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005065 Py_XDECREF(errorHandler);
5066 Py_XDECREF(exc);
5067 return NULL;
5068}
5069
5070PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005071_PyUnicode_EncodeUTF32(PyObject *str,
5072 const char *errors,
5073 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005074{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005075 int kind;
5076 void *data;
5077 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005078 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005080 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005082#if PY_LITTLE_ENDIAN
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 int iorder[] = {0, 1, 2, 3};
5084#else
5085 int iorder[] = {3, 2, 1, 0};
5086#endif
5087
Benjamin Peterson29060642009-01-31 22:14:21 +00005088#define STORECHAR(CH) \
5089 do { \
5090 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5091 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5092 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5093 p[iorder[0]] = (CH) & 0xff; \
5094 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095 } while(0)
5096
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005097 if (!PyUnicode_Check(str)) {
5098 PyErr_BadArgument();
5099 return NULL;
5100 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005101 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005102 return NULL;
5103 kind = PyUnicode_KIND(str);
5104 data = PyUnicode_DATA(str);
5105 len = PyUnicode_GET_LENGTH(str);
5106
5107 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005108 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005109 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005110 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005111 if (v == NULL)
5112 return NULL;
5113
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005114 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005116 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005117 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005118 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005119
5120 if (byteorder == -1) {
5121 /* force LE */
5122 iorder[0] = 0;
5123 iorder[1] = 1;
5124 iorder[2] = 2;
5125 iorder[3] = 3;
5126 }
5127 else if (byteorder == 1) {
5128 /* force BE */
5129 iorder[0] = 3;
5130 iorder[1] = 2;
5131 iorder[2] = 1;
5132 iorder[3] = 0;
5133 }
5134
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005135 for (i = 0; i < len; i++)
5136 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005137
5138 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005139 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005140#undef STORECHAR
5141}
5142
Alexander Belopolsky40018472011-02-26 01:02:56 +00005143PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005144PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5145 Py_ssize_t size,
5146 const char *errors,
5147 int byteorder)
5148{
5149 PyObject *result;
5150 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5151 if (tmp == NULL)
5152 return NULL;
5153 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5154 Py_DECREF(tmp);
5155 return result;
5156}
5157
5158PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005159PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005160{
Victor Stinnerb960b342011-11-20 19:12:52 +01005161 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005162}
5163
Guido van Rossumd57fd912000-03-10 22:53:23 +00005164/* --- UTF-16 Codec ------------------------------------------------------- */
5165
Tim Peters772747b2001-08-09 22:21:55 +00005166PyObject *
5167PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005168 Py_ssize_t size,
5169 const char *errors,
5170 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005171{
Walter Dörwald69652032004-09-07 20:24:22 +00005172 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5173}
5174
5175PyObject *
5176PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005177 Py_ssize_t size,
5178 const char *errors,
5179 int *byteorder,
5180 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005181{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005182 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005183 Py_ssize_t startinpos;
5184 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005185 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005186 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005187 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005188 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005189 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005190 PyObject *errorHandler = NULL;
5191 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005192
Tim Peters772747b2001-08-09 22:21:55 +00005193 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005194 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005195
5196 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005197 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005199 /* Check for BOM marks (U+FEFF) in the input and adjust current
5200 byte order setting accordingly. In native mode, the leading BOM
5201 mark is skipped, in all other modes, it is copied to the output
5202 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005203 if (bo == 0 && size >= 2) {
5204 const Py_UCS4 bom = (q[1] << 8) | q[0];
5205 if (bom == 0xFEFF) {
5206 q += 2;
5207 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005208 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005209 else if (bom == 0xFFFE) {
5210 q += 2;
5211 bo = 1;
5212 }
5213 if (byteorder)
5214 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005215 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005216
Antoine Pitrou63065d72012-05-15 23:48:04 +02005217 if (q == e) {
5218 if (consumed)
5219 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005220 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005221 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005222
Christian Heimes743e0cd2012-10-17 23:52:17 +02005223#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005224 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005225#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005226 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005227#endif
Tim Peters772747b2001-08-09 22:21:55 +00005228
Antoine Pitrou63065d72012-05-15 23:48:04 +02005229 /* Note: size will always be longer than the resulting Unicode
5230 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005231 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005232 writer.min_length = (e - q + 1) / 2;
5233 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005234 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005235
Antoine Pitrou63065d72012-05-15 23:48:04 +02005236 while (1) {
5237 Py_UCS4 ch = 0;
5238 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005239 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005240 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005241 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005242 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005243 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005244 native_ordering);
5245 else
5246 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005247 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005248 native_ordering);
5249 } else if (kind == PyUnicode_2BYTE_KIND) {
5250 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005251 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005252 native_ordering);
5253 } else {
5254 assert(kind == PyUnicode_4BYTE_KIND);
5255 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005256 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005257 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005258 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005259 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005260
Antoine Pitrou63065d72012-05-15 23:48:04 +02005261 switch (ch)
5262 {
5263 case 0:
5264 /* remaining byte at the end? (size should be even) */
5265 if (q == e || consumed)
5266 goto End;
5267 errmsg = "truncated data";
5268 startinpos = ((const char *)q) - starts;
5269 endinpos = ((const char *)e) - starts;
5270 break;
5271 /* The remaining input chars are ignored if the callback
5272 chooses to skip the input */
5273 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005274 q -= 2;
5275 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005276 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005277 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005278 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005279 endinpos = ((const char *)e) - starts;
5280 break;
5281 case 2:
5282 errmsg = "illegal encoding";
5283 startinpos = ((const char *)q) - 2 - starts;
5284 endinpos = startinpos + 2;
5285 break;
5286 case 3:
5287 errmsg = "illegal UTF-16 surrogate";
5288 startinpos = ((const char *)q) - 4 - starts;
5289 endinpos = startinpos + 2;
5290 break;
5291 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005292 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005293 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005294 continue;
5295 }
5296
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005297 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005298 errors,
5299 &errorHandler,
5300 "utf16", errmsg,
5301 &starts,
5302 (const char **)&e,
5303 &startinpos,
5304 &endinpos,
5305 &exc,
5306 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005307 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005308 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005309 }
5310
Antoine Pitrou63065d72012-05-15 23:48:04 +02005311End:
Walter Dörwald69652032004-09-07 20:24:22 +00005312 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005313 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005314
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005315 Py_XDECREF(errorHandler);
5316 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005317 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005318
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005320 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005321 Py_XDECREF(errorHandler);
5322 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005323 return NULL;
5324}
5325
Tim Peters772747b2001-08-09 22:21:55 +00005326PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005327_PyUnicode_EncodeUTF16(PyObject *str,
5328 const char *errors,
5329 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005330{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005331 enum PyUnicode_Kind kind;
5332 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005333 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005334 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005335 unsigned short *out;
5336 Py_ssize_t bytesize;
5337 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005338#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005339 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005340#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005341 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005342#endif
5343
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005344 if (!PyUnicode_Check(str)) {
5345 PyErr_BadArgument();
5346 return NULL;
5347 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005348 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005349 return NULL;
5350 kind = PyUnicode_KIND(str);
5351 data = PyUnicode_DATA(str);
5352 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005353
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005354 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005355 if (kind == PyUnicode_4BYTE_KIND) {
5356 const Py_UCS4 *in = (const Py_UCS4 *)data;
5357 const Py_UCS4 *end = in + len;
5358 while (in < end)
5359 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005360 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005361 }
5362 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005364 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005365 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005366 if (v == NULL)
5367 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005368
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005369 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005370 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005371 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005372 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005373 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005374 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005375 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005376
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005377 switch (kind) {
5378 case PyUnicode_1BYTE_KIND: {
5379 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5380 break;
Tim Peters772747b2001-08-09 22:21:55 +00005381 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005382 case PyUnicode_2BYTE_KIND: {
5383 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5384 break;
Tim Peters772747b2001-08-09 22:21:55 +00005385 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005386 case PyUnicode_4BYTE_KIND: {
5387 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5388 break;
5389 }
5390 default:
5391 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005392 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005393
5394 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005395 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005396}
5397
Alexander Belopolsky40018472011-02-26 01:02:56 +00005398PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005399PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5400 Py_ssize_t size,
5401 const char *errors,
5402 int byteorder)
5403{
5404 PyObject *result;
5405 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5406 if (tmp == NULL)
5407 return NULL;
5408 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5409 Py_DECREF(tmp);
5410 return result;
5411}
5412
5413PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005414PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005416 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417}
5418
5419/* --- Unicode Escape Codec ----------------------------------------------- */
5420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005421/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5422 if all the escapes in the string make it still a valid ASCII string.
5423 Returns -1 if any escapes were found which cause the string to
5424 pop out of ASCII range. Otherwise returns the length of the
5425 required buffer to hold the string.
5426 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005427static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005428length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5429{
5430 const unsigned char *p = (const unsigned char *)s;
5431 const unsigned char *end = p + size;
5432 Py_ssize_t length = 0;
5433
5434 if (size < 0)
5435 return -1;
5436
5437 for (; p < end; ++p) {
5438 if (*p > 127) {
5439 /* Non-ASCII */
5440 return -1;
5441 }
5442 else if (*p != '\\') {
5443 /* Normal character */
5444 ++length;
5445 }
5446 else {
5447 /* Backslash-escape, check next char */
5448 ++p;
5449 /* Escape sequence reaches till end of string or
5450 non-ASCII follow-up. */
5451 if (p >= end || *p > 127)
5452 return -1;
5453 switch (*p) {
5454 case '\n':
5455 /* backslash + \n result in zero characters */
5456 break;
5457 case '\\': case '\'': case '\"':
5458 case 'b': case 'f': case 't':
5459 case 'n': case 'r': case 'v': case 'a':
5460 ++length;
5461 break;
5462 case '0': case '1': case '2': case '3':
5463 case '4': case '5': case '6': case '7':
5464 case 'x': case 'u': case 'U': case 'N':
5465 /* these do not guarantee ASCII characters */
5466 return -1;
5467 default:
5468 /* count the backslash + the other character */
5469 length += 2;
5470 }
5471 }
5472 }
5473 return length;
5474}
5475
Fredrik Lundh06d12682001-01-24 07:59:11 +00005476static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005477
Alexander Belopolsky40018472011-02-26 01:02:56 +00005478PyObject *
5479PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005480 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005481 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005482{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005483 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005484 Py_ssize_t startinpos;
5485 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005486 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005487 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005488 char* message;
5489 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005490 PyObject *errorHandler = NULL;
5491 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005492 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005493
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005494 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005495 if (len == 0)
5496 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005497
5498 /* After length_of_escaped_ascii_string() there are two alternatives,
5499 either the string is pure ASCII with named escapes like \n, etc.
5500 and we determined it's exact size (common case)
5501 or it contains \x, \u, ... escape sequences. then we create a
5502 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005503 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005504 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005505 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005506 }
5507 else {
5508 /* Escaped strings will always be longer than the resulting
5509 Unicode string, so we start with size here and then reduce the
5510 length after conversion to the true value.
5511 (but if the error callback returns a long replacement string
5512 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005513 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005514 }
5515
Guido van Rossumd57fd912000-03-10 22:53:23 +00005516 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005517 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005518 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005519
Guido van Rossumd57fd912000-03-10 22:53:23 +00005520 while (s < end) {
5521 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005522 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005523 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524
5525 /* Non-escape characters are interpreted as Unicode ordinals */
5526 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005527 x = (unsigned char)*s;
5528 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005529 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005530 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531 continue;
5532 }
5533
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005534 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005535 /* \ - Escapes */
5536 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005537 c = *s++;
5538 if (s > end)
5539 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005540
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005541 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005542
Benjamin Peterson29060642009-01-31 22:14:21 +00005543 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005544#define WRITECHAR(ch) \
5545 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005546 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005547 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005548 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005549
Guido van Rossumd57fd912000-03-10 22:53:23 +00005550 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005551 case '\\': WRITECHAR('\\'); break;
5552 case '\'': WRITECHAR('\''); break;
5553 case '\"': WRITECHAR('\"'); break;
5554 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005555 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005556 case 'f': WRITECHAR('\014'); break;
5557 case 't': WRITECHAR('\t'); break;
5558 case 'n': WRITECHAR('\n'); break;
5559 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005560 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005561 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005562 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005563 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564
Benjamin Peterson29060642009-01-31 22:14:21 +00005565 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566 case '0': case '1': case '2': case '3':
5567 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005568 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005569 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005570 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005571 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005572 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005573 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005574 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005575 break;
5576
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 /* hex escapes */
5578 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005579 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005580 digits = 2;
5581 message = "truncated \\xXX escape";
5582 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005585 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005586 digits = 4;
5587 message = "truncated \\uXXXX escape";
5588 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005589
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005591 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005592 digits = 8;
5593 message = "truncated \\UXXXXXXXX escape";
5594 hexescape:
5595 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005596 if (end - s < digits) {
5597 /* count only hex digits */
5598 for (; s < end; ++s) {
5599 c = (unsigned char)*s;
5600 if (!Py_ISXDIGIT(c))
5601 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005602 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005603 goto error;
5604 }
5605 for (; digits--; ++s) {
5606 c = (unsigned char)*s;
5607 if (!Py_ISXDIGIT(c))
5608 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005609 chr = (chr<<4) & ~0xF;
5610 if (c >= '0' && c <= '9')
5611 chr += c - '0';
5612 else if (c >= 'a' && c <= 'f')
5613 chr += 10 + c - 'a';
5614 else
5615 chr += 10 + c - 'A';
5616 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005617 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005618 /* _decoding_error will have already written into the
5619 target buffer. */
5620 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005621 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005622 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005623 message = "illegal Unicode character";
5624 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005625 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005626 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005627 break;
5628
Benjamin Peterson29060642009-01-31 22:14:21 +00005629 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005630 case 'N':
5631 message = "malformed \\N character escape";
5632 if (ucnhash_CAPI == NULL) {
5633 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005634 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5635 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005636 if (ucnhash_CAPI == NULL)
5637 goto ucnhashError;
5638 }
5639 if (*s == '{') {
5640 const char *start = s+1;
5641 /* look for the closing brace */
5642 while (*s != '}' && s < end)
5643 s++;
5644 if (s > start && s < end && *s == '}') {
5645 /* found a name. look it up in the unicode database */
5646 message = "unknown Unicode character name";
5647 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005648 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005649 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005650 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005651 goto store;
5652 }
5653 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005654 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005655
5656 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005657 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005658 message = "\\ at end of string";
5659 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005660 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005661 }
5662 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005663 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005664 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005665 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005666 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005668 continue;
5669
5670 error:
5671 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005672 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005673 errors, &errorHandler,
5674 "unicodeescape", message,
5675 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005676 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005677 goto onError;
5678 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005680#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005681
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005682 Py_XDECREF(errorHandler);
5683 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005684 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005685
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005687 PyErr_SetString(
5688 PyExc_UnicodeError,
5689 "\\N escapes not supported (can't load unicodedata module)"
5690 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 Py_XDECREF(errorHandler);
5693 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005694 return NULL;
5695
Benjamin Peterson29060642009-01-31 22:14:21 +00005696 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005697 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005698 Py_XDECREF(errorHandler);
5699 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 return NULL;
5701}
5702
5703/* Return a Unicode-Escape string version of the Unicode object.
5704
5705 If quotes is true, the string is enclosed in u"" or u'' quotes as
5706 appropriate.
5707
5708*/
5709
Alexander Belopolsky40018472011-02-26 01:02:56 +00005710PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005711PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005712{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005713 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005714 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005715 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005716 int kind;
5717 void *data;
5718 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719
Ezio Melottie7f90372012-10-05 03:33:31 +03005720 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005721 escape.
5722
Ezio Melottie7f90372012-10-05 03:33:31 +03005723 For UCS1 strings it's '\xxx', 4 bytes per source character.
5724 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5725 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005726 */
5727
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005728 if (!PyUnicode_Check(unicode)) {
5729 PyErr_BadArgument();
5730 return NULL;
5731 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005732 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005733 return NULL;
5734 len = PyUnicode_GET_LENGTH(unicode);
5735 kind = PyUnicode_KIND(unicode);
5736 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005737 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005738 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5739 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5740 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5741 }
5742
5743 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005744 return PyBytes_FromStringAndSize(NULL, 0);
5745
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005746 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005748
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005749 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005750 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005751 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 if (repr == NULL)
5754 return NULL;
5755
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005756 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005758 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005759 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005760
Walter Dörwald79e913e2007-05-12 11:08:06 +00005761 /* Escape backslashes */
5762 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763 *p++ = '\\';
5764 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005765 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005766 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005767
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005768 /* Map 21-bit characters to '\U00xxxxxx' */
5769 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005770 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005771 *p++ = '\\';
5772 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005773 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5774 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5775 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5776 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5777 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5778 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5779 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5780 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005781 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005782 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005783
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005785 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786 *p++ = '\\';
5787 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005788 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5789 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5790 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5791 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005793
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005794 /* Map special whitespace to '\t', \n', '\r' */
5795 else if (ch == '\t') {
5796 *p++ = '\\';
5797 *p++ = 't';
5798 }
5799 else if (ch == '\n') {
5800 *p++ = '\\';
5801 *p++ = 'n';
5802 }
5803 else if (ch == '\r') {
5804 *p++ = '\\';
5805 *p++ = 'r';
5806 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005807
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005808 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005809 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005810 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005811 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005812 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5813 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005814 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005815
Guido van Rossumd57fd912000-03-10 22:53:23 +00005816 /* Copy everything else as-is */
5817 else
5818 *p++ = (char) ch;
5819 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005820
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005821 assert(p - PyBytes_AS_STRING(repr) > 0);
5822 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5823 return NULL;
5824 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005825}
5826
Alexander Belopolsky40018472011-02-26 01:02:56 +00005827PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005828PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5829 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005830{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005831 PyObject *result;
5832 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5833 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005834 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005835 result = PyUnicode_AsUnicodeEscapeString(tmp);
5836 Py_DECREF(tmp);
5837 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838}
5839
5840/* --- Raw Unicode Escape Codec ------------------------------------------- */
5841
Alexander Belopolsky40018472011-02-26 01:02:56 +00005842PyObject *
5843PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005844 Py_ssize_t size,
5845 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005847 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005848 Py_ssize_t startinpos;
5849 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005850 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 const char *end;
5852 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853 PyObject *errorHandler = NULL;
5854 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005855
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005856 if (size == 0)
5857 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005858
Guido van Rossumd57fd912000-03-10 22:53:23 +00005859 /* Escaped strings will always be longer than the resulting
5860 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005861 length after conversion to the true value. (But decoding error
5862 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005863 _PyUnicodeWriter_Init(&writer);
5864 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005865
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 end = s + size;
5867 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005868 unsigned char c;
5869 Py_UCS4 x;
5870 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005871 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872
Benjamin Peterson29060642009-01-31 22:14:21 +00005873 /* Non-escape characters are interpreted as Unicode ordinals */
5874 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005875 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005876 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005877 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005878 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005879 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005880 startinpos = s-starts;
5881
5882 /* \u-escapes are only interpreted iff the number of leading
5883 backslashes if odd */
5884 bs = s;
5885 for (;s < end;) {
5886 if (*s != '\\')
5887 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005888 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005889 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005890 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 }
5892 if (((s - bs) & 1) == 0 ||
5893 s >= end ||
5894 (*s != 'u' && *s != 'U')) {
5895 continue;
5896 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005897 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005898 count = *s=='u' ? 4 : 8;
5899 s++;
5900
5901 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005902 for (x = 0, i = 0; i < count; ++i, ++s) {
5903 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005904 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005906 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005907 errors, &errorHandler,
5908 "rawunicodeescape", "truncated \\uXXXX",
5909 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005910 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 goto onError;
5912 goto nextByte;
5913 }
5914 x = (x<<4) & ~0xF;
5915 if (c >= '0' && c <= '9')
5916 x += c - '0';
5917 else if (c >= 'a' && c <= 'f')
5918 x += 10 + c - 'a';
5919 else
5920 x += 10 + c - 'A';
5921 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005922 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005923 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005924 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005925 }
5926 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00005927 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005928 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005929 errors, &errorHandler,
5930 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005931 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005932 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005933 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005934 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 nextByte:
5936 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005938 Py_XDECREF(errorHandler);
5939 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005940 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00005941
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005943 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005944 Py_XDECREF(errorHandler);
5945 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946 return NULL;
5947}
5948
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005949
Alexander Belopolsky40018472011-02-26 01:02:56 +00005950PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005953 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 char *p;
5955 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005956 Py_ssize_t expandsize, pos;
5957 int kind;
5958 void *data;
5959 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005961 if (!PyUnicode_Check(unicode)) {
5962 PyErr_BadArgument();
5963 return NULL;
5964 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005965 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005966 return NULL;
5967 kind = PyUnicode_KIND(unicode);
5968 data = PyUnicode_DATA(unicode);
5969 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06005970 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
5971 bytes, and 1 byte characters 4. */
5972 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01005973
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005974 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005976
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005977 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 if (repr == NULL)
5979 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005980 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005981 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005983 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005984 for (pos = 0; pos < len; pos++) {
5985 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 /* Map 32-bit characters to '\Uxxxxxxxx' */
5987 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005988 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005989 *p++ = '\\';
5990 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005991 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
5992 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
5993 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
5994 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
5995 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5996 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5997 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5998 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005999 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006000 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006001 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006002 *p++ = '\\';
6003 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006004 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6005 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6006 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6007 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 /* Copy everything else as-is */
6010 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011 *p++ = (char) ch;
6012 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006013
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006014 assert(p > q);
6015 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006016 return NULL;
6017 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006018}
6019
Alexander Belopolsky40018472011-02-26 01:02:56 +00006020PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006021PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6022 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006024 PyObject *result;
6025 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6026 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006027 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006028 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6029 Py_DECREF(tmp);
6030 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031}
6032
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006033/* --- Unicode Internal Codec ------------------------------------------- */
6034
Alexander Belopolsky40018472011-02-26 01:02:56 +00006035PyObject *
6036_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006037 Py_ssize_t size,
6038 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006039{
6040 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006041 Py_ssize_t startinpos;
6042 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006043 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006044 const char *end;
6045 const char *reason;
6046 PyObject *errorHandler = NULL;
6047 PyObject *exc = NULL;
6048
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006049 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006050 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006051 1))
6052 return NULL;
6053
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006054 if (size == 0)
6055 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006056
Victor Stinner8f674cc2013-04-17 23:02:17 +02006057 _PyUnicodeWriter_Init(&writer);
6058 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6059 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006061 }
6062 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006063
Victor Stinner8f674cc2013-04-17 23:02:17 +02006064 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006065 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006066 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006067 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006068 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006069 endinpos = end-starts;
6070 reason = "truncated input";
6071 goto error;
6072 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006073 /* We copy the raw representation one byte at a time because the
6074 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006075 ((char *) &uch)[0] = s[0];
6076 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006077#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006078 ((char *) &uch)[2] = s[2];
6079 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006080#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006081 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006082#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006083 /* We have to sanity check the raw data, otherwise doom looms for
6084 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006085 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006086 endinpos = s - starts + Py_UNICODE_SIZE;
6087 reason = "illegal code point (> 0x10FFFF)";
6088 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006089 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006090#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006091 s += Py_UNICODE_SIZE;
6092#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006093 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006094 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006095 Py_UNICODE uch2;
6096 ((char *) &uch2)[0] = s[0];
6097 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006098 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006099 {
Victor Stinner551ac952011-11-29 22:58:13 +01006100 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006101 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006102 }
6103 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006104#endif
6105
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006106 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006107 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006108 continue;
6109
6110 error:
6111 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006112 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006113 errors, &errorHandler,
6114 "unicode_internal", reason,
6115 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006116 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006117 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006118 }
6119
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006120 Py_XDECREF(errorHandler);
6121 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006122 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006123
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006125 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006126 Py_XDECREF(errorHandler);
6127 Py_XDECREF(exc);
6128 return NULL;
6129}
6130
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131/* --- Latin-1 Codec ------------------------------------------------------ */
6132
Alexander Belopolsky40018472011-02-26 01:02:56 +00006133PyObject *
6134PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006135 Py_ssize_t size,
6136 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006139 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006140}
6141
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006142/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006143static void
6144make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006145 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006146 PyObject *unicode,
6147 Py_ssize_t startpos, Py_ssize_t endpos,
6148 const char *reason)
6149{
6150 if (*exceptionObject == NULL) {
6151 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006152 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006153 encoding, unicode, startpos, endpos, reason);
6154 }
6155 else {
6156 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6157 goto onError;
6158 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6159 goto onError;
6160 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6161 goto onError;
6162 return;
6163 onError:
6164 Py_DECREF(*exceptionObject);
6165 *exceptionObject = NULL;
6166 }
6167}
6168
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006169/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006170static void
6171raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006172 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006173 PyObject *unicode,
6174 Py_ssize_t startpos, Py_ssize_t endpos,
6175 const char *reason)
6176{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006177 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006178 encoding, unicode, startpos, endpos, reason);
6179 if (*exceptionObject != NULL)
6180 PyCodec_StrictErrors(*exceptionObject);
6181}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006182
6183/* error handling callback helper:
6184 build arguments, call the callback and check the arguments,
6185 put the result into newpos and return the replacement string, which
6186 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006187static PyObject *
6188unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006189 PyObject **errorHandler,
6190 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006191 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006192 Py_ssize_t startpos, Py_ssize_t endpos,
6193 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006194{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006195 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006196 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006197 PyObject *restuple;
6198 PyObject *resunicode;
6199
6200 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006202 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006203 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006204 }
6205
Benjamin Petersonbac79492012-01-14 13:34:47 -05006206 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006207 return NULL;
6208 len = PyUnicode_GET_LENGTH(unicode);
6209
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006210 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006211 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006213 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006214
6215 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006216 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006217 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006218 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006219 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006220 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006221 Py_DECREF(restuple);
6222 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006223 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006224 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006225 &resunicode, newpos)) {
6226 Py_DECREF(restuple);
6227 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006228 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006229 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6230 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6231 Py_DECREF(restuple);
6232 return NULL;
6233 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006234 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006235 *newpos = len + *newpos;
6236 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6238 Py_DECREF(restuple);
6239 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006240 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006241 Py_INCREF(resunicode);
6242 Py_DECREF(restuple);
6243 return resunicode;
6244}
6245
Alexander Belopolsky40018472011-02-26 01:02:56 +00006246static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006247unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006248 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006249 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006250{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006251 /* input state */
6252 Py_ssize_t pos=0, size;
6253 int kind;
6254 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006255 /* output object */
6256 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006257 /* pointer into the output */
6258 char *str;
6259 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006260 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006261 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6262 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006263 PyObject *errorHandler = NULL;
6264 PyObject *exc = NULL;
6265 /* the following variable is used for caching string comparisons
6266 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6267 int known_errorHandler = -1;
6268
Benjamin Petersonbac79492012-01-14 13:34:47 -05006269 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006270 return NULL;
6271 size = PyUnicode_GET_LENGTH(unicode);
6272 kind = PyUnicode_KIND(unicode);
6273 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006274 /* allocate enough for a simple encoding without
6275 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006276 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006277 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006278 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006279 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006280 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006281 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006282 ressize = size;
6283
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006284 while (pos < size) {
6285 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006286
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 /* can we encode this? */
6288 if (c<limit) {
6289 /* no overflow check, because we know that the space is enough */
6290 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006291 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006292 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006293 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 Py_ssize_t requiredsize;
6295 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006296 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006298 Py_ssize_t collstart = pos;
6299 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006301 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 ++collend;
6303 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6304 if (known_errorHandler==-1) {
6305 if ((errors==NULL) || (!strcmp(errors, "strict")))
6306 known_errorHandler = 1;
6307 else if (!strcmp(errors, "replace"))
6308 known_errorHandler = 2;
6309 else if (!strcmp(errors, "ignore"))
6310 known_errorHandler = 3;
6311 else if (!strcmp(errors, "xmlcharrefreplace"))
6312 known_errorHandler = 4;
6313 else
6314 known_errorHandler = 0;
6315 }
6316 switch (known_errorHandler) {
6317 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006318 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 goto onError;
6320 case 2: /* replace */
6321 while (collstart++<collend)
6322 *str++ = '?'; /* fall through */
6323 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006324 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 break;
6326 case 4: /* xmlcharrefreplace */
6327 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006328 /* determine replacement size */
6329 for (i = collstart, repsize = 0; i < collend; ++i) {
6330 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6331 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006332 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006333 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006334 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006335 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006336 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006337 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006338 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006339 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006341 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006343 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006344 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006345 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006346 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006347 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006348 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006349 if (requiredsize > ressize) {
6350 if (requiredsize<2*ressize)
6351 requiredsize = 2*ressize;
6352 if (_PyBytes_Resize(&res, requiredsize))
6353 goto onError;
6354 str = PyBytes_AS_STRING(res) + respos;
6355 ressize = requiredsize;
6356 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 /* generate replacement */
6358 for (i = collstart; i < collend; ++i) {
6359 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 break;
6363 default:
6364 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006365 encoding, reason, unicode, &exc,
6366 collstart, collend, &newpos);
6367 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006368 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006369 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006370 if (PyBytes_Check(repunicode)) {
6371 /* Directly copy bytes result to output. */
6372 repsize = PyBytes_Size(repunicode);
6373 if (repsize > 1) {
6374 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006375 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006376 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6377 Py_DECREF(repunicode);
6378 goto onError;
6379 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006380 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006381 ressize += repsize-1;
6382 }
6383 memcpy(str, PyBytes_AsString(repunicode), repsize);
6384 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006385 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006386 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006387 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006388 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006389 /* need more space? (at least enough for what we
6390 have+the replacement+the rest of the string, so
6391 we won't have to check space for encodable characters) */
6392 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006393 repsize = PyUnicode_GET_LENGTH(repunicode);
6394 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 if (requiredsize > ressize) {
6396 if (requiredsize<2*ressize)
6397 requiredsize = 2*ressize;
6398 if (_PyBytes_Resize(&res, requiredsize)) {
6399 Py_DECREF(repunicode);
6400 goto onError;
6401 }
6402 str = PyBytes_AS_STRING(res) + respos;
6403 ressize = requiredsize;
6404 }
6405 /* check if there is anything unencodable in the replacement
6406 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006407 for (i = 0; repsize-->0; ++i, ++str) {
6408 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006410 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 Py_DECREF(repunicode);
6413 goto onError;
6414 }
6415 *str = (char)c;
6416 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006417 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006418 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006419 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006420 }
6421 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006422 /* Resize if we allocated to much */
6423 size = str - PyBytes_AS_STRING(res);
6424 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006425 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006426 if (_PyBytes_Resize(&res, size) < 0)
6427 goto onError;
6428 }
6429
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 Py_XDECREF(errorHandler);
6431 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006432 return res;
6433
6434 onError:
6435 Py_XDECREF(res);
6436 Py_XDECREF(errorHandler);
6437 Py_XDECREF(exc);
6438 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006439}
6440
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006441/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006442PyObject *
6443PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006444 Py_ssize_t size,
6445 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006447 PyObject *result;
6448 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6449 if (unicode == NULL)
6450 return NULL;
6451 result = unicode_encode_ucs1(unicode, errors, 256);
6452 Py_DECREF(unicode);
6453 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006454}
6455
Alexander Belopolsky40018472011-02-26 01:02:56 +00006456PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006457_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006458{
6459 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006460 PyErr_BadArgument();
6461 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006463 if (PyUnicode_READY(unicode) == -1)
6464 return NULL;
6465 /* Fast path: if it is a one-byte string, construct
6466 bytes object directly. */
6467 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6468 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6469 PyUnicode_GET_LENGTH(unicode));
6470 /* Non-Latin-1 characters present. Defer to above function to
6471 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006473}
6474
6475PyObject*
6476PyUnicode_AsLatin1String(PyObject *unicode)
6477{
6478 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006479}
6480
6481/* --- 7-bit ASCII Codec -------------------------------------------------- */
6482
Alexander Belopolsky40018472011-02-26 01:02:56 +00006483PyObject *
6484PyUnicode_DecodeASCII(const char *s,
6485 Py_ssize_t size,
6486 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006487{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006488 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006489 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006490 int kind;
6491 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006492 Py_ssize_t startinpos;
6493 Py_ssize_t endinpos;
6494 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006495 const char *e;
6496 PyObject *errorHandler = NULL;
6497 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006498
Guido van Rossumd57fd912000-03-10 22:53:23 +00006499 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006500 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006501
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006503 if (size == 1 && (unsigned char)s[0] < 128)
6504 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006505
Victor Stinner8f674cc2013-04-17 23:02:17 +02006506 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006507 writer.min_length = size;
6508 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006509 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006510
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006511 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006512 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006513 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006514 writer.pos = outpos;
6515 if (writer.pos == size)
6516 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006517
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006518 s += writer.pos;
6519 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006520 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006521 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006523 PyUnicode_WRITE(kind, data, writer.pos, c);
6524 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006525 ++s;
6526 }
6527 else {
6528 startinpos = s-starts;
6529 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006530 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 errors, &errorHandler,
6532 "ascii", "ordinal not in range(128)",
6533 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006534 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006536 kind = writer.kind;
6537 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006539 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006540 Py_XDECREF(errorHandler);
6541 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006542 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006543
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006545 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006546 Py_XDECREF(errorHandler);
6547 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548 return NULL;
6549}
6550
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006551/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006552PyObject *
6553PyUnicode_EncodeASCII(const Py_UNICODE *p,
6554 Py_ssize_t size,
6555 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006557 PyObject *result;
6558 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6559 if (unicode == NULL)
6560 return NULL;
6561 result = unicode_encode_ucs1(unicode, errors, 128);
6562 Py_DECREF(unicode);
6563 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006564}
6565
Alexander Belopolsky40018472011-02-26 01:02:56 +00006566PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006567_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006568{
6569 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 PyErr_BadArgument();
6571 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006573 if (PyUnicode_READY(unicode) == -1)
6574 return NULL;
6575 /* Fast path: if it is an ASCII-only string, construct bytes object
6576 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006577 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006578 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6579 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006581}
6582
6583PyObject *
6584PyUnicode_AsASCIIString(PyObject *unicode)
6585{
6586 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006587}
6588
Victor Stinner99b95382011-07-04 14:23:54 +02006589#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006590
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006591/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006592
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006593#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006594#define NEED_RETRY
6595#endif
6596
Victor Stinner3a50e702011-10-18 21:21:00 +02006597#ifndef WC_ERR_INVALID_CHARS
6598# define WC_ERR_INVALID_CHARS 0x0080
6599#endif
6600
6601static char*
6602code_page_name(UINT code_page, PyObject **obj)
6603{
6604 *obj = NULL;
6605 if (code_page == CP_ACP)
6606 return "mbcs";
6607 if (code_page == CP_UTF7)
6608 return "CP_UTF7";
6609 if (code_page == CP_UTF8)
6610 return "CP_UTF8";
6611
6612 *obj = PyBytes_FromFormat("cp%u", code_page);
6613 if (*obj == NULL)
6614 return NULL;
6615 return PyBytes_AS_STRING(*obj);
6616}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006617
Alexander Belopolsky40018472011-02-26 01:02:56 +00006618static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006619is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006620{
6621 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006622 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006623
Victor Stinner3a50e702011-10-18 21:21:00 +02006624 if (!IsDBCSLeadByteEx(code_page, *curr))
6625 return 0;
6626
6627 prev = CharPrevExA(code_page, s, curr, 0);
6628 if (prev == curr)
6629 return 1;
6630 /* FIXME: This code is limited to "true" double-byte encodings,
6631 as it assumes an incomplete character consists of a single
6632 byte. */
6633 if (curr - prev == 2)
6634 return 1;
6635 if (!IsDBCSLeadByteEx(code_page, *prev))
6636 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006637 return 0;
6638}
6639
Victor Stinner3a50e702011-10-18 21:21:00 +02006640static DWORD
6641decode_code_page_flags(UINT code_page)
6642{
6643 if (code_page == CP_UTF7) {
6644 /* The CP_UTF7 decoder only supports flags=0 */
6645 return 0;
6646 }
6647 else
6648 return MB_ERR_INVALID_CHARS;
6649}
6650
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006651/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006652 * Decode a byte string from a Windows code page into unicode object in strict
6653 * mode.
6654 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006655 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6656 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006657 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006658static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006659decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006660 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006661 const char *in,
6662 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006663{
Victor Stinner3a50e702011-10-18 21:21:00 +02006664 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006665 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006666 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006667
6668 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006669 assert(insize > 0);
6670 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6671 if (outsize <= 0)
6672 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006673
6674 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006676 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006677 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 if (*v == NULL)
6679 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006680 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006681 }
6682 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006684 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006685 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006686 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006687 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006688 }
6689
6690 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006691 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6692 if (outsize <= 0)
6693 goto error;
6694 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006695
Victor Stinner3a50e702011-10-18 21:21:00 +02006696error:
6697 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6698 return -2;
6699 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006700 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006701}
6702
Victor Stinner3a50e702011-10-18 21:21:00 +02006703/*
6704 * Decode a byte string from a code page into unicode object with an error
6705 * handler.
6706 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006707 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006708 * UnicodeDecodeError exception and returns -1 on error.
6709 */
6710static int
6711decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006712 PyObject **v,
6713 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006714 const char *errors)
6715{
6716 const char *startin = in;
6717 const char *endin = in + size;
6718 const DWORD flags = decode_code_page_flags(code_page);
6719 /* Ideally, we should get reason from FormatMessage. This is the Windows
6720 2000 English version of the message. */
6721 const char *reason = "No mapping for the Unicode character exists "
6722 "in the target code page.";
6723 /* each step cannot decode more than 1 character, but a character can be
6724 represented as a surrogate pair */
6725 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006726 int insize;
6727 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006728 PyObject *errorHandler = NULL;
6729 PyObject *exc = NULL;
6730 PyObject *encoding_obj = NULL;
6731 char *encoding;
6732 DWORD err;
6733 int ret = -1;
6734
6735 assert(size > 0);
6736
6737 encoding = code_page_name(code_page, &encoding_obj);
6738 if (encoding == NULL)
6739 return -1;
6740
6741 if (errors == NULL || strcmp(errors, "strict") == 0) {
6742 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6743 UnicodeDecodeError. */
6744 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6745 if (exc != NULL) {
6746 PyCodec_StrictErrors(exc);
6747 Py_CLEAR(exc);
6748 }
6749 goto error;
6750 }
6751
6752 if (*v == NULL) {
6753 /* Create unicode object */
6754 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6755 PyErr_NoMemory();
6756 goto error;
6757 }
Victor Stinnerab595942011-12-17 04:59:06 +01006758 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006759 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006760 if (*v == NULL)
6761 goto error;
6762 startout = PyUnicode_AS_UNICODE(*v);
6763 }
6764 else {
6765 /* Extend unicode object */
6766 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6767 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6768 PyErr_NoMemory();
6769 goto error;
6770 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006771 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006772 goto error;
6773 startout = PyUnicode_AS_UNICODE(*v) + n;
6774 }
6775
6776 /* Decode the byte string character per character */
6777 out = startout;
6778 while (in < endin)
6779 {
6780 /* Decode a character */
6781 insize = 1;
6782 do
6783 {
6784 outsize = MultiByteToWideChar(code_page, flags,
6785 in, insize,
6786 buffer, Py_ARRAY_LENGTH(buffer));
6787 if (outsize > 0)
6788 break;
6789 err = GetLastError();
6790 if (err != ERROR_NO_UNICODE_TRANSLATION
6791 && err != ERROR_INSUFFICIENT_BUFFER)
6792 {
6793 PyErr_SetFromWindowsErr(0);
6794 goto error;
6795 }
6796 insize++;
6797 }
6798 /* 4=maximum length of a UTF-8 sequence */
6799 while (insize <= 4 && (in + insize) <= endin);
6800
6801 if (outsize <= 0) {
6802 Py_ssize_t startinpos, endinpos, outpos;
6803
6804 startinpos = in - startin;
6805 endinpos = startinpos + 1;
6806 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006807 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006808 errors, &errorHandler,
6809 encoding, reason,
6810 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006811 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006812 {
6813 goto error;
6814 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006815 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006816 }
6817 else {
6818 in += insize;
6819 memcpy(out, buffer, outsize * sizeof(wchar_t));
6820 out += outsize;
6821 }
6822 }
6823
6824 /* write a NUL character at the end */
6825 *out = 0;
6826
6827 /* Extend unicode object */
6828 outsize = out - startout;
6829 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006830 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006831 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006832 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006833
6834error:
6835 Py_XDECREF(encoding_obj);
6836 Py_XDECREF(errorHandler);
6837 Py_XDECREF(exc);
6838 return ret;
6839}
6840
Victor Stinner3a50e702011-10-18 21:21:00 +02006841static PyObject *
6842decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006843 const char *s, Py_ssize_t size,
6844 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006845{
Victor Stinner76a31a62011-11-04 00:05:13 +01006846 PyObject *v = NULL;
6847 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006848
Victor Stinner3a50e702011-10-18 21:21:00 +02006849 if (code_page < 0) {
6850 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6851 return NULL;
6852 }
6853
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006854 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006855 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006856
Victor Stinner76a31a62011-11-04 00:05:13 +01006857 do
6858 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006859#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006860 if (size > INT_MAX) {
6861 chunk_size = INT_MAX;
6862 final = 0;
6863 done = 0;
6864 }
6865 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006866#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006867 {
6868 chunk_size = (int)size;
6869 final = (consumed == NULL);
6870 done = 1;
6871 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006872
Victor Stinner76a31a62011-11-04 00:05:13 +01006873 /* Skip trailing lead-byte unless 'final' is set */
6874 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6875 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006876
Victor Stinner76a31a62011-11-04 00:05:13 +01006877 if (chunk_size == 0 && done) {
6878 if (v != NULL)
6879 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006880 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006881 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006882
Victor Stinner76a31a62011-11-04 00:05:13 +01006883
6884 converted = decode_code_page_strict(code_page, &v,
6885 s, chunk_size);
6886 if (converted == -2)
6887 converted = decode_code_page_errors(code_page, &v,
6888 s, chunk_size,
6889 errors);
6890 assert(converted != 0);
6891
6892 if (converted < 0) {
6893 Py_XDECREF(v);
6894 return NULL;
6895 }
6896
6897 if (consumed)
6898 *consumed += converted;
6899
6900 s += converted;
6901 size -= converted;
6902 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006903
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006904 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006905}
6906
Alexander Belopolsky40018472011-02-26 01:02:56 +00006907PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006908PyUnicode_DecodeCodePageStateful(int code_page,
6909 const char *s,
6910 Py_ssize_t size,
6911 const char *errors,
6912 Py_ssize_t *consumed)
6913{
6914 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6915}
6916
6917PyObject *
6918PyUnicode_DecodeMBCSStateful(const char *s,
6919 Py_ssize_t size,
6920 const char *errors,
6921 Py_ssize_t *consumed)
6922{
6923 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6924}
6925
6926PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006927PyUnicode_DecodeMBCS(const char *s,
6928 Py_ssize_t size,
6929 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006930{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006931 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6932}
6933
Victor Stinner3a50e702011-10-18 21:21:00 +02006934static DWORD
6935encode_code_page_flags(UINT code_page, const char *errors)
6936{
6937 if (code_page == CP_UTF8) {
6938 if (winver.dwMajorVersion >= 6)
6939 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6940 and later */
6941 return WC_ERR_INVALID_CHARS;
6942 else
6943 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
6944 return 0;
6945 }
6946 else if (code_page == CP_UTF7) {
6947 /* CP_UTF7 only supports flags=0 */
6948 return 0;
6949 }
6950 else {
6951 if (errors != NULL && strcmp(errors, "replace") == 0)
6952 return 0;
6953 else
6954 return WC_NO_BEST_FIT_CHARS;
6955 }
6956}
6957
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006958/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006959 * Encode a Unicode string to a Windows code page into a byte string in strict
6960 * mode.
6961 *
6962 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006963 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006964 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006965static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006966encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01006967 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02006968 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006969{
Victor Stinner554f3f02010-06-16 23:33:54 +00006970 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 BOOL *pusedDefaultChar = &usedDefaultChar;
6972 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006973 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01006974 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006975 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006976 const DWORD flags = encode_code_page_flags(code_page, NULL);
6977 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006978 /* Create a substring so that we can get the UTF-16 representation
6979 of just the slice under consideration. */
6980 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006981
Martin v. Löwis3d325192011-11-04 18:23:06 +01006982 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006983
Victor Stinner3a50e702011-10-18 21:21:00 +02006984 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00006985 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02006986 else
Victor Stinner554f3f02010-06-16 23:33:54 +00006987 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00006988
Victor Stinner2fc507f2011-11-04 20:06:39 +01006989 substring = PyUnicode_Substring(unicode, offset, offset+len);
6990 if (substring == NULL)
6991 return -1;
6992 p = PyUnicode_AsUnicodeAndSize(substring, &size);
6993 if (p == NULL) {
6994 Py_DECREF(substring);
6995 return -1;
6996 }
Victor Stinner9f067f42013-06-05 00:21:31 +02006997 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01006998
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006999 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007000 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007001 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007002 NULL, 0,
7003 NULL, pusedDefaultChar);
7004 if (outsize <= 0)
7005 goto error;
7006 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007007 if (pusedDefaultChar && *pusedDefaultChar) {
7008 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007009 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007010 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007011
Victor Stinner3a50e702011-10-18 21:21:00 +02007012 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007014 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007015 if (*outbytes == NULL) {
7016 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007017 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007018 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007019 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020 }
7021 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007023 const Py_ssize_t n = PyBytes_Size(*outbytes);
7024 if (outsize > PY_SSIZE_T_MAX - n) {
7025 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007026 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007027 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007029 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7030 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007031 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007032 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034 }
7035
7036 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007037 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007038 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 out, outsize,
7040 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007041 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007042 if (outsize <= 0)
7043 goto error;
7044 if (pusedDefaultChar && *pusedDefaultChar)
7045 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007049 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007050 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7051 return -2;
7052 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007053 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007054}
7055
Victor Stinner3a50e702011-10-18 21:21:00 +02007056/*
7057 * Encode a Unicode string to a Windows code page into a byte string using a
7058 * error handler.
7059 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007060 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007061 * -1 on other error.
7062 */
7063static int
7064encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007065 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007066 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007067{
Victor Stinner3a50e702011-10-18 21:21:00 +02007068 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007069 Py_ssize_t pos = unicode_offset;
7070 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007071 /* Ideally, we should get reason from FormatMessage. This is the Windows
7072 2000 English version of the message. */
7073 const char *reason = "invalid character";
7074 /* 4=maximum length of a UTF-8 sequence */
7075 char buffer[4];
7076 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7077 Py_ssize_t outsize;
7078 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007079 PyObject *errorHandler = NULL;
7080 PyObject *exc = NULL;
7081 PyObject *encoding_obj = NULL;
7082 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007083 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 PyObject *rep;
7085 int ret = -1;
7086
7087 assert(insize > 0);
7088
7089 encoding = code_page_name(code_page, &encoding_obj);
7090 if (encoding == NULL)
7091 return -1;
7092
7093 if (errors == NULL || strcmp(errors, "strict") == 0) {
7094 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7095 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007096 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 if (exc != NULL) {
7098 PyCodec_StrictErrors(exc);
7099 Py_DECREF(exc);
7100 }
7101 Py_XDECREF(encoding_obj);
7102 return -1;
7103 }
7104
7105 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7106 pusedDefaultChar = &usedDefaultChar;
7107 else
7108 pusedDefaultChar = NULL;
7109
7110 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7111 PyErr_NoMemory();
7112 goto error;
7113 }
7114 outsize = insize * Py_ARRAY_LENGTH(buffer);
7115
7116 if (*outbytes == NULL) {
7117 /* Create string object */
7118 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7119 if (*outbytes == NULL)
7120 goto error;
7121 out = PyBytes_AS_STRING(*outbytes);
7122 }
7123 else {
7124 /* Extend string object */
7125 Py_ssize_t n = PyBytes_Size(*outbytes);
7126 if (n > PY_SSIZE_T_MAX - outsize) {
7127 PyErr_NoMemory();
7128 goto error;
7129 }
7130 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7131 goto error;
7132 out = PyBytes_AS_STRING(*outbytes) + n;
7133 }
7134
7135 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007136 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007137 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007138 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7139 wchar_t chars[2];
7140 int charsize;
7141 if (ch < 0x10000) {
7142 chars[0] = (wchar_t)ch;
7143 charsize = 1;
7144 }
7145 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007146 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7147 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007148 charsize = 2;
7149 }
7150
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007152 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007153 buffer, Py_ARRAY_LENGTH(buffer),
7154 NULL, pusedDefaultChar);
7155 if (outsize > 0) {
7156 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7157 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007158 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 memcpy(out, buffer, outsize);
7160 out += outsize;
7161 continue;
7162 }
7163 }
7164 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7165 PyErr_SetFromWindowsErr(0);
7166 goto error;
7167 }
7168
Victor Stinner3a50e702011-10-18 21:21:00 +02007169 rep = unicode_encode_call_errorhandler(
7170 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007171 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007172 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 if (rep == NULL)
7174 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007175 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007176
7177 if (PyBytes_Check(rep)) {
7178 outsize = PyBytes_GET_SIZE(rep);
7179 if (outsize != 1) {
7180 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7181 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7182 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7183 Py_DECREF(rep);
7184 goto error;
7185 }
7186 out = PyBytes_AS_STRING(*outbytes) + offset;
7187 }
7188 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7189 out += outsize;
7190 }
7191 else {
7192 Py_ssize_t i;
7193 enum PyUnicode_Kind kind;
7194 void *data;
7195
Benjamin Petersonbac79492012-01-14 13:34:47 -05007196 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 Py_DECREF(rep);
7198 goto error;
7199 }
7200
7201 outsize = PyUnicode_GET_LENGTH(rep);
7202 if (outsize != 1) {
7203 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7204 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7205 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7206 Py_DECREF(rep);
7207 goto error;
7208 }
7209 out = PyBytes_AS_STRING(*outbytes) + offset;
7210 }
7211 kind = PyUnicode_KIND(rep);
7212 data = PyUnicode_DATA(rep);
7213 for (i=0; i < outsize; i++) {
7214 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7215 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007216 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007217 encoding, unicode,
7218 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 "unable to encode error handler result to ASCII");
7220 Py_DECREF(rep);
7221 goto error;
7222 }
7223 *out = (unsigned char)ch;
7224 out++;
7225 }
7226 }
7227 Py_DECREF(rep);
7228 }
7229 /* write a NUL byte */
7230 *out = 0;
7231 outsize = out - PyBytes_AS_STRING(*outbytes);
7232 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7233 if (_PyBytes_Resize(outbytes, outsize) < 0)
7234 goto error;
7235 ret = 0;
7236
7237error:
7238 Py_XDECREF(encoding_obj);
7239 Py_XDECREF(errorHandler);
7240 Py_XDECREF(exc);
7241 return ret;
7242}
7243
Victor Stinner3a50e702011-10-18 21:21:00 +02007244static PyObject *
7245encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007246 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 const char *errors)
7248{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007249 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007251 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007252 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007253
Benjamin Petersonbac79492012-01-14 13:34:47 -05007254 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007255 return NULL;
7256 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007257
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 if (code_page < 0) {
7259 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7260 return NULL;
7261 }
7262
Martin v. Löwis3d325192011-11-04 18:23:06 +01007263 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007264 return PyBytes_FromStringAndSize(NULL, 0);
7265
Victor Stinner7581cef2011-11-03 22:32:33 +01007266 offset = 0;
7267 do
7268 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007269#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007270 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007271 chunks. */
7272 if (len > INT_MAX/2) {
7273 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007274 done = 0;
7275 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007276 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007279 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 done = 1;
7281 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007282
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007284 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007285 errors);
7286 if (ret == -2)
7287 ret = encode_code_page_errors(code_page, &outbytes,
7288 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007289 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007290 if (ret < 0) {
7291 Py_XDECREF(outbytes);
7292 return NULL;
7293 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007294
Victor Stinner7581cef2011-11-03 22:32:33 +01007295 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007296 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007297 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298
Victor Stinner3a50e702011-10-18 21:21:00 +02007299 return outbytes;
7300}
7301
7302PyObject *
7303PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7304 Py_ssize_t size,
7305 const char *errors)
7306{
Victor Stinner7581cef2011-11-03 22:32:33 +01007307 PyObject *unicode, *res;
7308 unicode = PyUnicode_FromUnicode(p, size);
7309 if (unicode == NULL)
7310 return NULL;
7311 res = encode_code_page(CP_ACP, unicode, errors);
7312 Py_DECREF(unicode);
7313 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007314}
7315
7316PyObject *
7317PyUnicode_EncodeCodePage(int code_page,
7318 PyObject *unicode,
7319 const char *errors)
7320{
Victor Stinner7581cef2011-11-03 22:32:33 +01007321 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007322}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007323
Alexander Belopolsky40018472011-02-26 01:02:56 +00007324PyObject *
7325PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007326{
7327 if (!PyUnicode_Check(unicode)) {
7328 PyErr_BadArgument();
7329 return NULL;
7330 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007331 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007332}
7333
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007334#undef NEED_RETRY
7335
Victor Stinner99b95382011-07-04 14:23:54 +02007336#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007337
Guido van Rossumd57fd912000-03-10 22:53:23 +00007338/* --- Character Mapping Codec -------------------------------------------- */
7339
Victor Stinnerfb161b12013-04-18 01:44:27 +02007340static int
7341charmap_decode_string(const char *s,
7342 Py_ssize_t size,
7343 PyObject *mapping,
7344 const char *errors,
7345 _PyUnicodeWriter *writer)
7346{
7347 const char *starts = s;
7348 const char *e;
7349 Py_ssize_t startinpos, endinpos;
7350 PyObject *errorHandler = NULL, *exc = NULL;
7351 Py_ssize_t maplen;
7352 enum PyUnicode_Kind mapkind;
7353 void *mapdata;
7354 Py_UCS4 x;
7355 unsigned char ch;
7356
7357 if (PyUnicode_READY(mapping) == -1)
7358 return -1;
7359
7360 maplen = PyUnicode_GET_LENGTH(mapping);
7361 mapdata = PyUnicode_DATA(mapping);
7362 mapkind = PyUnicode_KIND(mapping);
7363
7364 e = s + size;
7365
7366 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7367 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7368 * is disabled in encoding aliases, latin1 is preferred because
7369 * its implementation is faster. */
7370 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7371 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7372 Py_UCS4 maxchar = writer->maxchar;
7373
7374 assert (writer->kind == PyUnicode_1BYTE_KIND);
7375 while (s < e) {
7376 ch = *s;
7377 x = mapdata_ucs1[ch];
7378 if (x > maxchar) {
7379 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7380 goto onError;
7381 maxchar = writer->maxchar;
7382 outdata = (Py_UCS1 *)writer->data;
7383 }
7384 outdata[writer->pos] = x;
7385 writer->pos++;
7386 ++s;
7387 }
7388 return 0;
7389 }
7390
7391 while (s < e) {
7392 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7393 enum PyUnicode_Kind outkind = writer->kind;
7394 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7395 if (outkind == PyUnicode_1BYTE_KIND) {
7396 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7397 Py_UCS4 maxchar = writer->maxchar;
7398 while (s < e) {
7399 ch = *s;
7400 x = mapdata_ucs2[ch];
7401 if (x > maxchar)
7402 goto Error;
7403 outdata[writer->pos] = x;
7404 writer->pos++;
7405 ++s;
7406 }
7407 break;
7408 }
7409 else if (outkind == PyUnicode_2BYTE_KIND) {
7410 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7411 while (s < e) {
7412 ch = *s;
7413 x = mapdata_ucs2[ch];
7414 if (x == 0xFFFE)
7415 goto Error;
7416 outdata[writer->pos] = x;
7417 writer->pos++;
7418 ++s;
7419 }
7420 break;
7421 }
7422 }
7423 ch = *s;
7424
7425 if (ch < maplen)
7426 x = PyUnicode_READ(mapkind, mapdata, ch);
7427 else
7428 x = 0xfffe; /* invalid value */
7429Error:
7430 if (x == 0xfffe)
7431 {
7432 /* undefined mapping */
7433 startinpos = s-starts;
7434 endinpos = startinpos+1;
7435 if (unicode_decode_call_errorhandler_writer(
7436 errors, &errorHandler,
7437 "charmap", "character maps to <undefined>",
7438 &starts, &e, &startinpos, &endinpos, &exc, &s,
7439 writer)) {
7440 goto onError;
7441 }
7442 continue;
7443 }
7444
7445 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7446 goto onError;
7447 ++s;
7448 }
7449 Py_XDECREF(errorHandler);
7450 Py_XDECREF(exc);
7451 return 0;
7452
7453onError:
7454 Py_XDECREF(errorHandler);
7455 Py_XDECREF(exc);
7456 return -1;
7457}
7458
7459static int
7460charmap_decode_mapping(const char *s,
7461 Py_ssize_t size,
7462 PyObject *mapping,
7463 const char *errors,
7464 _PyUnicodeWriter *writer)
7465{
7466 const char *starts = s;
7467 const char *e;
7468 Py_ssize_t startinpos, endinpos;
7469 PyObject *errorHandler = NULL, *exc = NULL;
7470 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007471 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007472
7473 e = s + size;
7474
7475 while (s < e) {
7476 ch = *s;
7477
7478 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7479 key = PyLong_FromLong((long)ch);
7480 if (key == NULL)
7481 goto onError;
7482
7483 item = PyObject_GetItem(mapping, key);
7484 Py_DECREF(key);
7485 if (item == NULL) {
7486 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7487 /* No mapping found means: mapping is undefined. */
7488 PyErr_Clear();
7489 goto Undefined;
7490 } else
7491 goto onError;
7492 }
7493
7494 /* Apply mapping */
7495 if (item == Py_None)
7496 goto Undefined;
7497 if (PyLong_Check(item)) {
7498 long value = PyLong_AS_LONG(item);
7499 if (value == 0xFFFE)
7500 goto Undefined;
7501 if (value < 0 || value > MAX_UNICODE) {
7502 PyErr_Format(PyExc_TypeError,
7503 "character mapping must be in range(0x%lx)",
7504 (unsigned long)MAX_UNICODE + 1);
7505 goto onError;
7506 }
7507
7508 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7509 goto onError;
7510 }
7511 else if (PyUnicode_Check(item)) {
7512 if (PyUnicode_READY(item) == -1)
7513 goto onError;
7514 if (PyUnicode_GET_LENGTH(item) == 1) {
7515 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7516 if (value == 0xFFFE)
7517 goto Undefined;
7518 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7519 goto onError;
7520 }
7521 else {
7522 writer->overallocate = 1;
7523 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7524 goto onError;
7525 }
7526 }
7527 else {
7528 /* wrong return value */
7529 PyErr_SetString(PyExc_TypeError,
7530 "character mapping must return integer, None or str");
7531 goto onError;
7532 }
7533 Py_CLEAR(item);
7534 ++s;
7535 continue;
7536
7537Undefined:
7538 /* undefined mapping */
7539 Py_CLEAR(item);
7540 startinpos = s-starts;
7541 endinpos = startinpos+1;
7542 if (unicode_decode_call_errorhandler_writer(
7543 errors, &errorHandler,
7544 "charmap", "character maps to <undefined>",
7545 &starts, &e, &startinpos, &endinpos, &exc, &s,
7546 writer)) {
7547 goto onError;
7548 }
7549 }
7550 Py_XDECREF(errorHandler);
7551 Py_XDECREF(exc);
7552 return 0;
7553
7554onError:
7555 Py_XDECREF(item);
7556 Py_XDECREF(errorHandler);
7557 Py_XDECREF(exc);
7558 return -1;
7559}
7560
Alexander Belopolsky40018472011-02-26 01:02:56 +00007561PyObject *
7562PyUnicode_DecodeCharmap(const char *s,
7563 Py_ssize_t size,
7564 PyObject *mapping,
7565 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007567 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007568
Guido van Rossumd57fd912000-03-10 22:53:23 +00007569 /* Default to Latin-1 */
7570 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007571 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572
Guido van Rossumd57fd912000-03-10 22:53:23 +00007573 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007574 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007575 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007576 writer.min_length = size;
7577 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007578 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007579
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007580 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007581 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7582 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007583 }
7584 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007585 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7586 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007588 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007589
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007591 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007592 return NULL;
7593}
7594
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007595/* Charmap encoding: the lookup table */
7596
Alexander Belopolsky40018472011-02-26 01:02:56 +00007597struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 PyObject_HEAD
7599 unsigned char level1[32];
7600 int count2, count3;
7601 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007602};
7603
7604static PyObject*
7605encoding_map_size(PyObject *obj, PyObject* args)
7606{
7607 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007608 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007609 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007610}
7611
7612static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007613 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 PyDoc_STR("Return the size (in bytes) of this object") },
7615 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007616};
7617
7618static void
7619encoding_map_dealloc(PyObject* o)
7620{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007621 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007622}
7623
7624static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007625 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 "EncodingMap", /*tp_name*/
7627 sizeof(struct encoding_map), /*tp_basicsize*/
7628 0, /*tp_itemsize*/
7629 /* methods */
7630 encoding_map_dealloc, /*tp_dealloc*/
7631 0, /*tp_print*/
7632 0, /*tp_getattr*/
7633 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007634 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007635 0, /*tp_repr*/
7636 0, /*tp_as_number*/
7637 0, /*tp_as_sequence*/
7638 0, /*tp_as_mapping*/
7639 0, /*tp_hash*/
7640 0, /*tp_call*/
7641 0, /*tp_str*/
7642 0, /*tp_getattro*/
7643 0, /*tp_setattro*/
7644 0, /*tp_as_buffer*/
7645 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7646 0, /*tp_doc*/
7647 0, /*tp_traverse*/
7648 0, /*tp_clear*/
7649 0, /*tp_richcompare*/
7650 0, /*tp_weaklistoffset*/
7651 0, /*tp_iter*/
7652 0, /*tp_iternext*/
7653 encoding_map_methods, /*tp_methods*/
7654 0, /*tp_members*/
7655 0, /*tp_getset*/
7656 0, /*tp_base*/
7657 0, /*tp_dict*/
7658 0, /*tp_descr_get*/
7659 0, /*tp_descr_set*/
7660 0, /*tp_dictoffset*/
7661 0, /*tp_init*/
7662 0, /*tp_alloc*/
7663 0, /*tp_new*/
7664 0, /*tp_free*/
7665 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007666};
7667
7668PyObject*
7669PyUnicode_BuildEncodingMap(PyObject* string)
7670{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007671 PyObject *result;
7672 struct encoding_map *mresult;
7673 int i;
7674 int need_dict = 0;
7675 unsigned char level1[32];
7676 unsigned char level2[512];
7677 unsigned char *mlevel1, *mlevel2, *mlevel3;
7678 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007679 int kind;
7680 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007681 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007682 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007683
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007684 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007685 PyErr_BadArgument();
7686 return NULL;
7687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007688 kind = PyUnicode_KIND(string);
7689 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007690 length = PyUnicode_GET_LENGTH(string);
7691 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007692 memset(level1, 0xFF, sizeof level1);
7693 memset(level2, 0xFF, sizeof level2);
7694
7695 /* If there isn't a one-to-one mapping of NULL to \0,
7696 or if there are non-BMP characters, we need to use
7697 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007698 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007699 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007700 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007702 ch = PyUnicode_READ(kind, data, i);
7703 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007704 need_dict = 1;
7705 break;
7706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007707 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007708 /* unmapped character */
7709 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007710 l1 = ch >> 11;
7711 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007712 if (level1[l1] == 0xFF)
7713 level1[l1] = count2++;
7714 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007715 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007716 }
7717
7718 if (count2 >= 0xFF || count3 >= 0xFF)
7719 need_dict = 1;
7720
7721 if (need_dict) {
7722 PyObject *result = PyDict_New();
7723 PyObject *key, *value;
7724 if (!result)
7725 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007726 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007727 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007728 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007729 if (!key || !value)
7730 goto failed1;
7731 if (PyDict_SetItem(result, key, value) == -1)
7732 goto failed1;
7733 Py_DECREF(key);
7734 Py_DECREF(value);
7735 }
7736 return result;
7737 failed1:
7738 Py_XDECREF(key);
7739 Py_XDECREF(value);
7740 Py_DECREF(result);
7741 return NULL;
7742 }
7743
7744 /* Create a three-level trie */
7745 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7746 16*count2 + 128*count3 - 1);
7747 if (!result)
7748 return PyErr_NoMemory();
7749 PyObject_Init(result, &EncodingMapType);
7750 mresult = (struct encoding_map*)result;
7751 mresult->count2 = count2;
7752 mresult->count3 = count3;
7753 mlevel1 = mresult->level1;
7754 mlevel2 = mresult->level23;
7755 mlevel3 = mresult->level23 + 16*count2;
7756 memcpy(mlevel1, level1, 32);
7757 memset(mlevel2, 0xFF, 16*count2);
7758 memset(mlevel3, 0, 128*count3);
7759 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007760 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007761 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007762 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7763 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764 /* unmapped character */
7765 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007766 o1 = ch>>11;
7767 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768 i2 = 16*mlevel1[o1] + o2;
7769 if (mlevel2[i2] == 0xFF)
7770 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007771 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007772 i3 = 128*mlevel2[i2] + o3;
7773 mlevel3[i3] = i;
7774 }
7775 return result;
7776}
7777
7778static int
Victor Stinner22168992011-11-20 17:09:18 +01007779encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780{
7781 struct encoding_map *map = (struct encoding_map*)mapping;
7782 int l1 = c>>11;
7783 int l2 = (c>>7) & 0xF;
7784 int l3 = c & 0x7F;
7785 int i;
7786
Victor Stinner22168992011-11-20 17:09:18 +01007787 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007788 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007789 if (c == 0)
7790 return 0;
7791 /* level 1*/
7792 i = map->level1[l1];
7793 if (i == 0xFF) {
7794 return -1;
7795 }
7796 /* level 2*/
7797 i = map->level23[16*i+l2];
7798 if (i == 0xFF) {
7799 return -1;
7800 }
7801 /* level 3 */
7802 i = map->level23[16*map->count2 + 128*i + l3];
7803 if (i == 0) {
7804 return -1;
7805 }
7806 return i;
7807}
7808
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007809/* Lookup the character ch in the mapping. If the character
7810 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007811 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007812static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007813charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007814{
Christian Heimes217cfd12007-12-02 14:31:20 +00007815 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007816 PyObject *x;
7817
7818 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007820 x = PyObject_GetItem(mapping, w);
7821 Py_DECREF(w);
7822 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007823 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7824 /* No mapping found means: mapping is undefined. */
7825 PyErr_Clear();
7826 x = Py_None;
7827 Py_INCREF(x);
7828 return x;
7829 } else
7830 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007831 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007832 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007834 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007835 long value = PyLong_AS_LONG(x);
7836 if (value < 0 || value > 255) {
7837 PyErr_SetString(PyExc_TypeError,
7838 "character mapping must be in range(256)");
7839 Py_DECREF(x);
7840 return NULL;
7841 }
7842 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007843 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007844 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007845 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007846 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 /* wrong return value */
7848 PyErr_Format(PyExc_TypeError,
7849 "character mapping must return integer, bytes or None, not %.400s",
7850 x->ob_type->tp_name);
7851 Py_DECREF(x);
7852 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007853 }
7854}
7855
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007856static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007857charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007859 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7860 /* exponentially overallocate to minimize reallocations */
7861 if (requiredsize < 2*outsize)
7862 requiredsize = 2*outsize;
7863 if (_PyBytes_Resize(outobj, requiredsize))
7864 return -1;
7865 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007866}
7867
Benjamin Peterson14339b62009-01-31 16:36:08 +00007868typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007870} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007871/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007872 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007873 space is available. Return a new reference to the object that
7874 was put in the output buffer, or Py_None, if the mapping was undefined
7875 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007876 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007877static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007878charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007879 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007880{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007881 PyObject *rep;
7882 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007883 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007884
Christian Heimes90aa7642007-12-19 02:45:37 +00007885 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007886 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888 if (res == -1)
7889 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 if (outsize<requiredsize)
7891 if (charmapencode_resize(outobj, outpos, requiredsize))
7892 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007893 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007894 outstart[(*outpos)++] = (char)res;
7895 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007896 }
7897
7898 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007899 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007900 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007901 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 Py_DECREF(rep);
7903 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007905 if (PyLong_Check(rep)) {
7906 Py_ssize_t requiredsize = *outpos+1;
7907 if (outsize<requiredsize)
7908 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7909 Py_DECREF(rep);
7910 return enc_EXCEPTION;
7911 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007912 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007914 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 else {
7916 const char *repchars = PyBytes_AS_STRING(rep);
7917 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7918 Py_ssize_t requiredsize = *outpos+repsize;
7919 if (outsize<requiredsize)
7920 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7921 Py_DECREF(rep);
7922 return enc_EXCEPTION;
7923 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007924 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 memcpy(outstart + *outpos, repchars, repsize);
7926 *outpos += repsize;
7927 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007928 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007929 Py_DECREF(rep);
7930 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007931}
7932
7933/* handle an error in PyUnicode_EncodeCharmap
7934 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007935static int
7936charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007937 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007938 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007939 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007940 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941{
7942 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007943 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007944 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007945 enum PyUnicode_Kind kind;
7946 void *data;
7947 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007948 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007949 Py_ssize_t collstartpos = *inpos;
7950 Py_ssize_t collendpos = *inpos+1;
7951 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007952 char *encoding = "charmap";
7953 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007954 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007955 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007956 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007957
Benjamin Petersonbac79492012-01-14 13:34:47 -05007958 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007959 return -1;
7960 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007961 /* find all unencodable characters */
7962 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007963 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007964 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007965 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007966 val = encoding_map_lookup(ch, mapping);
7967 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 break;
7969 ++collendpos;
7970 continue;
7971 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007972
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007973 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7974 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007975 if (rep==NULL)
7976 return -1;
7977 else if (rep!=Py_None) {
7978 Py_DECREF(rep);
7979 break;
7980 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007981 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007982 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007983 }
7984 /* cache callback name lookup
7985 * (if not done yet, i.e. it's the first error) */
7986 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 if ((errors==NULL) || (!strcmp(errors, "strict")))
7988 *known_errorHandler = 1;
7989 else if (!strcmp(errors, "replace"))
7990 *known_errorHandler = 2;
7991 else if (!strcmp(errors, "ignore"))
7992 *known_errorHandler = 3;
7993 else if (!strcmp(errors, "xmlcharrefreplace"))
7994 *known_errorHandler = 4;
7995 else
7996 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007997 }
7998 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007999 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008000 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008001 return -1;
8002 case 2: /* replace */
8003 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 x = charmapencode_output('?', mapping, res, respos);
8005 if (x==enc_EXCEPTION) {
8006 return -1;
8007 }
8008 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008009 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 return -1;
8011 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008012 }
8013 /* fall through */
8014 case 3: /* ignore */
8015 *inpos = collendpos;
8016 break;
8017 case 4: /* xmlcharrefreplace */
8018 /* generate replacement (temporarily (mis)uses p) */
8019 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 char buffer[2+29+1+1];
8021 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008022 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 for (cp = buffer; *cp; ++cp) {
8024 x = charmapencode_output(*cp, mapping, res, respos);
8025 if (x==enc_EXCEPTION)
8026 return -1;
8027 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008028 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 return -1;
8030 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008031 }
8032 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008033 *inpos = collendpos;
8034 break;
8035 default:
8036 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008037 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008039 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008041 if (PyBytes_Check(repunicode)) {
8042 /* Directly copy bytes result to output. */
8043 Py_ssize_t outsize = PyBytes_Size(*res);
8044 Py_ssize_t requiredsize;
8045 repsize = PyBytes_Size(repunicode);
8046 requiredsize = *respos + repsize;
8047 if (requiredsize > outsize)
8048 /* Make room for all additional bytes. */
8049 if (charmapencode_resize(res, respos, requiredsize)) {
8050 Py_DECREF(repunicode);
8051 return -1;
8052 }
8053 memcpy(PyBytes_AsString(*res) + *respos,
8054 PyBytes_AsString(repunicode), repsize);
8055 *respos += repsize;
8056 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008057 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008058 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008059 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008060 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008061 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008062 Py_DECREF(repunicode);
8063 return -1;
8064 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008065 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008066 data = PyUnicode_DATA(repunicode);
8067 kind = PyUnicode_KIND(repunicode);
8068 for (index = 0; index < repsize; index++) {
8069 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8070 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008072 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008073 return -1;
8074 }
8075 else if (x==enc_FAILED) {
8076 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008077 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008078 return -1;
8079 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008080 }
8081 *inpos = newpos;
8082 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008083 }
8084 return 0;
8085}
8086
Alexander Belopolsky40018472011-02-26 01:02:56 +00008087PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008088_PyUnicode_EncodeCharmap(PyObject *unicode,
8089 PyObject *mapping,
8090 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008091{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 /* output object */
8093 PyObject *res = NULL;
8094 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008095 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008096 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008097 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008098 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008099 PyObject *errorHandler = NULL;
8100 PyObject *exc = NULL;
8101 /* the following variable is used for caching string comparisons
8102 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8103 * 3=ignore, 4=xmlcharrefreplace */
8104 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008105 void *data;
8106 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008107
Benjamin Petersonbac79492012-01-14 13:34:47 -05008108 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008109 return NULL;
8110 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008111 data = PyUnicode_DATA(unicode);
8112 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008113
Guido van Rossumd57fd912000-03-10 22:53:23 +00008114 /* Default to Latin-1 */
8115 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008116 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008117
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008118 /* allocate enough for a simple encoding without
8119 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008120 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 if (res == NULL)
8122 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008123 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008125
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008126 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008127 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008129 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 if (x==enc_EXCEPTION) /* error */
8131 goto onError;
8132 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008133 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008134 &exc,
8135 &known_errorHandler, &errorHandler, errors,
8136 &res, &respos)) {
8137 goto onError;
8138 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008139 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008140 else
8141 /* done with this character => adjust input position */
8142 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008143 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008144
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008145 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008146 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008147 if (_PyBytes_Resize(&res, respos) < 0)
8148 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008149
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008150 Py_XDECREF(exc);
8151 Py_XDECREF(errorHandler);
8152 return res;
8153
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008155 Py_XDECREF(res);
8156 Py_XDECREF(exc);
8157 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008158 return NULL;
8159}
8160
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008161/* Deprecated */
8162PyObject *
8163PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8164 Py_ssize_t size,
8165 PyObject *mapping,
8166 const char *errors)
8167{
8168 PyObject *result;
8169 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8170 if (unicode == NULL)
8171 return NULL;
8172 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8173 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008174 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008175}
8176
Alexander Belopolsky40018472011-02-26 01:02:56 +00008177PyObject *
8178PyUnicode_AsCharmapString(PyObject *unicode,
8179 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008180{
8181 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 PyErr_BadArgument();
8183 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008184 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008185 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186}
8187
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008188/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008189static void
8190make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008191 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008192 Py_ssize_t startpos, Py_ssize_t endpos,
8193 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008196 *exceptionObject = _PyUnicodeTranslateError_Create(
8197 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008198 }
8199 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8201 goto onError;
8202 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8203 goto onError;
8204 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8205 goto onError;
8206 return;
8207 onError:
8208 Py_DECREF(*exceptionObject);
8209 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210 }
8211}
8212
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008213/* error handling callback helper:
8214 build arguments, call the callback and check the arguments,
8215 put the result into newpos and return the replacement string, which
8216 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008217static PyObject *
8218unicode_translate_call_errorhandler(const char *errors,
8219 PyObject **errorHandler,
8220 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008221 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008222 Py_ssize_t startpos, Py_ssize_t endpos,
8223 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008225 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008226
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008227 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008228 PyObject *restuple;
8229 PyObject *resunicode;
8230
8231 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 }
8236
8237 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008238 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008239 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241
8242 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008247 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 Py_DECREF(restuple);
8249 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008250 }
8251 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 &resunicode, &i_newpos)) {
8253 Py_DECREF(restuple);
8254 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008256 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008257 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008258 else
8259 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008260 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8262 Py_DECREF(restuple);
8263 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008264 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 Py_INCREF(resunicode);
8266 Py_DECREF(restuple);
8267 return resunicode;
8268}
8269
8270/* Lookup the character ch in the mapping and put the result in result,
8271 which must be decrefed by the caller.
8272 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008273static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008274charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275{
Christian Heimes217cfd12007-12-02 14:31:20 +00008276 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008277 PyObject *x;
8278
8279 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 x = PyObject_GetItem(mapping, w);
8282 Py_DECREF(w);
8283 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8285 /* No mapping found means: use 1:1 mapping. */
8286 PyErr_Clear();
8287 *result = NULL;
8288 return 0;
8289 } else
8290 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291 }
8292 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 *result = x;
8294 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008296 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 long value = PyLong_AS_LONG(x);
8298 long max = PyUnicode_GetMax();
8299 if (value < 0 || value > max) {
8300 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008301 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 Py_DECREF(x);
8303 return -1;
8304 }
8305 *result = x;
8306 return 0;
8307 }
8308 else if (PyUnicode_Check(x)) {
8309 *result = x;
8310 return 0;
8311 }
8312 else {
8313 /* wrong return value */
8314 PyErr_SetString(PyExc_TypeError,
8315 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008316 Py_DECREF(x);
8317 return -1;
8318 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319}
8320/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 if not reallocate and adjust various state variables.
8322 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008323static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008324charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008327 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008328 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008329 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 /* exponentially overallocate to minimize reallocations */
8331 if (requiredsize < 2 * oldsize)
8332 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008333 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8334 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008336 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008337 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338 }
8339 return 0;
8340}
8341/* lookup the character, put the result in the output string and adjust
8342 various state variables. Return a new reference to the object that
8343 was put in the output buffer in *result, or Py_None, if the mapping was
8344 undefined (in which case no character was written).
8345 The called must decref result.
8346 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008347static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008348charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8349 PyObject *mapping, Py_UCS4 **output,
8350 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008351 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008353 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8354 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008358 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 }
8360 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008362 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365 }
8366 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008367 Py_ssize_t repsize;
8368 if (PyUnicode_READY(*res) == -1)
8369 return -1;
8370 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 if (repsize==1) {
8372 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008374 }
8375 else if (repsize!=0) {
8376 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008377 Py_ssize_t requiredsize = *opos +
8378 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008380 Py_ssize_t i;
8381 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383 for(i = 0; i < repsize; i++)
8384 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 }
8387 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 return 0;
8390}
8391
Alexander Belopolsky40018472011-02-26 01:02:56 +00008392PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008393_PyUnicode_TranslateCharmap(PyObject *input,
8394 PyObject *mapping,
8395 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008397 /* input object */
8398 char *idata;
8399 Py_ssize_t size, i;
8400 int kind;
8401 /* output buffer */
8402 Py_UCS4 *output = NULL;
8403 Py_ssize_t osize;
8404 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008406 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 char *reason = "character maps to <undefined>";
8408 PyObject *errorHandler = NULL;
8409 PyObject *exc = NULL;
8410 /* the following variable is used for caching string comparisons
8411 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8412 * 3=ignore, 4=xmlcharrefreplace */
8413 int known_errorHandler = -1;
8414
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 PyErr_BadArgument();
8417 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008418 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008420 if (PyUnicode_READY(input) == -1)
8421 return NULL;
8422 idata = (char*)PyUnicode_DATA(input);
8423 kind = PyUnicode_KIND(input);
8424 size = PyUnicode_GET_LENGTH(input);
8425 i = 0;
8426
8427 if (size == 0) {
8428 Py_INCREF(input);
8429 return input;
8430 }
8431
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432 /* allocate enough for a simple 1:1 translation without
8433 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008434 osize = size;
8435 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8436 opos = 0;
8437 if (output == NULL) {
8438 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008440 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 /* try to encode it */
8444 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 if (charmaptranslate_output(input, i, mapping,
8446 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 Py_XDECREF(x);
8448 goto onError;
8449 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008450 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008452 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 else { /* untranslatable character */
8454 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8455 Py_ssize_t repsize;
8456 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008459 Py_ssize_t collstart = i;
8460 Py_ssize_t collend = i+1;
8461 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008462
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 while (collend < size) {
8465 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 goto onError;
8467 Py_XDECREF(x);
8468 if (x!=Py_None)
8469 break;
8470 ++collend;
8471 }
8472 /* cache callback name lookup
8473 * (if not done yet, i.e. it's the first error) */
8474 if (known_errorHandler==-1) {
8475 if ((errors==NULL) || (!strcmp(errors, "strict")))
8476 known_errorHandler = 1;
8477 else if (!strcmp(errors, "replace"))
8478 known_errorHandler = 2;
8479 else if (!strcmp(errors, "ignore"))
8480 known_errorHandler = 3;
8481 else if (!strcmp(errors, "xmlcharrefreplace"))
8482 known_errorHandler = 4;
8483 else
8484 known_errorHandler = 0;
8485 }
8486 switch (known_errorHandler) {
8487 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008488 make_translate_exception(&exc,
8489 input, collstart, collend, reason);
8490 if (exc != NULL)
8491 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 case 2: /* replace */
8494 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 for (coll = collstart; coll<collend; coll++)
8496 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 /* fall through */
8498 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 break;
8501 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502 /* generate replacement (temporarily (mis)uses i) */
8503 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 char buffer[2+29+1+1];
8505 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8507 if (charmaptranslate_makespace(&output, &osize,
8508 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 goto onError;
8510 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008514 break;
8515 default:
8516 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 reason, input, &exc,
8518 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008519 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008521 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008522 Py_DECREF(repunicode);
8523 goto onError;
8524 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 repsize = PyUnicode_GET_LENGTH(repunicode);
8527 if (charmaptranslate_makespace(&output, &osize,
8528 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 Py_DECREF(repunicode);
8530 goto onError;
8531 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 for (uni2 = 0; repsize-->0; ++uni2)
8533 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8534 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008536 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008537 }
8538 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008539 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8540 if (!res)
8541 goto onError;
8542 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008543 Py_XDECREF(exc);
8544 Py_XDECREF(errorHandler);
8545 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008546
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008549 Py_XDECREF(exc);
8550 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008551 return NULL;
8552}
8553
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554/* Deprecated. Use PyUnicode_Translate instead. */
8555PyObject *
8556PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8557 Py_ssize_t size,
8558 PyObject *mapping,
8559 const char *errors)
8560{
Christian Heimes5f520f42012-09-11 14:03:25 +02008561 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8563 if (!unicode)
8564 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008565 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8566 Py_DECREF(unicode);
8567 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568}
8569
Alexander Belopolsky40018472011-02-26 01:02:56 +00008570PyObject *
8571PyUnicode_Translate(PyObject *str,
8572 PyObject *mapping,
8573 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008574{
8575 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008576
Guido van Rossumd57fd912000-03-10 22:53:23 +00008577 str = PyUnicode_FromObject(str);
8578 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008579 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581 Py_DECREF(str);
8582 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583}
Tim Petersced69f82003-09-16 20:30:58 +00008584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008586fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587{
8588 /* No need to call PyUnicode_READY(self) because this function is only
8589 called as a callback from fixup() which does it already. */
8590 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8591 const int kind = PyUnicode_KIND(self);
8592 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008593 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008594 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 Py_ssize_t i;
8596
8597 for (i = 0; i < len; ++i) {
8598 ch = PyUnicode_READ(kind, data, i);
8599 fixed = 0;
8600 if (ch > 127) {
8601 if (Py_UNICODE_ISSPACE(ch))
8602 fixed = ' ';
8603 else {
8604 const int decimal = Py_UNICODE_TODECIMAL(ch);
8605 if (decimal >= 0)
8606 fixed = '0' + decimal;
8607 }
8608 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008609 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008610 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 PyUnicode_WRITE(kind, data, i, fixed);
8612 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008613 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008614 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 }
8617
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008618 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619}
8620
8621PyObject *
8622_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8623{
8624 if (!PyUnicode_Check(unicode)) {
8625 PyErr_BadInternalCall();
8626 return NULL;
8627 }
8628 if (PyUnicode_READY(unicode) == -1)
8629 return NULL;
8630 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8631 /* If the string is already ASCII, just return the same string */
8632 Py_INCREF(unicode);
8633 return unicode;
8634 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008635 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636}
8637
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008638PyObject *
8639PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8640 Py_ssize_t length)
8641{
Victor Stinnerf0124502011-11-21 23:12:56 +01008642 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008643 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008644 Py_UCS4 maxchar;
8645 enum PyUnicode_Kind kind;
8646 void *data;
8647
Victor Stinner99d7ad02012-02-22 13:37:39 +01008648 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008649 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008650 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008651 if (ch > 127) {
8652 int decimal = Py_UNICODE_TODECIMAL(ch);
8653 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008654 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008655 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008656 }
8657 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008658
8659 /* Copy to a new string */
8660 decimal = PyUnicode_New(length, maxchar);
8661 if (decimal == NULL)
8662 return decimal;
8663 kind = PyUnicode_KIND(decimal);
8664 data = PyUnicode_DATA(decimal);
8665 /* Iterate over code points */
8666 for (i = 0; i < length; i++) {
8667 Py_UNICODE ch = s[i];
8668 if (ch > 127) {
8669 int decimal = Py_UNICODE_TODECIMAL(ch);
8670 if (decimal >= 0)
8671 ch = '0' + decimal;
8672 }
8673 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008675 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008676}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008677/* --- Decimal Encoder ---------------------------------------------------- */
8678
Alexander Belopolsky40018472011-02-26 01:02:56 +00008679int
8680PyUnicode_EncodeDecimal(Py_UNICODE *s,
8681 Py_ssize_t length,
8682 char *output,
8683 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008684{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008685 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008686 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008687 enum PyUnicode_Kind kind;
8688 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008689
8690 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 PyErr_BadArgument();
8692 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008693 }
8694
Victor Stinner42bf7752011-11-21 22:52:58 +01008695 unicode = PyUnicode_FromUnicode(s, length);
8696 if (unicode == NULL)
8697 return -1;
8698
Benjamin Petersonbac79492012-01-14 13:34:47 -05008699 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008700 Py_DECREF(unicode);
8701 return -1;
8702 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008703 kind = PyUnicode_KIND(unicode);
8704 data = PyUnicode_DATA(unicode);
8705
Victor Stinnerb84d7232011-11-22 01:50:07 +01008706 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008707 PyObject *exc;
8708 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008709 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008710 Py_ssize_t startpos;
8711
8712 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008713
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008715 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008716 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008718 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 decimal = Py_UNICODE_TODECIMAL(ch);
8720 if (decimal >= 0) {
8721 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008722 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 continue;
8724 }
8725 if (0 < ch && ch < 256) {
8726 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008727 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 continue;
8729 }
Victor Stinner6345be92011-11-25 20:09:01 +01008730
Victor Stinner42bf7752011-11-21 22:52:58 +01008731 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008732 exc = NULL;
8733 raise_encode_exception(&exc, "decimal", unicode,
8734 startpos, startpos+1,
8735 "invalid decimal Unicode string");
8736 Py_XDECREF(exc);
8737 Py_DECREF(unicode);
8738 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008739 }
8740 /* 0-terminate the output string */
8741 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008742 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008743 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008744}
8745
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746/* --- Helpers ------------------------------------------------------------ */
8747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008749any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 Py_ssize_t start,
8751 Py_ssize_t end)
8752{
8753 int kind1, kind2, kind;
8754 void *buf1, *buf2;
8755 Py_ssize_t len1, len2, result;
8756
8757 kind1 = PyUnicode_KIND(s1);
8758 kind2 = PyUnicode_KIND(s2);
8759 kind = kind1 > kind2 ? kind1 : kind2;
8760 buf1 = PyUnicode_DATA(s1);
8761 buf2 = PyUnicode_DATA(s2);
8762 if (kind1 != kind)
8763 buf1 = _PyUnicode_AsKind(s1, kind);
8764 if (!buf1)
8765 return -2;
8766 if (kind2 != kind)
8767 buf2 = _PyUnicode_AsKind(s2, kind);
8768 if (!buf2) {
8769 if (kind1 != kind) PyMem_Free(buf1);
8770 return -2;
8771 }
8772 len1 = PyUnicode_GET_LENGTH(s1);
8773 len2 = PyUnicode_GET_LENGTH(s2);
8774
Victor Stinner794d5672011-10-10 03:21:36 +02008775 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008776 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008777 case PyUnicode_1BYTE_KIND:
8778 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8779 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8780 else
8781 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8782 break;
8783 case PyUnicode_2BYTE_KIND:
8784 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8785 break;
8786 case PyUnicode_4BYTE_KIND:
8787 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8788 break;
8789 default:
8790 assert(0); result = -2;
8791 }
8792 }
8793 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008794 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008795 case PyUnicode_1BYTE_KIND:
8796 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8797 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8798 else
8799 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8800 break;
8801 case PyUnicode_2BYTE_KIND:
8802 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8803 break;
8804 case PyUnicode_4BYTE_KIND:
8805 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8806 break;
8807 default:
8808 assert(0); result = -2;
8809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008810 }
8811
8812 if (kind1 != kind)
8813 PyMem_Free(buf1);
8814 if (kind2 != kind)
8815 PyMem_Free(buf2);
8816
8817 return result;
8818}
8819
8820Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008821_PyUnicode_InsertThousandsGrouping(
8822 PyObject *unicode, Py_ssize_t index,
8823 Py_ssize_t n_buffer,
8824 void *digits, Py_ssize_t n_digits,
8825 Py_ssize_t min_width,
8826 const char *grouping, PyObject *thousands_sep,
8827 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828{
Victor Stinner41a863c2012-02-24 00:37:51 +01008829 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008830 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008831 Py_ssize_t thousands_sep_len;
8832 Py_ssize_t len;
8833
8834 if (unicode != NULL) {
8835 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008836 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008837 }
8838 else {
8839 kind = PyUnicode_1BYTE_KIND;
8840 data = NULL;
8841 }
8842 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8843 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8844 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8845 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008846 if (thousands_sep_kind < kind) {
8847 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8848 if (!thousands_sep_data)
8849 return -1;
8850 }
8851 else {
8852 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8853 if (!data)
8854 return -1;
8855 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008856 }
8857
Benjamin Petersonead6b532011-12-20 17:23:42 -06008858 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008859 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008860 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008861 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008862 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008863 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008864 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008865 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008866 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008867 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008868 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008869 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008870 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008872 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008873 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008874 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008875 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008876 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008878 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008879 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008880 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008881 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008882 break;
8883 default:
8884 assert(0);
8885 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008886 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008887 if (unicode != NULL && thousands_sep_kind != kind) {
8888 if (thousands_sep_kind < kind)
8889 PyMem_Free(thousands_sep_data);
8890 else
8891 PyMem_Free(data);
8892 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008893 if (unicode == NULL) {
8894 *maxchar = 127;
8895 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07008896 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02008897 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008898 }
8899 }
8900 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901}
8902
8903
Thomas Wouters477c8d52006-05-27 19:21:47 +00008904/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008905#define ADJUST_INDICES(start, end, len) \
8906 if (end > len) \
8907 end = len; \
8908 else if (end < 0) { \
8909 end += len; \
8910 if (end < 0) \
8911 end = 0; \
8912 } \
8913 if (start < 0) { \
8914 start += len; \
8915 if (start < 0) \
8916 start = 0; \
8917 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008918
Alexander Belopolsky40018472011-02-26 01:02:56 +00008919Py_ssize_t
8920PyUnicode_Count(PyObject *str,
8921 PyObject *substr,
8922 Py_ssize_t start,
8923 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008924{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008925 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008926 PyObject* str_obj;
8927 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928 int kind1, kind2, kind;
8929 void *buf1 = NULL, *buf2 = NULL;
8930 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008931
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008932 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008933 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008934 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008935 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008936 if (!sub_obj) {
8937 Py_DECREF(str_obj);
8938 return -1;
8939 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008940 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008941 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 Py_DECREF(str_obj);
8943 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944 }
Tim Petersced69f82003-09-16 20:30:58 +00008945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008946 kind1 = PyUnicode_KIND(str_obj);
8947 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008948 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008949 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008951 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008952 if (kind2 > kind) {
8953 Py_DECREF(sub_obj);
8954 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008955 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008956 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008957 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008959 if (!buf2)
8960 goto onError;
8961 len1 = PyUnicode_GET_LENGTH(str_obj);
8962 len2 = PyUnicode_GET_LENGTH(sub_obj);
8963
8964 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008965 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008967 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8968 result = asciilib_count(
8969 ((Py_UCS1*)buf1) + start, end - start,
8970 buf2, len2, PY_SSIZE_T_MAX
8971 );
8972 else
8973 result = ucs1lib_count(
8974 ((Py_UCS1*)buf1) + start, end - start,
8975 buf2, len2, PY_SSIZE_T_MAX
8976 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 break;
8978 case PyUnicode_2BYTE_KIND:
8979 result = ucs2lib_count(
8980 ((Py_UCS2*)buf1) + start, end - start,
8981 buf2, len2, PY_SSIZE_T_MAX
8982 );
8983 break;
8984 case PyUnicode_4BYTE_KIND:
8985 result = ucs4lib_count(
8986 ((Py_UCS4*)buf1) + start, end - start,
8987 buf2, len2, PY_SSIZE_T_MAX
8988 );
8989 break;
8990 default:
8991 assert(0); result = 0;
8992 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008993
8994 Py_DECREF(sub_obj);
8995 Py_DECREF(str_obj);
8996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997 if (kind2 != kind)
8998 PyMem_Free(buf2);
8999
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 onError:
9002 Py_DECREF(sub_obj);
9003 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009004 if (kind2 != kind && buf2)
9005 PyMem_Free(buf2);
9006 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009007}
9008
Alexander Belopolsky40018472011-02-26 01:02:56 +00009009Py_ssize_t
9010PyUnicode_Find(PyObject *str,
9011 PyObject *sub,
9012 Py_ssize_t start,
9013 Py_ssize_t end,
9014 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009015{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009016 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009017
Guido van Rossumd57fd912000-03-10 22:53:23 +00009018 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009019 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009020 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009021 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009022 if (!sub) {
9023 Py_DECREF(str);
9024 return -2;
9025 }
9026 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9027 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009028 Py_DECREF(str);
9029 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030 }
Tim Petersced69f82003-09-16 20:30:58 +00009031
Victor Stinner794d5672011-10-10 03:21:36 +02009032 result = any_find_slice(direction,
9033 str, sub, start, end
9034 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009035
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009037 Py_DECREF(sub);
9038
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039 return result;
9040}
9041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042Py_ssize_t
9043PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9044 Py_ssize_t start, Py_ssize_t end,
9045 int direction)
9046{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009048 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049 if (PyUnicode_READY(str) == -1)
9050 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009051 if (start < 0 || end < 0) {
9052 PyErr_SetString(PyExc_IndexError, "string index out of range");
9053 return -2;
9054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009055 if (end > PyUnicode_GET_LENGTH(str))
9056 end = PyUnicode_GET_LENGTH(str);
9057 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009058 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9059 kind, end-start, ch, direction);
9060 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009062 else
9063 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064}
9065
Alexander Belopolsky40018472011-02-26 01:02:56 +00009066static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009067tailmatch(PyObject *self,
9068 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009069 Py_ssize_t start,
9070 Py_ssize_t end,
9071 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009072{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073 int kind_self;
9074 int kind_sub;
9075 void *data_self;
9076 void *data_sub;
9077 Py_ssize_t offset;
9078 Py_ssize_t i;
9079 Py_ssize_t end_sub;
9080
9081 if (PyUnicode_READY(self) == -1 ||
9082 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009083 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084
9085 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009086 return 1;
9087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009088 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9089 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009091 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093 kind_self = PyUnicode_KIND(self);
9094 data_self = PyUnicode_DATA(self);
9095 kind_sub = PyUnicode_KIND(substring);
9096 data_sub = PyUnicode_DATA(substring);
9097 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9098
9099 if (direction > 0)
9100 offset = end;
9101 else
9102 offset = start;
9103
9104 if (PyUnicode_READ(kind_self, data_self, offset) ==
9105 PyUnicode_READ(kind_sub, data_sub, 0) &&
9106 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9107 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9108 /* If both are of the same kind, memcmp is sufficient */
9109 if (kind_self == kind_sub) {
9110 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009111 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 data_sub,
9113 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009114 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115 }
9116 /* otherwise we have to compare each character by first accesing it */
9117 else {
9118 /* We do not need to compare 0 and len(substring)-1 because
9119 the if statement above ensured already that they are equal
9120 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 for (i = 1; i < end_sub; ++i) {
9122 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9123 PyUnicode_READ(kind_sub, data_sub, i))
9124 return 0;
9125 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009127 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009128 }
9129
9130 return 0;
9131}
9132
Alexander Belopolsky40018472011-02-26 01:02:56 +00009133Py_ssize_t
9134PyUnicode_Tailmatch(PyObject *str,
9135 PyObject *substr,
9136 Py_ssize_t start,
9137 Py_ssize_t end,
9138 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009140 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009141
Guido van Rossumd57fd912000-03-10 22:53:23 +00009142 str = PyUnicode_FromObject(str);
9143 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009144 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145 substr = PyUnicode_FromObject(substr);
9146 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 Py_DECREF(str);
9148 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149 }
Tim Petersced69f82003-09-16 20:30:58 +00009150
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009151 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009152 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009153 Py_DECREF(str);
9154 Py_DECREF(substr);
9155 return result;
9156}
9157
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158/* Apply fixfct filter to the Unicode object self and return a
9159 reference to the modified object */
9160
Alexander Belopolsky40018472011-02-26 01:02:56 +00009161static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009162fixup(PyObject *self,
9163 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009164{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009165 PyObject *u;
9166 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009167 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009169 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009170 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009172 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174 /* fix functions return the new maximum character in a string,
9175 if the kind of the resulting unicode object does not change,
9176 everything is fine. Otherwise we need to change the string kind
9177 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009178 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009179
9180 if (maxchar_new == 0) {
9181 /* no changes */;
9182 if (PyUnicode_CheckExact(self)) {
9183 Py_DECREF(u);
9184 Py_INCREF(self);
9185 return self;
9186 }
9187 else
9188 return u;
9189 }
9190
Victor Stinnere6abb482012-05-02 01:15:40 +02009191 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192
Victor Stinnereaab6042011-12-11 22:22:39 +01009193 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009195
9196 /* In case the maximum character changed, we need to
9197 convert the string to the new category. */
9198 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9199 if (v == NULL) {
9200 Py_DECREF(u);
9201 return NULL;
9202 }
9203 if (maxchar_new > maxchar_old) {
9204 /* If the maxchar increased so that the kind changed, not all
9205 characters are representable anymore and we need to fix the
9206 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009207 _PyUnicode_FastCopyCharacters(v, 0,
9208 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009209 maxchar_old = fixfct(v);
9210 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 }
9212 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009213 _PyUnicode_FastCopyCharacters(v, 0,
9214 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009216 Py_DECREF(u);
9217 assert(_PyUnicode_CheckConsistency(v, 1));
9218 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219}
9220
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009221static PyObject *
9222ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009223{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009224 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9225 char *resdata, *data = PyUnicode_DATA(self);
9226 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009227
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009228 res = PyUnicode_New(len, 127);
9229 if (res == NULL)
9230 return NULL;
9231 resdata = PyUnicode_DATA(res);
9232 if (lower)
9233 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009235 _Py_bytes_upper(resdata, data, len);
9236 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237}
9238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009240handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009241{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009242 Py_ssize_t j;
9243 int final_sigma;
9244 Py_UCS4 c;
9245 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009246
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009247 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9248
9249 where ! is a negation and \p{xxx} is a character with property xxx.
9250 */
9251 for (j = i - 1; j >= 0; j--) {
9252 c = PyUnicode_READ(kind, data, j);
9253 if (!_PyUnicode_IsCaseIgnorable(c))
9254 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009256 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9257 if (final_sigma) {
9258 for (j = i + 1; j < length; j++) {
9259 c = PyUnicode_READ(kind, data, j);
9260 if (!_PyUnicode_IsCaseIgnorable(c))
9261 break;
9262 }
9263 final_sigma = j == length || !_PyUnicode_IsCased(c);
9264 }
9265 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266}
9267
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009268static int
9269lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9270 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009272 /* Obscure special case. */
9273 if (c == 0x3A3) {
9274 mapped[0] = handle_capital_sigma(kind, data, length, i);
9275 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009277 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278}
9279
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009280static Py_ssize_t
9281do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009283 Py_ssize_t i, k = 0;
9284 int n_res, j;
9285 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009286
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009287 c = PyUnicode_READ(kind, data, 0);
9288 n_res = _PyUnicode_ToUpperFull(c, mapped);
9289 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009290 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009291 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009293 for (i = 1; i < length; i++) {
9294 c = PyUnicode_READ(kind, data, i);
9295 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9296 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009297 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009298 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009299 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009300 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009301 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009302}
9303
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009304static Py_ssize_t
9305do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9306 Py_ssize_t i, k = 0;
9307
9308 for (i = 0; i < length; i++) {
9309 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9310 int n_res, j;
9311 if (Py_UNICODE_ISUPPER(c)) {
9312 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9313 }
9314 else if (Py_UNICODE_ISLOWER(c)) {
9315 n_res = _PyUnicode_ToUpperFull(c, mapped);
9316 }
9317 else {
9318 n_res = 1;
9319 mapped[0] = c;
9320 }
9321 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009322 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009323 res[k++] = mapped[j];
9324 }
9325 }
9326 return k;
9327}
9328
9329static Py_ssize_t
9330do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9331 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009332{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009333 Py_ssize_t i, k = 0;
9334
9335 for (i = 0; i < length; i++) {
9336 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9337 int n_res, j;
9338 if (lower)
9339 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9340 else
9341 n_res = _PyUnicode_ToUpperFull(c, mapped);
9342 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009343 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009344 res[k++] = mapped[j];
9345 }
9346 }
9347 return k;
9348}
9349
9350static Py_ssize_t
9351do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9352{
9353 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9354}
9355
9356static Py_ssize_t
9357do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9358{
9359 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9360}
9361
Benjamin Petersone51757f2012-01-12 21:10:29 -05009362static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009363do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9364{
9365 Py_ssize_t i, k = 0;
9366
9367 for (i = 0; i < length; i++) {
9368 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9369 Py_UCS4 mapped[3];
9370 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9371 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009372 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009373 res[k++] = mapped[j];
9374 }
9375 }
9376 return k;
9377}
9378
9379static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009380do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9381{
9382 Py_ssize_t i, k = 0;
9383 int previous_is_cased;
9384
9385 previous_is_cased = 0;
9386 for (i = 0; i < length; i++) {
9387 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9388 Py_UCS4 mapped[3];
9389 int n_res, j;
9390
9391 if (previous_is_cased)
9392 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9393 else
9394 n_res = _PyUnicode_ToTitleFull(c, mapped);
9395
9396 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009397 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009398 res[k++] = mapped[j];
9399 }
9400
9401 previous_is_cased = _PyUnicode_IsCased(c);
9402 }
9403 return k;
9404}
9405
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009406static PyObject *
9407case_operation(PyObject *self,
9408 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9409{
9410 PyObject *res = NULL;
9411 Py_ssize_t length, newlength = 0;
9412 int kind, outkind;
9413 void *data, *outdata;
9414 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9415
Benjamin Petersoneea48462012-01-16 14:28:50 -05009416 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009417
9418 kind = PyUnicode_KIND(self);
9419 data = PyUnicode_DATA(self);
9420 length = PyUnicode_GET_LENGTH(self);
9421 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9422 if (tmp == NULL)
9423 return PyErr_NoMemory();
9424 newlength = perform(kind, data, length, tmp, &maxchar);
9425 res = PyUnicode_New(newlength, maxchar);
9426 if (res == NULL)
9427 goto leave;
9428 tmpend = tmp + newlength;
9429 outdata = PyUnicode_DATA(res);
9430 outkind = PyUnicode_KIND(res);
9431 switch (outkind) {
9432 case PyUnicode_1BYTE_KIND:
9433 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9434 break;
9435 case PyUnicode_2BYTE_KIND:
9436 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9437 break;
9438 case PyUnicode_4BYTE_KIND:
9439 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9440 break;
9441 default:
9442 assert(0);
9443 break;
9444 }
9445 leave:
9446 PyMem_FREE(tmp);
9447 return res;
9448}
9449
Tim Peters8ce9f162004-08-27 01:49:32 +00009450PyObject *
9451PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009454 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009456 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009457 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9458 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009459 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009461 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009463 int use_memcpy;
9464 unsigned char *res_data = NULL, *sep_data = NULL;
9465 PyObject *last_obj;
9466 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467
Tim Peters05eba1f2004-08-27 21:32:02 +00009468 fseq = PySequence_Fast(seq, "");
9469 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009470 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009471 }
9472
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009473 /* NOTE: the following code can't call back into Python code,
9474 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009475 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009476
Tim Peters05eba1f2004-08-27 21:32:02 +00009477 seqlen = PySequence_Fast_GET_SIZE(fseq);
9478 /* If empty sequence, return u"". */
9479 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009480 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009481 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009482 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009483
Tim Peters05eba1f2004-08-27 21:32:02 +00009484 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009485 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009486 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009487 if (seqlen == 1) {
9488 if (PyUnicode_CheckExact(items[0])) {
9489 res = items[0];
9490 Py_INCREF(res);
9491 Py_DECREF(fseq);
9492 return res;
9493 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009494 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009495 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009496 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009497 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009498 /* Set up sep and seplen */
9499 if (separator == NULL) {
9500 /* fall back to a blank space separator */
9501 sep = PyUnicode_FromOrdinal(' ');
9502 if (!sep)
9503 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009504 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009505 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009506 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009507 else {
9508 if (!PyUnicode_Check(separator)) {
9509 PyErr_Format(PyExc_TypeError,
9510 "separator: expected str instance,"
9511 " %.80s found",
9512 Py_TYPE(separator)->tp_name);
9513 goto onError;
9514 }
9515 if (PyUnicode_READY(separator))
9516 goto onError;
9517 sep = separator;
9518 seplen = PyUnicode_GET_LENGTH(separator);
9519 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9520 /* inc refcount to keep this code path symmetric with the
9521 above case of a blank separator */
9522 Py_INCREF(sep);
9523 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009524 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009525 }
9526
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009527 /* There are at least two things to join, or else we have a subclass
9528 * of str in the sequence.
9529 * Do a pre-pass to figure out the total amount of space we'll
9530 * need (sz), and see whether all argument are strings.
9531 */
9532 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009533#ifdef Py_DEBUG
9534 use_memcpy = 0;
9535#else
9536 use_memcpy = 1;
9537#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009538 for (i = 0; i < seqlen; i++) {
9539 const Py_ssize_t old_sz = sz;
9540 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009541 if (!PyUnicode_Check(item)) {
9542 PyErr_Format(PyExc_TypeError,
9543 "sequence item %zd: expected str instance,"
9544 " %.80s found",
9545 i, Py_TYPE(item)->tp_name);
9546 goto onError;
9547 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548 if (PyUnicode_READY(item) == -1)
9549 goto onError;
9550 sz += PyUnicode_GET_LENGTH(item);
9551 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009552 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009553 if (i != 0)
9554 sz += seplen;
9555 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9556 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009558 goto onError;
9559 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009560 if (use_memcpy && last_obj != NULL) {
9561 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9562 use_memcpy = 0;
9563 }
9564 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009565 }
Tim Petersced69f82003-09-16 20:30:58 +00009566
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009567 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009568 if (res == NULL)
9569 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009570
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009571 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009572#ifdef Py_DEBUG
9573 use_memcpy = 0;
9574#else
9575 if (use_memcpy) {
9576 res_data = PyUnicode_1BYTE_DATA(res);
9577 kind = PyUnicode_KIND(res);
9578 if (seplen != 0)
9579 sep_data = PyUnicode_1BYTE_DATA(sep);
9580 }
9581#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009582 if (use_memcpy) {
9583 for (i = 0; i < seqlen; ++i) {
9584 Py_ssize_t itemlen;
9585 item = items[i];
9586
9587 /* Copy item, and maybe the separator. */
9588 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009589 Py_MEMCPY(res_data,
9590 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009591 kind * seplen);
9592 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009593 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009594
9595 itemlen = PyUnicode_GET_LENGTH(item);
9596 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009597 Py_MEMCPY(res_data,
9598 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009599 kind * itemlen);
9600 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009601 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009602 }
9603 assert(res_data == PyUnicode_1BYTE_DATA(res)
9604 + kind * PyUnicode_GET_LENGTH(res));
9605 }
9606 else {
9607 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9608 Py_ssize_t itemlen;
9609 item = items[i];
9610
9611 /* Copy item, and maybe the separator. */
9612 if (i && seplen != 0) {
9613 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9614 res_offset += seplen;
9615 }
9616
9617 itemlen = PyUnicode_GET_LENGTH(item);
9618 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009619 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009620 res_offset += itemlen;
9621 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009622 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009623 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009624 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009625
Tim Peters05eba1f2004-08-27 21:32:02 +00009626 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009628 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630
Benjamin Peterson29060642009-01-31 22:14:21 +00009631 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009632 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009633 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009634 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009635 return NULL;
9636}
9637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638#define FILL(kind, data, value, start, length) \
9639 do { \
9640 Py_ssize_t i_ = 0; \
9641 assert(kind != PyUnicode_WCHAR_KIND); \
9642 switch ((kind)) { \
9643 case PyUnicode_1BYTE_KIND: { \
9644 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009645 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 break; \
9647 } \
9648 case PyUnicode_2BYTE_KIND: { \
9649 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9650 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9651 break; \
9652 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009653 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9655 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9656 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009657 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 } \
9659 } \
9660 } while (0)
9661
Victor Stinnerd3f08822012-05-29 12:57:52 +02009662void
9663_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9664 Py_UCS4 fill_char)
9665{
9666 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9667 const void *data = PyUnicode_DATA(unicode);
9668 assert(PyUnicode_IS_READY(unicode));
9669 assert(unicode_modifiable(unicode));
9670 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9671 assert(start >= 0);
9672 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9673 FILL(kind, data, fill_char, start, length);
9674}
9675
Victor Stinner3fe55312012-01-04 00:33:50 +01009676Py_ssize_t
9677PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9678 Py_UCS4 fill_char)
9679{
9680 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009681
9682 if (!PyUnicode_Check(unicode)) {
9683 PyErr_BadInternalCall();
9684 return -1;
9685 }
9686 if (PyUnicode_READY(unicode) == -1)
9687 return -1;
9688 if (unicode_check_modifiable(unicode))
9689 return -1;
9690
Victor Stinnerd3f08822012-05-29 12:57:52 +02009691 if (start < 0) {
9692 PyErr_SetString(PyExc_IndexError, "string index out of range");
9693 return -1;
9694 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009695 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9696 PyErr_SetString(PyExc_ValueError,
9697 "fill character is bigger than "
9698 "the string maximum character");
9699 return -1;
9700 }
9701
9702 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9703 length = Py_MIN(maxlen, length);
9704 if (length <= 0)
9705 return 0;
9706
Victor Stinnerd3f08822012-05-29 12:57:52 +02009707 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009708 return length;
9709}
9710
Victor Stinner9310abb2011-10-05 00:59:23 +02009711static PyObject *
9712pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009713 Py_ssize_t left,
9714 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009715 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009716{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009717 PyObject *u;
9718 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009719 int kind;
9720 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009721
9722 if (left < 0)
9723 left = 0;
9724 if (right < 0)
9725 right = 0;
9726
Victor Stinnerc4b49542011-12-11 22:44:26 +01009727 if (left == 0 && right == 0)
9728 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009730 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9731 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009732 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9733 return NULL;
9734 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009736 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009737 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009738 if (!u)
9739 return NULL;
9740
9741 kind = PyUnicode_KIND(u);
9742 data = PyUnicode_DATA(u);
9743 if (left)
9744 FILL(kind, data, fill, 0, left);
9745 if (right)
9746 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009747 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009748 assert(_PyUnicode_CheckConsistency(u, 1));
9749 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009750}
9751
Alexander Belopolsky40018472011-02-26 01:02:56 +00009752PyObject *
9753PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009754{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009756
9757 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009758 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009759 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009760 if (PyUnicode_READY(string) == -1) {
9761 Py_DECREF(string);
9762 return NULL;
9763 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764
Benjamin Petersonead6b532011-12-20 17:23:42 -06009765 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009767 if (PyUnicode_IS_ASCII(string))
9768 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009769 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009770 PyUnicode_GET_LENGTH(string), keepends);
9771 else
9772 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009773 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009774 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 break;
9776 case PyUnicode_2BYTE_KIND:
9777 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009778 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009779 PyUnicode_GET_LENGTH(string), keepends);
9780 break;
9781 case PyUnicode_4BYTE_KIND:
9782 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009783 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 PyUnicode_GET_LENGTH(string), keepends);
9785 break;
9786 default:
9787 assert(0);
9788 list = 0;
9789 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790 Py_DECREF(string);
9791 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009792}
9793
Alexander Belopolsky40018472011-02-26 01:02:56 +00009794static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009795split(PyObject *self,
9796 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009797 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009799 int kind1, kind2, kind;
9800 void *buf1, *buf2;
9801 Py_ssize_t len1, len2;
9802 PyObject* out;
9803
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009805 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 if (PyUnicode_READY(self) == -1)
9808 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009811 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009813 if (PyUnicode_IS_ASCII(self))
9814 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009815 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009816 PyUnicode_GET_LENGTH(self), maxcount
9817 );
9818 else
9819 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009820 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009821 PyUnicode_GET_LENGTH(self), maxcount
9822 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009823 case PyUnicode_2BYTE_KIND:
9824 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009825 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 PyUnicode_GET_LENGTH(self), maxcount
9827 );
9828 case PyUnicode_4BYTE_KIND:
9829 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009830 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 PyUnicode_GET_LENGTH(self), maxcount
9832 );
9833 default:
9834 assert(0);
9835 return NULL;
9836 }
9837
9838 if (PyUnicode_READY(substring) == -1)
9839 return NULL;
9840
9841 kind1 = PyUnicode_KIND(self);
9842 kind2 = PyUnicode_KIND(substring);
9843 kind = kind1 > kind2 ? kind1 : kind2;
9844 buf1 = PyUnicode_DATA(self);
9845 buf2 = PyUnicode_DATA(substring);
9846 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009847 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 if (!buf1)
9849 return NULL;
9850 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009851 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 if (!buf2) {
9853 if (kind1 != kind) PyMem_Free(buf1);
9854 return NULL;
9855 }
9856 len1 = PyUnicode_GET_LENGTH(self);
9857 len2 = PyUnicode_GET_LENGTH(substring);
9858
Benjamin Petersonead6b532011-12-20 17:23:42 -06009859 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009861 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9862 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009863 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009864 else
9865 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009866 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 break;
9868 case PyUnicode_2BYTE_KIND:
9869 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009870 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 break;
9872 case PyUnicode_4BYTE_KIND:
9873 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009874 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 break;
9876 default:
9877 out = NULL;
9878 }
9879 if (kind1 != kind)
9880 PyMem_Free(buf1);
9881 if (kind2 != kind)
9882 PyMem_Free(buf2);
9883 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009884}
9885
Alexander Belopolsky40018472011-02-26 01:02:56 +00009886static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009887rsplit(PyObject *self,
9888 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009889 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009890{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 int kind1, kind2, kind;
9892 void *buf1, *buf2;
9893 Py_ssize_t len1, len2;
9894 PyObject* out;
9895
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009896 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009897 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 if (PyUnicode_READY(self) == -1)
9900 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009901
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009903 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009904 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009905 if (PyUnicode_IS_ASCII(self))
9906 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009907 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009908 PyUnicode_GET_LENGTH(self), maxcount
9909 );
9910 else
9911 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009912 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009913 PyUnicode_GET_LENGTH(self), maxcount
9914 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 case PyUnicode_2BYTE_KIND:
9916 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009917 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 PyUnicode_GET_LENGTH(self), maxcount
9919 );
9920 case PyUnicode_4BYTE_KIND:
9921 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009922 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 PyUnicode_GET_LENGTH(self), maxcount
9924 );
9925 default:
9926 assert(0);
9927 return NULL;
9928 }
9929
9930 if (PyUnicode_READY(substring) == -1)
9931 return NULL;
9932
9933 kind1 = PyUnicode_KIND(self);
9934 kind2 = PyUnicode_KIND(substring);
9935 kind = kind1 > kind2 ? kind1 : kind2;
9936 buf1 = PyUnicode_DATA(self);
9937 buf2 = PyUnicode_DATA(substring);
9938 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009939 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 if (!buf1)
9941 return NULL;
9942 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009943 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009944 if (!buf2) {
9945 if (kind1 != kind) PyMem_Free(buf1);
9946 return NULL;
9947 }
9948 len1 = PyUnicode_GET_LENGTH(self);
9949 len2 = PyUnicode_GET_LENGTH(substring);
9950
Benjamin Petersonead6b532011-12-20 17:23:42 -06009951 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009953 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9954 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009955 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009956 else
9957 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009958 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 break;
9960 case PyUnicode_2BYTE_KIND:
9961 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009962 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 break;
9964 case PyUnicode_4BYTE_KIND:
9965 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009966 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 break;
9968 default:
9969 out = NULL;
9970 }
9971 if (kind1 != kind)
9972 PyMem_Free(buf1);
9973 if (kind2 != kind)
9974 PyMem_Free(buf2);
9975 return out;
9976}
9977
9978static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009979anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9980 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009982 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009984 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9985 return asciilib_find(buf1, len1, buf2, len2, offset);
9986 else
9987 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 case PyUnicode_2BYTE_KIND:
9989 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9990 case PyUnicode_4BYTE_KIND:
9991 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9992 }
9993 assert(0);
9994 return -1;
9995}
9996
9997static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009998anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9999 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010001 switch (kind) {
10002 case PyUnicode_1BYTE_KIND:
10003 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10004 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10005 else
10006 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10007 case PyUnicode_2BYTE_KIND:
10008 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10009 case PyUnicode_4BYTE_KIND:
10010 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10011 }
10012 assert(0);
10013 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010014}
10015
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010016static void
10017replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10018 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10019{
10020 int kind = PyUnicode_KIND(u);
10021 void *data = PyUnicode_DATA(u);
10022 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10023 if (kind == PyUnicode_1BYTE_KIND) {
10024 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10025 (Py_UCS1 *)data + len,
10026 u1, u2, maxcount);
10027 }
10028 else if (kind == PyUnicode_2BYTE_KIND) {
10029 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10030 (Py_UCS2 *)data + len,
10031 u1, u2, maxcount);
10032 }
10033 else {
10034 assert(kind == PyUnicode_4BYTE_KIND);
10035 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10036 (Py_UCS4 *)data + len,
10037 u1, u2, maxcount);
10038 }
10039}
10040
Alexander Belopolsky40018472011-02-26 01:02:56 +000010041static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042replace(PyObject *self, PyObject *str1,
10043 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010044{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 PyObject *u;
10046 char *sbuf = PyUnicode_DATA(self);
10047 char *buf1 = PyUnicode_DATA(str1);
10048 char *buf2 = PyUnicode_DATA(str2);
10049 int srelease = 0, release1 = 0, release2 = 0;
10050 int skind = PyUnicode_KIND(self);
10051 int kind1 = PyUnicode_KIND(str1);
10052 int kind2 = PyUnicode_KIND(str2);
10053 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10054 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10055 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010056 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010057 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010058
10059 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010060 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010062 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010063
Victor Stinner59de0ee2011-10-07 10:01:28 +020010064 if (str1 == str2)
10065 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066
Victor Stinner49a0a212011-10-12 23:46:10 +020010067 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010068 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10069 if (maxchar < maxchar_str1)
10070 /* substring too wide to be present */
10071 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010072 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10073 /* Replacing str1 with str2 may cause a maxchar reduction in the
10074 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010075 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010076 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010079 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010081 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010083 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010084 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010085 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010086
Victor Stinner69ed0f42013-04-09 21:48:24 +020010087 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010088 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010089 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010090 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010091 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010093 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010095
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010096 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10097 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010098 }
10099 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 int rkind = skind;
10101 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010102 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 if (kind1 < rkind) {
10105 /* widen substring */
10106 buf1 = _PyUnicode_AsKind(str1, rkind);
10107 if (!buf1) goto error;
10108 release1 = 1;
10109 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010110 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010111 if (i < 0)
10112 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 if (rkind > kind2) {
10114 /* widen replacement */
10115 buf2 = _PyUnicode_AsKind(str2, rkind);
10116 if (!buf2) goto error;
10117 release2 = 1;
10118 }
10119 else if (rkind < kind2) {
10120 /* widen self and buf1 */
10121 rkind = kind2;
10122 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010123 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 sbuf = _PyUnicode_AsKind(self, rkind);
10125 if (!sbuf) goto error;
10126 srelease = 1;
10127 buf1 = _PyUnicode_AsKind(str1, rkind);
10128 if (!buf1) goto error;
10129 release1 = 1;
10130 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010131 u = PyUnicode_New(slen, maxchar);
10132 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010134 assert(PyUnicode_KIND(u) == rkind);
10135 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010136
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010137 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010138 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010139 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010141 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010143
10144 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010145 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010146 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010148 if (i == -1)
10149 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010150 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010152 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010154 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010155 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010156 }
10157 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010159 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 int rkind = skind;
10161 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010164 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 buf1 = _PyUnicode_AsKind(str1, rkind);
10166 if (!buf1) goto error;
10167 release1 = 1;
10168 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010169 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010170 if (n == 0)
10171 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010173 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 buf2 = _PyUnicode_AsKind(str2, rkind);
10175 if (!buf2) goto error;
10176 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010177 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010179 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 rkind = kind2;
10181 sbuf = _PyUnicode_AsKind(self, rkind);
10182 if (!sbuf) goto error;
10183 srelease = 1;
10184 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010185 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 buf1 = _PyUnicode_AsKind(str1, rkind);
10187 if (!buf1) goto error;
10188 release1 = 1;
10189 }
10190 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10191 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010192 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 PyErr_SetString(PyExc_OverflowError,
10194 "replace string is too long");
10195 goto error;
10196 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010197 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010198 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010199 _Py_INCREF_UNICODE_EMPTY();
10200 if (!unicode_empty)
10201 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010202 u = unicode_empty;
10203 goto done;
10204 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010205 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 PyErr_SetString(PyExc_OverflowError,
10207 "replace string is too long");
10208 goto error;
10209 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010210 u = PyUnicode_New(new_size, maxchar);
10211 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010213 assert(PyUnicode_KIND(u) == rkind);
10214 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 ires = i = 0;
10216 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010217 while (n-- > 0) {
10218 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010220 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010222 if (j == -1)
10223 break;
10224 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010225 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 memcpy(res + rkind * ires,
10227 sbuf + rkind * i,
10228 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010230 }
10231 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010233 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010235 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010241 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010242 memcpy(res + rkind * ires,
10243 sbuf + rkind * i,
10244 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010245 }
10246 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010247 /* interleave */
10248 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010249 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010251 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010253 if (--n <= 0)
10254 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010255 memcpy(res + rkind * ires,
10256 sbuf + rkind * i,
10257 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 ires++;
10259 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010260 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010261 memcpy(res + rkind * ires,
10262 sbuf + rkind * i,
10263 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010264 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010265 }
10266
10267 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010268 unicode_adjust_maxchar(&u);
10269 if (u == NULL)
10270 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010271 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010272
10273 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 if (srelease)
10275 PyMem_FREE(sbuf);
10276 if (release1)
10277 PyMem_FREE(buf1);
10278 if (release2)
10279 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010280 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282
Benjamin Peterson29060642009-01-31 22:14:21 +000010283 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010284 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (srelease)
10286 PyMem_FREE(sbuf);
10287 if (release1)
10288 PyMem_FREE(buf1);
10289 if (release2)
10290 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010291 return unicode_result_unchanged(self);
10292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 error:
10294 if (srelease && sbuf)
10295 PyMem_FREE(sbuf);
10296 if (release1 && buf1)
10297 PyMem_FREE(buf1);
10298 if (release2 && buf2)
10299 PyMem_FREE(buf2);
10300 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301}
10302
10303/* --- Unicode Object Methods --------------------------------------------- */
10304
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010305PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010306 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307\n\
10308Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010309characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310
10311static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010312unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010314 if (PyUnicode_READY(self) == -1)
10315 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010316 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010317}
10318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010319PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010320 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321\n\
10322Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010323have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010324
10325static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010326unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010328 if (PyUnicode_READY(self) == -1)
10329 return NULL;
10330 if (PyUnicode_GET_LENGTH(self) == 0)
10331 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010332 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010333}
10334
Benjamin Petersond5890c82012-01-14 13:23:30 -050010335PyDoc_STRVAR(casefold__doc__,
10336 "S.casefold() -> str\n\
10337\n\
10338Return a version of S suitable for caseless comparisons.");
10339
10340static PyObject *
10341unicode_casefold(PyObject *self)
10342{
10343 if (PyUnicode_READY(self) == -1)
10344 return NULL;
10345 if (PyUnicode_IS_ASCII(self))
10346 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010347 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010348}
10349
10350
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010351/* Argument converter. Coerces to a single unicode character */
10352
10353static int
10354convert_uc(PyObject *obj, void *addr)
10355{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010357 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010358
Benjamin Peterson14339b62009-01-31 16:36:08 +000010359 uniobj = PyUnicode_FromObject(obj);
10360 if (uniobj == NULL) {
10361 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010362 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010363 return 0;
10364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010366 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010367 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010368 Py_DECREF(uniobj);
10369 return 0;
10370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010372 Py_DECREF(uniobj);
10373 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010374}
10375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010376PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010377 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010378\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010379Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010380done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010381
10382static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010383unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010385 Py_ssize_t marg, left;
10386 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 Py_UCS4 fillchar = ' ';
10388
Victor Stinnere9a29352011-10-01 02:14:59 +020010389 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391
Benjamin Petersonbac79492012-01-14 13:34:47 -050010392 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 return NULL;
10394
Victor Stinnerc4b49542011-12-11 22:44:26 +010010395 if (PyUnicode_GET_LENGTH(self) >= width)
10396 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397
Victor Stinnerc4b49542011-12-11 22:44:26 +010010398 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399 left = marg / 2 + (marg & width & 1);
10400
Victor Stinner9310abb2011-10-05 00:59:23 +020010401 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402}
10403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404/* This function assumes that str1 and str2 are readied by the caller. */
10405
Marc-André Lemburge5034372000-08-08 08:04:29 +000010406static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010407unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010408{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010409#define COMPARE(TYPE1, TYPE2) \
10410 do { \
10411 TYPE1* p1 = (TYPE1 *)data1; \
10412 TYPE2* p2 = (TYPE2 *)data2; \
10413 TYPE1* end = p1 + len; \
10414 Py_UCS4 c1, c2; \
10415 for (; p1 != end; p1++, p2++) { \
10416 c1 = *p1; \
10417 c2 = *p2; \
10418 if (c1 != c2) \
10419 return (c1 < c2) ? -1 : 1; \
10420 } \
10421 } \
10422 while (0)
10423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 int kind1, kind2;
10425 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010426 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010427
Victor Stinner90db9c42012-10-04 21:53:50 +020010428 /* a string is equal to itself */
10429 if (str1 == str2)
10430 return 0;
10431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 kind1 = PyUnicode_KIND(str1);
10433 kind2 = PyUnicode_KIND(str2);
10434 data1 = PyUnicode_DATA(str1);
10435 data2 = PyUnicode_DATA(str2);
10436 len1 = PyUnicode_GET_LENGTH(str1);
10437 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010438 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010439
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010440 switch(kind1) {
10441 case PyUnicode_1BYTE_KIND:
10442 {
10443 switch(kind2) {
10444 case PyUnicode_1BYTE_KIND:
10445 {
10446 int cmp = memcmp(data1, data2, len);
10447 /* normalize result of memcmp() into the range [-1; 1] */
10448 if (cmp < 0)
10449 return -1;
10450 if (cmp > 0)
10451 return 1;
10452 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010453 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010454 case PyUnicode_2BYTE_KIND:
10455 COMPARE(Py_UCS1, Py_UCS2);
10456 break;
10457 case PyUnicode_4BYTE_KIND:
10458 COMPARE(Py_UCS1, Py_UCS4);
10459 break;
10460 default:
10461 assert(0);
10462 }
10463 break;
10464 }
10465 case PyUnicode_2BYTE_KIND:
10466 {
10467 switch(kind2) {
10468 case PyUnicode_1BYTE_KIND:
10469 COMPARE(Py_UCS2, Py_UCS1);
10470 break;
10471 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010472 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010473 COMPARE(Py_UCS2, Py_UCS2);
10474 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010475 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010476 case PyUnicode_4BYTE_KIND:
10477 COMPARE(Py_UCS2, Py_UCS4);
10478 break;
10479 default:
10480 assert(0);
10481 }
10482 break;
10483 }
10484 case PyUnicode_4BYTE_KIND:
10485 {
10486 switch(kind2) {
10487 case PyUnicode_1BYTE_KIND:
10488 COMPARE(Py_UCS4, Py_UCS1);
10489 break;
10490 case PyUnicode_2BYTE_KIND:
10491 COMPARE(Py_UCS4, Py_UCS2);
10492 break;
10493 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010494 {
10495#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10496 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10497 /* normalize result of wmemcmp() into the range [-1; 1] */
10498 if (cmp < 0)
10499 return -1;
10500 if (cmp > 0)
10501 return 1;
10502#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010503 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010504#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010505 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010506 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010507 default:
10508 assert(0);
10509 }
10510 break;
10511 }
10512 default:
10513 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010514 }
10515
Victor Stinner770e19e2012-10-04 22:59:45 +020010516 if (len1 == len2)
10517 return 0;
10518 if (len1 < len2)
10519 return -1;
10520 else
10521 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010522
10523#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010524}
10525
Victor Stinnere5567ad2012-10-23 02:48:49 +020010526static int
10527unicode_compare_eq(PyObject *str1, PyObject *str2)
10528{
10529 int kind;
10530 void *data1, *data2;
10531 Py_ssize_t len;
10532 int cmp;
10533
10534 /* a string is equal to itself */
10535 if (str1 == str2)
10536 return 1;
10537
10538 len = PyUnicode_GET_LENGTH(str1);
10539 if (PyUnicode_GET_LENGTH(str2) != len)
10540 return 0;
10541 kind = PyUnicode_KIND(str1);
10542 if (PyUnicode_KIND(str2) != kind)
10543 return 0;
10544 data1 = PyUnicode_DATA(str1);
10545 data2 = PyUnicode_DATA(str2);
10546
10547 cmp = memcmp(data1, data2, len * kind);
10548 return (cmp == 0);
10549}
10550
10551
Alexander Belopolsky40018472011-02-26 01:02:56 +000010552int
10553PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010554{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10556 if (PyUnicode_READY(left) == -1 ||
10557 PyUnicode_READY(right) == -1)
10558 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010559 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010561 PyErr_Format(PyExc_TypeError,
10562 "Can't compare %.100s and %.100s",
10563 left->ob_type->tp_name,
10564 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010565 return -1;
10566}
10567
Martin v. Löwis5b222132007-06-10 09:51:05 +000010568int
10569PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10570{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 Py_ssize_t i;
10572 int kind;
10573 void *data;
10574 Py_UCS4 chr;
10575
Victor Stinner910337b2011-10-03 03:20:16 +020010576 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 if (PyUnicode_READY(uni) == -1)
10578 return -1;
10579 kind = PyUnicode_KIND(uni);
10580 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010581 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10583 if (chr != str[i])
10584 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010585 /* This check keeps Python strings that end in '\0' from comparing equal
10586 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010588 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010589 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010590 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010591 return 0;
10592}
10593
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010594
Benjamin Peterson29060642009-01-31 22:14:21 +000010595#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010596 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010597
Alexander Belopolsky40018472011-02-26 01:02:56 +000010598PyObject *
10599PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010600{
10601 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010602 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010603
Victor Stinnere5567ad2012-10-23 02:48:49 +020010604 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10605 Py_RETURN_NOTIMPLEMENTED;
10606
10607 if (PyUnicode_READY(left) == -1 ||
10608 PyUnicode_READY(right) == -1)
10609 return NULL;
10610
10611 if (op == Py_EQ || op == Py_NE) {
10612 result = unicode_compare_eq(left, right);
10613 if (op == Py_EQ)
10614 v = TEST_COND(result);
10615 else
10616 v = TEST_COND(!result);
10617 }
10618 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010619 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010620
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010621 /* Convert the return value to a Boolean */
10622 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010623 case Py_LE:
10624 v = TEST_COND(result <= 0);
10625 break;
10626 case Py_GE:
10627 v = TEST_COND(result >= 0);
10628 break;
10629 case Py_LT:
10630 v = TEST_COND(result == -1);
10631 break;
10632 case Py_GT:
10633 v = TEST_COND(result == 1);
10634 break;
10635 default:
10636 PyErr_BadArgument();
10637 return NULL;
10638 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010639 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010640 Py_INCREF(v);
10641 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010642}
10643
Alexander Belopolsky40018472011-02-26 01:02:56 +000010644int
10645PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010646{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010648 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 void *buf1, *buf2;
10650 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010651 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010652
10653 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010654 sub = PyUnicode_FromObject(element);
10655 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010656 PyErr_Format(PyExc_TypeError,
10657 "'in <string>' requires string as left operand, not %s",
10658 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010659 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010660 }
10661
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010663 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664 Py_DECREF(sub);
10665 return -1;
10666 }
10667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 kind1 = PyUnicode_KIND(str);
10669 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 buf1 = PyUnicode_DATA(str);
10671 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010672 if (kind2 != kind1) {
10673 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010674 Py_DECREF(sub);
10675 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010676 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010677 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010678 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010679 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 if (!buf2) {
10681 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010682 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 return -1;
10684 }
10685 len1 = PyUnicode_GET_LENGTH(str);
10686 len2 = PyUnicode_GET_LENGTH(sub);
10687
Victor Stinner77282cb2013-04-14 19:22:47 +020010688 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 case PyUnicode_1BYTE_KIND:
10690 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10691 break;
10692 case PyUnicode_2BYTE_KIND:
10693 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10694 break;
10695 case PyUnicode_4BYTE_KIND:
10696 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10697 break;
10698 default:
10699 result = -1;
10700 assert(0);
10701 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010702
10703 Py_DECREF(str);
10704 Py_DECREF(sub);
10705
Victor Stinner77282cb2013-04-14 19:22:47 +020010706 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 PyMem_Free(buf2);
10708
Guido van Rossum403d68b2000-03-13 15:55:09 +000010709 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010710}
10711
Guido van Rossumd57fd912000-03-10 22:53:23 +000010712/* Concat to string or Unicode object giving a new Unicode object. */
10713
Alexander Belopolsky40018472011-02-26 01:02:56 +000010714PyObject *
10715PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010718 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010719 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720
10721 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010722 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010724 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010725 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010727 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010728
10729 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010730 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010731 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010733 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010734 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010735 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010736 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010737 }
10738
Victor Stinner488fa492011-12-12 00:01:39 +010010739 u_len = PyUnicode_GET_LENGTH(u);
10740 v_len = PyUnicode_GET_LENGTH(v);
10741 if (u_len > PY_SSIZE_T_MAX - v_len) {
10742 PyErr_SetString(PyExc_OverflowError,
10743 "strings are too large to concat");
10744 goto onError;
10745 }
10746 new_len = u_len + v_len;
10747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010749 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010750 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010751
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010753 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010755 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010756 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10757 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758 Py_DECREF(u);
10759 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010760 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762
Benjamin Peterson29060642009-01-31 22:14:21 +000010763 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764 Py_XDECREF(u);
10765 Py_XDECREF(v);
10766 return NULL;
10767}
10768
Walter Dörwald1ab83302007-05-18 17:15:44 +000010769void
Victor Stinner23e56682011-10-03 03:54:37 +020010770PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010771{
Victor Stinner23e56682011-10-03 03:54:37 +020010772 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010773 Py_UCS4 maxchar, maxchar2;
10774 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010775
10776 if (p_left == NULL) {
10777 if (!PyErr_Occurred())
10778 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010779 return;
10780 }
Victor Stinner23e56682011-10-03 03:54:37 +020010781 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020010782 if (right == NULL || left == NULL
10783 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010784 if (!PyErr_Occurred())
10785 PyErr_BadInternalCall();
10786 goto error;
10787 }
10788
Benjamin Petersonbac79492012-01-14 13:34:47 -050010789 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010790 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010791 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010792 goto error;
10793
Victor Stinner488fa492011-12-12 00:01:39 +010010794 /* Shortcuts */
10795 if (left == unicode_empty) {
10796 Py_DECREF(left);
10797 Py_INCREF(right);
10798 *p_left = right;
10799 return;
10800 }
10801 if (right == unicode_empty)
10802 return;
10803
10804 left_len = PyUnicode_GET_LENGTH(left);
10805 right_len = PyUnicode_GET_LENGTH(right);
10806 if (left_len > PY_SSIZE_T_MAX - right_len) {
10807 PyErr_SetString(PyExc_OverflowError,
10808 "strings are too large to concat");
10809 goto error;
10810 }
10811 new_len = left_len + right_len;
10812
10813 if (unicode_modifiable(left)
10814 && PyUnicode_CheckExact(right)
10815 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010816 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10817 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010818 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010819 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010820 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10821 {
10822 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010823 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010010824 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020010825
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010826 /* copy 'right' into the newly allocated area of 'left' */
10827 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010828 }
Victor Stinner488fa492011-12-12 00:01:39 +010010829 else {
10830 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10831 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010832 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010833
Victor Stinner488fa492011-12-12 00:01:39 +010010834 /* Concat the two Unicode strings */
10835 res = PyUnicode_New(new_len, maxchar);
10836 if (res == NULL)
10837 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010838 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10839 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010840 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010841 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010010842 }
10843 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010844 return;
10845
10846error:
Victor Stinner488fa492011-12-12 00:01:39 +010010847 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010848}
10849
10850void
10851PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10852{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010853 PyUnicode_Append(pleft, right);
10854 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010855}
10856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010857PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010858 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010860Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010861string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010862interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863
10864static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010865unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010866{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010867 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010868 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010869 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010870 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010871 int kind1, kind2, kind;
10872 void *buf1, *buf2;
10873 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874
Jesus Ceaac451502011-04-20 17:09:23 +020010875 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10876 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010877 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010879 kind1 = PyUnicode_KIND(self);
10880 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020010881 if (kind2 > kind1) {
10882 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010883 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020010884 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010885 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010886 buf1 = PyUnicode_DATA(self);
10887 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010888 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010889 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010890 if (!buf2) {
10891 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010892 return NULL;
10893 }
10894 len1 = PyUnicode_GET_LENGTH(self);
10895 len2 = PyUnicode_GET_LENGTH(substring);
10896
10897 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010898 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010899 case PyUnicode_1BYTE_KIND:
10900 iresult = ucs1lib_count(
10901 ((Py_UCS1*)buf1) + start, end - start,
10902 buf2, len2, PY_SSIZE_T_MAX
10903 );
10904 break;
10905 case PyUnicode_2BYTE_KIND:
10906 iresult = ucs2lib_count(
10907 ((Py_UCS2*)buf1) + start, end - start,
10908 buf2, len2, PY_SSIZE_T_MAX
10909 );
10910 break;
10911 case PyUnicode_4BYTE_KIND:
10912 iresult = ucs4lib_count(
10913 ((Py_UCS4*)buf1) + start, end - start,
10914 buf2, len2, PY_SSIZE_T_MAX
10915 );
10916 break;
10917 default:
10918 assert(0); iresult = 0;
10919 }
10920
10921 result = PyLong_FromSsize_t(iresult);
10922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010923 if (kind2 != kind)
10924 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925
10926 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010927
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928 return result;
10929}
10930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010931PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010932 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010934Encode S using the codec registered for encoding. Default encoding\n\
10935is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010936handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010937a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10938'xmlcharrefreplace' as well as any other name registered with\n\
10939codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940
10941static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010942unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010944 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945 char *encoding = NULL;
10946 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010947
Benjamin Peterson308d6372009-09-18 21:42:35 +000010948 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10949 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010951 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010952}
10953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010954PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956\n\
10957Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010958If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959
10960static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010961unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010963 Py_ssize_t i, j, line_pos, src_len, incr;
10964 Py_UCS4 ch;
10965 PyObject *u;
10966 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010968 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010969 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
10971 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010972 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973
Antoine Pitrou22425222011-10-04 19:10:51 +020010974 if (PyUnicode_READY(self) == -1)
10975 return NULL;
10976
Thomas Wouters7e474022000-07-16 12:04:32 +000010977 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010978 src_len = PyUnicode_GET_LENGTH(self);
10979 i = j = line_pos = 0;
10980 kind = PyUnicode_KIND(self);
10981 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010982 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010983 for (; i < src_len; i++) {
10984 ch = PyUnicode_READ(kind, src_data, i);
10985 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010986 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010987 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010988 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010989 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010990 goto overflow;
10991 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010993 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010994 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010997 goto overflow;
10998 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011000 if (ch == '\n' || ch == '\r')
11001 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011003 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011004 if (!found)
11005 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011006
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011008 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009 if (!u)
11010 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011011 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012
Antoine Pitroue71d5742011-10-04 15:55:09 +020011013 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014
Antoine Pitroue71d5742011-10-04 15:55:09 +020011015 for (; i < src_len; i++) {
11016 ch = PyUnicode_READ(kind, src_data, i);
11017 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011018 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011019 incr = tabsize - (line_pos % tabsize);
11020 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011021 FILL(kind, dest_data, ' ', j, incr);
11022 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011023 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011024 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011026 line_pos++;
11027 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011028 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011029 if (ch == '\n' || ch == '\r')
11030 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011032 }
11033 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011034 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011035
Antoine Pitroue71d5742011-10-04 15:55:09 +020011036 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011037 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11038 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039}
11040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011041PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043\n\
11044Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011045such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046arguments start and end are interpreted as in slice notation.\n\
11047\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011048Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049
11050static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011051unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011053 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011054 Py_ssize_t start;
11055 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011056 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057
Jesus Ceaac451502011-04-20 17:09:23 +020011058 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11059 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061
Christian Heimesd47802e2013-06-29 21:33:36 +020011062 if (PyUnicode_READY(self) == -1) {
11063 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011064 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011065 }
11066 if (PyUnicode_READY(substring) == -1) {
11067 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011070
Victor Stinner7931d9a2011-11-04 00:22:48 +010011071 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
11073 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011075 if (result == -2)
11076 return NULL;
11077
Christian Heimes217cfd12007-12-02 14:31:20 +000011078 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079}
11080
11081static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011082unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011084 void *data;
11085 enum PyUnicode_Kind kind;
11086 Py_UCS4 ch;
11087 PyObject *res;
11088
11089 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11090 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011092 }
11093 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11094 PyErr_SetString(PyExc_IndexError, "string index out of range");
11095 return NULL;
11096 }
11097 kind = PyUnicode_KIND(self);
11098 data = PyUnicode_DATA(self);
11099 ch = PyUnicode_READ(kind, data, index);
11100 if (ch < 256)
11101 return get_latin1_char(ch);
11102
11103 res = PyUnicode_New(1, ch);
11104 if (res == NULL)
11105 return NULL;
11106 kind = PyUnicode_KIND(res);
11107 data = PyUnicode_DATA(res);
11108 PyUnicode_WRITE(kind, data, 0, ch);
11109 assert(_PyUnicode_CheckConsistency(res, 1));
11110 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111}
11112
Guido van Rossumc2504932007-09-18 19:42:40 +000011113/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011114 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011115static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011116unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117{
Guido van Rossumc2504932007-09-18 19:42:40 +000011118 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011119 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011120
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011121#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011122 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011123#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124 if (_PyUnicode_HASH(self) != -1)
11125 return _PyUnicode_HASH(self);
11126 if (PyUnicode_READY(self) == -1)
11127 return -1;
11128 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011129 /*
11130 We make the hash of the empty string be 0, rather than using
11131 (prefix ^ suffix), since this slightly obfuscates the hash secret
11132 */
11133 if (len == 0) {
11134 _PyUnicode_HASH(self) = 0;
11135 return 0;
11136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137
11138 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011139#define HASH(P) \
11140 x ^= (Py_uhash_t) *P << 7; \
11141 while (--len >= 0) \
11142 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143
Georg Brandl2fb477c2012-02-21 00:33:36 +010011144 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 switch (PyUnicode_KIND(self)) {
11146 case PyUnicode_1BYTE_KIND: {
11147 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11148 HASH(c);
11149 break;
11150 }
11151 case PyUnicode_2BYTE_KIND: {
11152 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11153 HASH(s);
11154 break;
11155 }
11156 default: {
11157 Py_UCS4 *l;
11158 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11159 "Impossible switch case in unicode_hash");
11160 l = PyUnicode_4BYTE_DATA(self);
11161 HASH(l);
11162 break;
11163 }
11164 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011165 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11166 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167
Guido van Rossumc2504932007-09-18 19:42:40 +000011168 if (x == -1)
11169 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011171 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011175PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011178Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179
11180static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011181unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011183 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011184 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011185 Py_ssize_t start;
11186 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187
Jesus Ceaac451502011-04-20 17:09:23 +020011188 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11189 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191
Christian Heimesd47a0452013-06-29 21:21:37 +020011192 if (PyUnicode_READY(self) == -1) {
11193 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011194 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011195 }
11196 if (PyUnicode_READY(substring) == -1) {
11197 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011199 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011200
Victor Stinner7931d9a2011-11-04 00:22:48 +010011201 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 if (result == -2)
11206 return NULL;
11207
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208 if (result < 0) {
11209 PyErr_SetString(PyExc_ValueError, "substring not found");
11210 return NULL;
11211 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011212
Christian Heimes217cfd12007-12-02 14:31:20 +000011213 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214}
11215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011216PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011219Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011220at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221
11222static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011223unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 Py_ssize_t i, length;
11226 int kind;
11227 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228 int cased;
11229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 if (PyUnicode_READY(self) == -1)
11231 return NULL;
11232 length = PyUnicode_GET_LENGTH(self);
11233 kind = PyUnicode_KIND(self);
11234 data = PyUnicode_DATA(self);
11235
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 if (length == 1)
11238 return PyBool_FromLong(
11239 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011241 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011243 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011244
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 for (i = 0; i < length; i++) {
11247 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011248
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11250 return PyBool_FromLong(0);
11251 else if (!cased && Py_UNICODE_ISLOWER(ch))
11252 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011254 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255}
11256
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011257PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011258 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011260Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011261at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262
11263static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011264unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011266 Py_ssize_t i, length;
11267 int kind;
11268 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269 int cased;
11270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 if (PyUnicode_READY(self) == -1)
11272 return NULL;
11273 length = PyUnicode_GET_LENGTH(self);
11274 kind = PyUnicode_KIND(self);
11275 data = PyUnicode_DATA(self);
11276
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 if (length == 1)
11279 return PyBool_FromLong(
11280 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011282 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011285
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 for (i = 0; i < length; i++) {
11288 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011289
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11291 return PyBool_FromLong(0);
11292 else if (!cased && Py_UNICODE_ISUPPER(ch))
11293 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011295 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296}
11297
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011298PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011299 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011301Return True if S is a titlecased string and there is at least one\n\
11302character in S, i.e. upper- and titlecase characters may only\n\
11303follow uncased characters and lowercase characters only cased ones.\n\
11304Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305
11306static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011307unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 Py_ssize_t i, length;
11310 int kind;
11311 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 int cased, previous_is_cased;
11313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (PyUnicode_READY(self) == -1)
11315 return NULL;
11316 length = PyUnicode_GET_LENGTH(self);
11317 kind = PyUnicode_KIND(self);
11318 data = PyUnicode_DATA(self);
11319
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 if (length == 1) {
11322 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11323 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11324 (Py_UNICODE_ISUPPER(ch) != 0));
11325 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011327 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011329 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011330
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331 cased = 0;
11332 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 for (i = 0; i < length; i++) {
11334 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011335
Benjamin Peterson29060642009-01-31 22:14:21 +000011336 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11337 if (previous_is_cased)
11338 return PyBool_FromLong(0);
11339 previous_is_cased = 1;
11340 cased = 1;
11341 }
11342 else if (Py_UNICODE_ISLOWER(ch)) {
11343 if (!previous_is_cased)
11344 return PyBool_FromLong(0);
11345 previous_is_cased = 1;
11346 cased = 1;
11347 }
11348 else
11349 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011351 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352}
11353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011354PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011357Return True if all characters in S are whitespace\n\
11358and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359
11360static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011361unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 Py_ssize_t i, length;
11364 int kind;
11365 void *data;
11366
11367 if (PyUnicode_READY(self) == -1)
11368 return NULL;
11369 length = PyUnicode_GET_LENGTH(self);
11370 kind = PyUnicode_KIND(self);
11371 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011372
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 if (length == 1)
11375 return PyBool_FromLong(
11376 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011378 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011379 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011380 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 for (i = 0; i < length; i++) {
11383 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011384 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011385 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011387 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388}
11389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011390PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011391 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011392\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011393Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011394and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011395
11396static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011397unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 Py_ssize_t i, length;
11400 int kind;
11401 void *data;
11402
11403 if (PyUnicode_READY(self) == -1)
11404 return NULL;
11405 length = PyUnicode_GET_LENGTH(self);
11406 kind = PyUnicode_KIND(self);
11407 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011408
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011409 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 if (length == 1)
11411 return PyBool_FromLong(
11412 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011413
11414 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011416 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011418 for (i = 0; i < length; i++) {
11419 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011421 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011422 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011423}
11424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011425PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011427\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011428Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011429and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011430
11431static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011432unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 int kind;
11435 void *data;
11436 Py_ssize_t len, i;
11437
11438 if (PyUnicode_READY(self) == -1)
11439 return NULL;
11440
11441 kind = PyUnicode_KIND(self);
11442 data = PyUnicode_DATA(self);
11443 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011444
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011445 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 if (len == 1) {
11447 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11448 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11449 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011450
11451 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011453 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011455 for (i = 0; i < len; i++) {
11456 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011457 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011459 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011460 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011461}
11462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011463PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011464 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011466Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011467False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468
11469static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011470unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 Py_ssize_t i, length;
11473 int kind;
11474 void *data;
11475
11476 if (PyUnicode_READY(self) == -1)
11477 return NULL;
11478 length = PyUnicode_GET_LENGTH(self);
11479 kind = PyUnicode_KIND(self);
11480 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011483 if (length == 1)
11484 return PyBool_FromLong(
11485 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011487 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 for (i = 0; i < length; i++) {
11492 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011495 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496}
11497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011498PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011501Return True if all characters in S are digits\n\
11502and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
11504static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011505unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 Py_ssize_t i, length;
11508 int kind;
11509 void *data;
11510
11511 if (PyUnicode_READY(self) == -1)
11512 return NULL;
11513 length = PyUnicode_GET_LENGTH(self);
11514 kind = PyUnicode_KIND(self);
11515 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 if (length == 1) {
11519 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11520 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11521 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011523 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 for (i = 0; i < length; i++) {
11528 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011529 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011531 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532}
11533
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011534PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011537Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011538False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539
11540static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011541unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011543 Py_ssize_t i, length;
11544 int kind;
11545 void *data;
11546
11547 if (PyUnicode_READY(self) == -1)
11548 return NULL;
11549 length = PyUnicode_GET_LENGTH(self);
11550 kind = PyUnicode_KIND(self);
11551 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 if (length == 1)
11555 return PyBool_FromLong(
11556 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011558 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011560 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011561
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 for (i = 0; i < length; i++) {
11563 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011566 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567}
11568
Martin v. Löwis47383402007-08-15 07:32:56 +000011569int
11570PyUnicode_IsIdentifier(PyObject *self)
11571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 int kind;
11573 void *data;
11574 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011575 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 if (PyUnicode_READY(self) == -1) {
11578 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 }
11581
11582 /* Special case for empty strings */
11583 if (PyUnicode_GET_LENGTH(self) == 0)
11584 return 0;
11585 kind = PyUnicode_KIND(self);
11586 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011587
11588 /* PEP 3131 says that the first character must be in
11589 XID_Start and subsequent characters in XID_Continue,
11590 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011591 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011592 letters, digits, underscore). However, given the current
11593 definition of XID_Start and XID_Continue, it is sufficient
11594 to check just for these, except that _ must be allowed
11595 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011597 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011598 return 0;
11599
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011600 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011602 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011603 return 1;
11604}
11605
11606PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011608\n\
11609Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011610to the language definition.\n\
11611\n\
11612Use keyword.iskeyword() to test for reserved identifiers\n\
11613such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011614
11615static PyObject*
11616unicode_isidentifier(PyObject *self)
11617{
11618 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11619}
11620
Georg Brandl559e5d72008-06-11 18:37:52 +000011621PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011622 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011623\n\
11624Return True if all characters in S are considered\n\
11625printable in repr() or S is empty, False otherwise.");
11626
11627static PyObject*
11628unicode_isprintable(PyObject *self)
11629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 Py_ssize_t i, length;
11631 int kind;
11632 void *data;
11633
11634 if (PyUnicode_READY(self) == -1)
11635 return NULL;
11636 length = PyUnicode_GET_LENGTH(self);
11637 kind = PyUnicode_KIND(self);
11638 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011639
11640 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641 if (length == 1)
11642 return PyBool_FromLong(
11643 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 for (i = 0; i < length; i++) {
11646 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011647 Py_RETURN_FALSE;
11648 }
11649 }
11650 Py_RETURN_TRUE;
11651}
11652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011653PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011654 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655\n\
11656Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011657iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011658
11659static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011660unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011662 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663}
11664
Martin v. Löwis18e16552006-02-15 17:27:45 +000011665static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011666unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 if (PyUnicode_READY(self) == -1)
11669 return -1;
11670 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671}
11672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011673PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011674 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011676Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011677done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678
11679static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011680unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011682 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 Py_UCS4 fillchar = ' ';
11684
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011685 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686 return NULL;
11687
Benjamin Petersonbac79492012-01-14 13:34:47 -050011688 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011689 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
Victor Stinnerc4b49542011-12-11 22:44:26 +010011691 if (PyUnicode_GET_LENGTH(self) >= width)
11692 return unicode_result_unchanged(self);
11693
11694 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695}
11696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011697PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011698 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011700Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
11702static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011703unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011705 if (PyUnicode_READY(self) == -1)
11706 return NULL;
11707 if (PyUnicode_IS_ASCII(self))
11708 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011709 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710}
11711
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011712#define LEFTSTRIP 0
11713#define RIGHTSTRIP 1
11714#define BOTHSTRIP 2
11715
11716/* Arrays indexed by above */
11717static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11718
11719#define STRIPNAME(i) (stripformat[i]+3)
11720
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011721/* externally visible for str.strip(unicode) */
11722PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011723_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 void *data;
11726 int kind;
11727 Py_ssize_t i, j, len;
11728 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011729 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11732 return NULL;
11733
11734 kind = PyUnicode_KIND(self);
11735 data = PyUnicode_DATA(self);
11736 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011737 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11739 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011740 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011741
Benjamin Peterson14339b62009-01-31 16:36:08 +000011742 i = 0;
11743 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011744 while (i < len) {
11745 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11746 if (!BLOOM(sepmask, ch))
11747 break;
11748 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11749 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011750 i++;
11751 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011752 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011753
Benjamin Peterson14339b62009-01-31 16:36:08 +000011754 j = len;
11755 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011756 j--;
11757 while (j >= i) {
11758 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11759 if (!BLOOM(sepmask, ch))
11760 break;
11761 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11762 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011764 }
11765
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011767 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768
Victor Stinner7931d9a2011-11-04 00:22:48 +010011769 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770}
11771
11772PyObject*
11773PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11774{
11775 unsigned char *data;
11776 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011777 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778
Victor Stinnerde636f32011-10-01 03:55:54 +020011779 if (PyUnicode_READY(self) == -1)
11780 return NULL;
11781
Victor Stinner684d5fd2012-05-03 02:32:34 +020011782 length = PyUnicode_GET_LENGTH(self);
11783 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011784
Victor Stinner684d5fd2012-05-03 02:32:34 +020011785 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011786 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787
Victor Stinnerde636f32011-10-01 03:55:54 +020011788 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011789 PyErr_SetString(PyExc_IndexError, "string index out of range");
11790 return NULL;
11791 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011792 if (start >= length || end < start)
11793 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011794
Victor Stinner684d5fd2012-05-03 02:32:34 +020011795 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011796 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011797 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011798 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011799 }
11800 else {
11801 kind = PyUnicode_KIND(self);
11802 data = PyUnicode_1BYTE_DATA(self);
11803 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011804 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011805 length);
11806 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808
11809static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011810do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812 Py_ssize_t len, i, j;
11813
11814 if (PyUnicode_READY(self) == -1)
11815 return NULL;
11816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818
Victor Stinnercc7af722013-04-09 22:39:24 +020011819 if (PyUnicode_IS_ASCII(self)) {
11820 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
11821
11822 i = 0;
11823 if (striptype != RIGHTSTRIP) {
11824 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020011825 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020011826 if (!_Py_ascii_whitespace[ch])
11827 break;
11828 i++;
11829 }
11830 }
11831
11832 j = len;
11833 if (striptype != LEFTSTRIP) {
11834 j--;
11835 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020011836 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020011837 if (!_Py_ascii_whitespace[ch])
11838 break;
11839 j--;
11840 }
11841 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011842 }
11843 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011844 else {
11845 int kind = PyUnicode_KIND(self);
11846 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011847
Victor Stinnercc7af722013-04-09 22:39:24 +020011848 i = 0;
11849 if (striptype != RIGHTSTRIP) {
11850 while (i < len) {
11851 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11852 if (!Py_UNICODE_ISSPACE(ch))
11853 break;
11854 i++;
11855 }
Victor Stinner9c79e412013-04-09 22:21:08 +020011856 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011857
11858 j = len;
11859 if (striptype != LEFTSTRIP) {
11860 j--;
11861 while (j >= i) {
11862 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11863 if (!Py_UNICODE_ISSPACE(ch))
11864 break;
11865 j--;
11866 }
11867 j++;
11868 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011869 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011870
Victor Stinner7931d9a2011-11-04 00:22:48 +010011871 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872}
11873
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011874
11875static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011876do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011877{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011878 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011879
Serhiy Storchakac6792272013-10-19 21:03:34 +030011880 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011881 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011882
Benjamin Peterson14339b62009-01-31 16:36:08 +000011883 if (sep != NULL && sep != Py_None) {
11884 if (PyUnicode_Check(sep))
11885 return _PyUnicode_XStrip(self, striptype, sep);
11886 else {
11887 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 "%s arg must be None or str",
11889 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011890 return NULL;
11891 }
11892 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011893
Benjamin Peterson14339b62009-01-31 16:36:08 +000011894 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011895}
11896
11897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011898PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011900\n\
11901Return a copy of the string S with leading and trailing\n\
11902whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011903If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011904
11905static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011906unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011907{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011908 if (PyTuple_GET_SIZE(args) == 0)
11909 return do_strip(self, BOTHSTRIP); /* Common case */
11910 else
11911 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011912}
11913
11914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011915PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011917\n\
11918Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011919If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011920
11921static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011922unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011923{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011924 if (PyTuple_GET_SIZE(args) == 0)
11925 return do_strip(self, LEFTSTRIP); /* Common case */
11926 else
11927 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011928}
11929
11930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011931PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011933\n\
11934Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011935If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011936
11937static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011938unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011939{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011940 if (PyTuple_GET_SIZE(args) == 0)
11941 return do_strip(self, RIGHTSTRIP); /* Common case */
11942 else
11943 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011944}
11945
11946
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011948unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011950 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952
Serhiy Storchaka05997252013-01-26 12:14:02 +020011953 if (len < 1)
11954 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955
Victor Stinnerc4b49542011-12-11 22:44:26 +010011956 /* no repeat, return original string */
11957 if (len == 1)
11958 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011959
Benjamin Petersonbac79492012-01-14 13:34:47 -050011960 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 return NULL;
11962
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011963 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011964 PyErr_SetString(PyExc_OverflowError,
11965 "repeated string is too long");
11966 return NULL;
11967 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011969
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011970 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971 if (!u)
11972 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011973 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 if (PyUnicode_GET_LENGTH(str) == 1) {
11976 const int kind = PyUnicode_KIND(str);
11977 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011978 if (kind == PyUnicode_1BYTE_KIND) {
11979 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011980 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011981 }
11982 else if (kind == PyUnicode_2BYTE_KIND) {
11983 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011984 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011985 ucs2[n] = fill_char;
11986 } else {
11987 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11988 assert(kind == PyUnicode_4BYTE_KIND);
11989 for (n = 0; n < len; ++n)
11990 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011991 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 }
11993 else {
11994 /* number of characters copied this far */
11995 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011996 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 char *to = (char *) PyUnicode_DATA(u);
11998 Py_MEMCPY(to, PyUnicode_DATA(str),
11999 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012000 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 n = (done <= nchars-done) ? done : nchars-done;
12002 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012003 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005 }
12006
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012007 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012008 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009}
12010
Alexander Belopolsky40018472011-02-26 01:02:56 +000012011PyObject *
12012PyUnicode_Replace(PyObject *obj,
12013 PyObject *subobj,
12014 PyObject *replobj,
12015 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016{
12017 PyObject *self;
12018 PyObject *str1;
12019 PyObject *str2;
12020 PyObject *result;
12021
12022 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012023 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012025 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012026 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012027 Py_DECREF(self);
12028 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012029 }
12030 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012031 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 Py_DECREF(self);
12033 Py_DECREF(str1);
12034 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012036 if (PyUnicode_READY(self) == -1 ||
12037 PyUnicode_READY(str1) == -1 ||
12038 PyUnicode_READY(str2) == -1)
12039 result = NULL;
12040 else
12041 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042 Py_DECREF(self);
12043 Py_DECREF(str1);
12044 Py_DECREF(str2);
12045 return result;
12046}
12047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012048PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012049 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050\n\
12051Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012052old replaced by new. If the optional argument count is\n\
12053given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054
12055static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 PyObject *str1;
12059 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012060 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061 PyObject *result;
12062
Martin v. Löwis18e16552006-02-15 17:27:45 +000012063 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012065 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012066 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012068 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 return NULL;
12070 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012071 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012072 Py_DECREF(str1);
12073 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012074 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012075 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12076 result = NULL;
12077 else
12078 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
12080 Py_DECREF(str1);
12081 Py_DECREF(str2);
12082 return result;
12083}
12084
Alexander Belopolsky40018472011-02-26 01:02:56 +000012085static PyObject *
12086unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012088 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 Py_ssize_t isize;
12090 Py_ssize_t osize, squote, dquote, i, o;
12091 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012092 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012096 return NULL;
12097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012098 isize = PyUnicode_GET_LENGTH(unicode);
12099 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012101 /* Compute length of output, quote characters, and
12102 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012103 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104 max = 127;
12105 squote = dquote = 0;
12106 ikind = PyUnicode_KIND(unicode);
12107 for (i = 0; i < isize; i++) {
12108 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12109 switch (ch) {
12110 case '\'': squote++; osize++; break;
12111 case '"': dquote++; osize++; break;
12112 case '\\': case '\t': case '\r': case '\n':
12113 osize += 2; break;
12114 default:
12115 /* Fast-path ASCII */
12116 if (ch < ' ' || ch == 0x7f)
12117 osize += 4; /* \xHH */
12118 else if (ch < 0x7f)
12119 osize++;
12120 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12121 osize++;
12122 max = ch > max ? ch : max;
12123 }
12124 else if (ch < 0x100)
12125 osize += 4; /* \xHH */
12126 else if (ch < 0x10000)
12127 osize += 6; /* \uHHHH */
12128 else
12129 osize += 10; /* \uHHHHHHHH */
12130 }
12131 }
12132
12133 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012134 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012136 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 if (dquote)
12138 /* Both squote and dquote present. Use squote,
12139 and escape them */
12140 osize += squote;
12141 else
12142 quote = '"';
12143 }
Victor Stinner55c08782013-04-14 18:45:39 +020012144 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145
12146 repr = PyUnicode_New(osize, max);
12147 if (repr == NULL)
12148 return NULL;
12149 okind = PyUnicode_KIND(repr);
12150 odata = PyUnicode_DATA(repr);
12151
12152 PyUnicode_WRITE(okind, odata, 0, quote);
12153 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012154 if (unchanged) {
12155 _PyUnicode_FastCopyCharacters(repr, 1,
12156 unicode, 0,
12157 isize);
12158 }
12159 else {
12160 for (i = 0, o = 1; i < isize; i++) {
12161 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162
Victor Stinner55c08782013-04-14 18:45:39 +020012163 /* Escape quotes and backslashes */
12164 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012165 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012167 continue;
12168 }
12169
12170 /* Map special whitespace to '\t', \n', '\r' */
12171 if (ch == '\t') {
12172 PyUnicode_WRITE(okind, odata, o++, '\\');
12173 PyUnicode_WRITE(okind, odata, o++, 't');
12174 }
12175 else if (ch == '\n') {
12176 PyUnicode_WRITE(okind, odata, o++, '\\');
12177 PyUnicode_WRITE(okind, odata, o++, 'n');
12178 }
12179 else if (ch == '\r') {
12180 PyUnicode_WRITE(okind, odata, o++, '\\');
12181 PyUnicode_WRITE(okind, odata, o++, 'r');
12182 }
12183
12184 /* Map non-printable US ASCII to '\xhh' */
12185 else if (ch < ' ' || ch == 0x7F) {
12186 PyUnicode_WRITE(okind, odata, o++, '\\');
12187 PyUnicode_WRITE(okind, odata, o++, 'x');
12188 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12189 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12190 }
12191
12192 /* Copy ASCII characters as-is */
12193 else if (ch < 0x7F) {
12194 PyUnicode_WRITE(okind, odata, o++, ch);
12195 }
12196
12197 /* Non-ASCII characters */
12198 else {
12199 /* Map Unicode whitespace and control characters
12200 (categories Z* and C* except ASCII space)
12201 */
12202 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12203 PyUnicode_WRITE(okind, odata, o++, '\\');
12204 /* Map 8-bit characters to '\xhh' */
12205 if (ch <= 0xff) {
12206 PyUnicode_WRITE(okind, odata, o++, 'x');
12207 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12208 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12209 }
12210 /* Map 16-bit characters to '\uxxxx' */
12211 else if (ch <= 0xffff) {
12212 PyUnicode_WRITE(okind, odata, o++, 'u');
12213 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12214 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12215 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12216 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12217 }
12218 /* Map 21-bit characters to '\U00xxxxxx' */
12219 else {
12220 PyUnicode_WRITE(okind, odata, o++, 'U');
12221 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12222 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12223 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12224 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12225 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12226 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12227 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12228 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12229 }
12230 }
12231 /* Copy characters as-is */
12232 else {
12233 PyUnicode_WRITE(okind, odata, o++, ch);
12234 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012235 }
12236 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012239 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012240 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241}
12242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012243PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245\n\
12246Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012247such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248arguments start and end are interpreted as in slice notation.\n\
12249\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012250Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
12252static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012255 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012256 Py_ssize_t start;
12257 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012258 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
Jesus Ceaac451502011-04-20 17:09:23 +020012260 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12261 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263
Christian Heimesea71a522013-06-29 21:17:34 +020012264 if (PyUnicode_READY(self) == -1) {
12265 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012267 }
12268 if (PyUnicode_READY(substring) == -1) {
12269 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272
Victor Stinner7931d9a2011-11-04 00:22:48 +010012273 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274
12275 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277 if (result == -2)
12278 return NULL;
12279
Christian Heimes217cfd12007-12-02 14:31:20 +000012280 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281}
12282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012283PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012286Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287
12288static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012291 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012292 Py_ssize_t start;
12293 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012294 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295
Jesus Ceaac451502011-04-20 17:09:23 +020012296 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12297 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012298 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012299
Christian Heimesea71a522013-06-29 21:17:34 +020012300 if (PyUnicode_READY(self) == -1) {
12301 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012303 }
12304 if (PyUnicode_READY(substring) == -1) {
12305 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012307 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308
Victor Stinner7931d9a2011-11-04 00:22:48 +010012309 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012310
12311 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 if (result == -2)
12314 return NULL;
12315
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316 if (result < 0) {
12317 PyErr_SetString(PyExc_ValueError, "substring not found");
12318 return NULL;
12319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320
Christian Heimes217cfd12007-12-02 14:31:20 +000012321 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322}
12323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012324PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012325 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012326\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012327Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012328done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012329
12330static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012331unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012332{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012333 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 Py_UCS4 fillchar = ' ';
12335
Victor Stinnere9a29352011-10-01 02:14:59 +020012336 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012338
Benjamin Petersonbac79492012-01-14 13:34:47 -050012339 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340 return NULL;
12341
Victor Stinnerc4b49542011-12-11 22:44:26 +010012342 if (PyUnicode_GET_LENGTH(self) >= width)
12343 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344
Victor Stinnerc4b49542011-12-11 22:44:26 +010012345 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346}
12347
Alexander Belopolsky40018472011-02-26 01:02:56 +000012348PyObject *
12349PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350{
12351 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012352
Guido van Rossumd57fd912000-03-10 22:53:23 +000012353 s = PyUnicode_FromObject(s);
12354 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012355 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012356 if (sep != NULL) {
12357 sep = PyUnicode_FromObject(sep);
12358 if (sep == NULL) {
12359 Py_DECREF(s);
12360 return NULL;
12361 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012362 }
12363
Victor Stinner9310abb2011-10-05 00:59:23 +020012364 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365
12366 Py_DECREF(s);
12367 Py_XDECREF(sep);
12368 return result;
12369}
12370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012371PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012372 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012373\n\
12374Return a list of the words in S, using sep as the\n\
12375delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012376splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012377whitespace string is a separator and empty strings are\n\
12378removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012379
12380static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012381unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012383 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012384 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012385 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012386
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012387 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12388 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012389 return NULL;
12390
12391 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012392 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012394 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012396 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397}
12398
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399PyObject *
12400PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12401{
12402 PyObject* str_obj;
12403 PyObject* sep_obj;
12404 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 int kind1, kind2, kind;
12406 void *buf1 = NULL, *buf2 = NULL;
12407 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012408
12409 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012410 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012411 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012412 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012413 if (!sep_obj) {
12414 Py_DECREF(str_obj);
12415 return NULL;
12416 }
12417 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12418 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012419 Py_DECREF(str_obj);
12420 return NULL;
12421 }
12422
Victor Stinner14f8f022011-10-05 20:58:25 +020012423 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012425 kind = Py_MAX(kind1, kind2);
12426 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012428 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012429 if (!buf1)
12430 goto onError;
12431 buf2 = PyUnicode_DATA(sep_obj);
12432 if (kind2 != kind)
12433 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12434 if (!buf2)
12435 goto onError;
12436 len1 = PyUnicode_GET_LENGTH(str_obj);
12437 len2 = PyUnicode_GET_LENGTH(sep_obj);
12438
Benjamin Petersonead6b532011-12-20 17:23:42 -060012439 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012441 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12442 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12443 else
12444 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 break;
12446 case PyUnicode_2BYTE_KIND:
12447 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12448 break;
12449 case PyUnicode_4BYTE_KIND:
12450 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12451 break;
12452 default:
12453 assert(0);
12454 out = 0;
12455 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456
12457 Py_DECREF(sep_obj);
12458 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459 if (kind1 != kind)
12460 PyMem_Free(buf1);
12461 if (kind2 != kind)
12462 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463
12464 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012465 onError:
12466 Py_DECREF(sep_obj);
12467 Py_DECREF(str_obj);
12468 if (kind1 != kind && buf1)
12469 PyMem_Free(buf1);
12470 if (kind2 != kind && buf2)
12471 PyMem_Free(buf2);
12472 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012473}
12474
12475
12476PyObject *
12477PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12478{
12479 PyObject* str_obj;
12480 PyObject* sep_obj;
12481 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 int kind1, kind2, kind;
12483 void *buf1 = NULL, *buf2 = NULL;
12484 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012485
12486 str_obj = PyUnicode_FromObject(str_in);
12487 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012488 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012489 sep_obj = PyUnicode_FromObject(sep_in);
12490 if (!sep_obj) {
12491 Py_DECREF(str_obj);
12492 return NULL;
12493 }
12494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 kind1 = PyUnicode_KIND(str_in);
12496 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012497 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498 buf1 = PyUnicode_DATA(str_in);
12499 if (kind1 != kind)
12500 buf1 = _PyUnicode_AsKind(str_in, kind);
12501 if (!buf1)
12502 goto onError;
12503 buf2 = PyUnicode_DATA(sep_obj);
12504 if (kind2 != kind)
12505 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12506 if (!buf2)
12507 goto onError;
12508 len1 = PyUnicode_GET_LENGTH(str_obj);
12509 len2 = PyUnicode_GET_LENGTH(sep_obj);
12510
Benjamin Petersonead6b532011-12-20 17:23:42 -060012511 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012513 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12514 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12515 else
12516 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517 break;
12518 case PyUnicode_2BYTE_KIND:
12519 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12520 break;
12521 case PyUnicode_4BYTE_KIND:
12522 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12523 break;
12524 default:
12525 assert(0);
12526 out = 0;
12527 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012528
12529 Py_DECREF(sep_obj);
12530 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012531 if (kind1 != kind)
12532 PyMem_Free(buf1);
12533 if (kind2 != kind)
12534 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012535
12536 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 onError:
12538 Py_DECREF(sep_obj);
12539 Py_DECREF(str_obj);
12540 if (kind1 != kind && buf1)
12541 PyMem_Free(buf1);
12542 if (kind2 != kind && buf2)
12543 PyMem_Free(buf2);
12544 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012545}
12546
12547PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012548 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012550Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012551the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012552found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012553
12554static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012555unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556{
Victor Stinner9310abb2011-10-05 00:59:23 +020012557 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012558}
12559
12560PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012561 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012562\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012563Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012564the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012565separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012566
12567static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012568unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012569{
Victor Stinner9310abb2011-10-05 00:59:23 +020012570 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012571}
12572
Alexander Belopolsky40018472011-02-26 01:02:56 +000012573PyObject *
12574PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012575{
12576 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012577
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012578 s = PyUnicode_FromObject(s);
12579 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012580 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012581 if (sep != NULL) {
12582 sep = PyUnicode_FromObject(sep);
12583 if (sep == NULL) {
12584 Py_DECREF(s);
12585 return NULL;
12586 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012587 }
12588
Victor Stinner9310abb2011-10-05 00:59:23 +020012589 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012590
12591 Py_DECREF(s);
12592 Py_XDECREF(sep);
12593 return result;
12594}
12595
12596PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012597 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012598\n\
12599Return a list of the words in S, using sep as the\n\
12600delimiter string, starting at the end of the string and\n\
12601working to the front. If maxsplit is given, at most maxsplit\n\
12602splits are done. If sep is not specified, any whitespace string\n\
12603is a separator.");
12604
12605static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012606unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012607{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012608 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012609 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012610 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012611
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012612 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12613 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012614 return NULL;
12615
12616 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012617 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012618 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012619 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012620 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012621 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012622}
12623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012624PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012625 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626\n\
12627Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012628Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012629is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630
12631static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012632unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012634 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012635 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012637 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12638 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639 return NULL;
12640
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012641 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642}
12643
12644static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012645PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012647 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648}
12649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012650PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012651 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652\n\
12653Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012654and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655
12656static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012657unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012659 if (PyUnicode_READY(self) == -1)
12660 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012661 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662}
12663
Larry Hastings31826802013-10-19 00:09:25 -070012664/*[clinic]
12665module str
Georg Brandlceee0772007-11-27 23:48:05 +000012666
Larry Hastings31826802013-10-19 00:09:25 -070012667@staticmethod
12668str.maketrans as unicode_maketrans
12669
12670 x: object
12671
12672 y: unicode=NULL
12673
12674 z: unicode=NULL
12675
12676 /
12677
12678Return a translation table usable for str.translate().
12679
12680If there is only one argument, it must be a dictionary mapping Unicode
12681ordinals (integers) or characters to Unicode ordinals, strings or None.
12682Character keys will be then converted to ordinals.
12683If there are two arguments, they must be strings of equal length, and
12684in the resulting dictionary, each character in x will be mapped to the
12685character at the same position in y. If there is a third argument, it
12686must be a string, whose characters will be mapped to None in the result.
12687[clinic]*/
12688
12689PyDoc_STRVAR(unicode_maketrans__doc__,
12690"Return a translation table usable for str.translate().\n"
12691"\n"
12692"str.maketrans(x, y=None, z=None)\n"
12693"\n"
12694"If there is only one argument, it must be a dictionary mapping Unicode\n"
12695"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12696"Character keys will be then converted to ordinals.\n"
12697"If there are two arguments, they must be strings of equal length, and\n"
12698"in the resulting dictionary, each character in x will be mapped to the\n"
12699"character at the same position in y. If there is a third argument, it\n"
12700"must be a string, whose characters will be mapped to None in the result.");
12701
12702#define UNICODE_MAKETRANS_METHODDEF \
12703 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12704
12705static PyObject *
12706unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
12707
12708static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012709unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012710{
Larry Hastings31826802013-10-19 00:09:25 -070012711 PyObject *return_value = NULL;
12712 PyObject *x;
12713 PyObject *y = NULL;
12714 PyObject *z = NULL;
12715
12716 if (!PyArg_ParseTuple(args,
12717 "O|UU:maketrans",
12718 &x, &y, &z))
12719 goto exit;
12720 return_value = unicode_maketrans_impl(x, y, z);
12721
12722exit:
12723 return return_value;
12724}
12725
12726static PyObject *
12727unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
12728/*[clinic checksum: 137db9c3199e7906b7967009f511c24fa3235b5f]*/
12729{
Georg Brandlceee0772007-11-27 23:48:05 +000012730 PyObject *new = NULL, *key, *value;
12731 Py_ssize_t i = 0;
12732 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012733
Georg Brandlceee0772007-11-27 23:48:05 +000012734 new = PyDict_New();
12735 if (!new)
12736 return NULL;
12737 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 int x_kind, y_kind, z_kind;
12739 void *x_data, *y_data, *z_data;
12740
Georg Brandlceee0772007-11-27 23:48:05 +000012741 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012742 if (!PyUnicode_Check(x)) {
12743 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12744 "be a string if there is a second argument");
12745 goto err;
12746 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012748 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12749 "arguments must have equal length");
12750 goto err;
12751 }
12752 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753 x_kind = PyUnicode_KIND(x);
12754 y_kind = PyUnicode_KIND(y);
12755 x_data = PyUnicode_DATA(x);
12756 y_data = PyUnicode_DATA(y);
12757 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12758 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012759 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012760 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012761 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012762 if (!value) {
12763 Py_DECREF(key);
12764 goto err;
12765 }
Georg Brandlceee0772007-11-27 23:48:05 +000012766 res = PyDict_SetItem(new, key, value);
12767 Py_DECREF(key);
12768 Py_DECREF(value);
12769 if (res < 0)
12770 goto err;
12771 }
12772 /* create entries for deleting chars in z */
12773 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 z_kind = PyUnicode_KIND(z);
12775 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012776 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012778 if (!key)
12779 goto err;
12780 res = PyDict_SetItem(new, key, Py_None);
12781 Py_DECREF(key);
12782 if (res < 0)
12783 goto err;
12784 }
12785 }
12786 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012787 int kind;
12788 void *data;
12789
Georg Brandlceee0772007-11-27 23:48:05 +000012790 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012791 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012792 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12793 "to maketrans it must be a dict");
12794 goto err;
12795 }
12796 /* copy entries into the new dict, converting string keys to int keys */
12797 while (PyDict_Next(x, &i, &key, &value)) {
12798 if (PyUnicode_Check(key)) {
12799 /* convert string keys to integer keys */
12800 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012801 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012802 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12803 "table must be of length 1");
12804 goto err;
12805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 kind = PyUnicode_KIND(key);
12807 data = PyUnicode_DATA(key);
12808 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012809 if (!newkey)
12810 goto err;
12811 res = PyDict_SetItem(new, newkey, value);
12812 Py_DECREF(newkey);
12813 if (res < 0)
12814 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012815 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012816 /* just keep integer keys */
12817 if (PyDict_SetItem(new, key, value) < 0)
12818 goto err;
12819 } else {
12820 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12821 "be strings or integers");
12822 goto err;
12823 }
12824 }
12825 }
12826 return new;
12827 err:
12828 Py_DECREF(new);
12829 return NULL;
12830}
12831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012832PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834\n\
12835Return a copy of the string S, where all characters have been mapped\n\
12836through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012837Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012838Unmapped characters are left untouched. Characters mapped to None\n\
12839are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840
12841static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845}
12846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012847PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012848 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012850Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851
12852static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012853unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012854{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012855 if (PyUnicode_READY(self) == -1)
12856 return NULL;
12857 if (PyUnicode_IS_ASCII(self))
12858 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012859 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860}
12861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012862PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012863 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012864\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012865Pad a numeric string S with zeros on the left, to fill a field\n\
12866of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867
12868static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012869unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012870{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012871 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012872 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012873 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 int kind;
12875 void *data;
12876 Py_UCS4 chr;
12877
Martin v. Löwis18e16552006-02-15 17:27:45 +000012878 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012879 return NULL;
12880
Benjamin Petersonbac79492012-01-14 13:34:47 -050012881 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012882 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883
Victor Stinnerc4b49542011-12-11 22:44:26 +010012884 if (PyUnicode_GET_LENGTH(self) >= width)
12885 return unicode_result_unchanged(self);
12886
12887 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888
12889 u = pad(self, fill, 0, '0');
12890
Walter Dörwald068325e2002-04-15 13:36:47 +000012891 if (u == NULL)
12892 return NULL;
12893
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012894 kind = PyUnicode_KIND(u);
12895 data = PyUnicode_DATA(u);
12896 chr = PyUnicode_READ(kind, data, fill);
12897
12898 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 PyUnicode_WRITE(kind, data, 0, chr);
12901 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012902 }
12903
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012904 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012905 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907
12908#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012909static PyObject *
12910unicode__decimal2ascii(PyObject *self)
12911{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012912 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012913}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012914#endif
12915
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012916PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012917 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012919Return True if S starts with the specified prefix, False otherwise.\n\
12920With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012921With optional end, stop comparing S at that position.\n\
12922prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923
12924static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012925unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012926 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012927{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012928 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012929 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012930 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012931 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012932 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933
Jesus Ceaac451502011-04-20 17:09:23 +020012934 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012935 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012936 if (PyTuple_Check(subobj)) {
12937 Py_ssize_t i;
12938 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012939 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012940 if (substring == NULL)
12941 return NULL;
12942 result = tailmatch(self, substring, start, end, -1);
12943 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012944 if (result == -1)
12945 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012946 if (result) {
12947 Py_RETURN_TRUE;
12948 }
12949 }
12950 /* nothing matched */
12951 Py_RETURN_FALSE;
12952 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012953 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012954 if (substring == NULL) {
12955 if (PyErr_ExceptionMatches(PyExc_TypeError))
12956 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12957 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012958 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012959 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012960 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012961 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012962 if (result == -1)
12963 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012964 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012965}
12966
12967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012968PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012969 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012970\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012971Return True if S ends with the specified suffix, False otherwise.\n\
12972With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012973With optional end, stop comparing S at that position.\n\
12974suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012975
12976static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012977unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012978 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012980 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012981 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012982 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012983 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012984 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985
Jesus Ceaac451502011-04-20 17:09:23 +020012986 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012987 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012988 if (PyTuple_Check(subobj)) {
12989 Py_ssize_t i;
12990 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012991 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012992 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012993 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012994 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012995 result = tailmatch(self, substring, start, end, +1);
12996 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012997 if (result == -1)
12998 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012999 if (result) {
13000 Py_RETURN_TRUE;
13001 }
13002 }
13003 Py_RETURN_FALSE;
13004 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013005 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013006 if (substring == NULL) {
13007 if (PyErr_ExceptionMatches(PyExc_TypeError))
13008 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13009 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013010 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013011 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013012 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013013 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013014 if (result == -1)
13015 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013016 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013017}
13018
Victor Stinner202fdca2012-05-07 12:47:02 +020013019Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013020_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013021{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013022 if (!writer->readonly)
13023 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13024 else {
13025 /* Copy-on-write mode: set buffer size to 0 so
13026 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13027 * next write. */
13028 writer->size = 0;
13029 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013030 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13031 writer->data = PyUnicode_DATA(writer->buffer);
13032 writer->kind = PyUnicode_KIND(writer->buffer);
13033}
13034
Victor Stinnerd3f08822012-05-29 12:57:52 +020013035void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013036_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013037{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013038 memset(writer, 0, sizeof(*writer));
13039#ifdef Py_DEBUG
13040 writer->kind = 5; /* invalid kind */
13041#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013042 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013043}
13044
Victor Stinnerd3f08822012-05-29 12:57:52 +020013045int
13046_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13047 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013048{
13049 Py_ssize_t newlen;
13050 PyObject *newbuffer;
13051
Victor Stinnerd3f08822012-05-29 12:57:52 +020013052 assert(length > 0);
13053
Victor Stinner202fdca2012-05-07 12:47:02 +020013054 if (length > PY_SSIZE_T_MAX - writer->pos) {
13055 PyErr_NoMemory();
13056 return -1;
13057 }
13058 newlen = writer->pos + length;
13059
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013060 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013061
Victor Stinnerd3f08822012-05-29 12:57:52 +020013062 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013063 assert(!writer->readonly);
13064 if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / 4)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013065 /* overallocate 25% to limit the number of resize */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013066 newlen += newlen / 4;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013067 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013068 if (newlen < writer->min_length)
13069 newlen = writer->min_length;
13070
Victor Stinnerd3f08822012-05-29 12:57:52 +020013071 writer->buffer = PyUnicode_New(newlen, maxchar);
13072 if (writer->buffer == NULL)
13073 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013074 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013075 else if (newlen > writer->size) {
13076 if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / 4)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013077 /* overallocate 25% to limit the number of resize */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013078 newlen += newlen / 4;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013079 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013080 if (newlen < writer->min_length)
13081 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013082
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013083 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013084 /* resize + widen */
13085 newbuffer = PyUnicode_New(newlen, maxchar);
13086 if (newbuffer == NULL)
13087 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013088 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13089 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013090 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013091 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013092 }
13093 else {
13094 newbuffer = resize_compact(writer->buffer, newlen);
13095 if (newbuffer == NULL)
13096 return -1;
13097 }
13098 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013099 }
13100 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013101 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013102 newbuffer = PyUnicode_New(writer->size, maxchar);
13103 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013104 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013105 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13106 writer->buffer, 0, writer->pos);
13107 Py_DECREF(writer->buffer);
13108 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013109 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013110 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013111 return 0;
13112}
13113
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013114Py_LOCAL_INLINE(int)
13115_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013116{
13117 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13118 return -1;
13119 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13120 writer->pos++;
13121 return 0;
13122}
13123
13124int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013125_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13126{
13127 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13128}
13129
13130int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013131_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13132{
13133 Py_UCS4 maxchar;
13134 Py_ssize_t len;
13135
13136 if (PyUnicode_READY(str) == -1)
13137 return -1;
13138 len = PyUnicode_GET_LENGTH(str);
13139 if (len == 0)
13140 return 0;
13141 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13142 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013143 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013144 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013145 Py_INCREF(str);
13146 writer->buffer = str;
13147 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013148 writer->pos += len;
13149 return 0;
13150 }
13151 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13152 return -1;
13153 }
13154 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13155 str, 0, len);
13156 writer->pos += len;
13157 return 0;
13158}
13159
Victor Stinnere215d962012-10-06 23:03:36 +020013160int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013161_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13162 Py_ssize_t start, Py_ssize_t end)
13163{
13164 Py_UCS4 maxchar;
13165 Py_ssize_t len;
13166
13167 if (PyUnicode_READY(str) == -1)
13168 return -1;
13169
13170 assert(0 <= start);
13171 assert(end <= PyUnicode_GET_LENGTH(str));
13172 assert(start <= end);
13173
13174 if (end == 0)
13175 return 0;
13176
13177 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13178 return _PyUnicodeWriter_WriteStr(writer, str);
13179
13180 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13181 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13182 else
13183 maxchar = writer->maxchar;
13184 len = end - start;
13185
13186 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13187 return -1;
13188
13189 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13190 str, start, len);
13191 writer->pos += len;
13192 return 0;
13193}
13194
13195int
Victor Stinnere215d962012-10-06 23:03:36 +020013196_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
13197{
13198 Py_UCS4 maxchar;
13199
13200 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13201 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13202 return -1;
13203 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13204 writer->pos += len;
13205 return 0;
13206}
13207
Victor Stinnerd3f08822012-05-29 12:57:52 +020013208PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013209_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013210{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013211 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013212 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013213 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013214 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013215 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013216 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013217 str = writer->buffer;
13218 writer->buffer = NULL;
13219 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13220 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013221 }
13222 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13223 PyObject *newbuffer;
13224 newbuffer = resize_compact(writer->buffer, writer->pos);
13225 if (newbuffer == NULL) {
13226 Py_DECREF(writer->buffer);
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013227 writer->buffer = NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013228 return NULL;
13229 }
13230 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013231 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013232 str = writer->buffer;
13233 writer->buffer = NULL;
13234 assert(_PyUnicode_CheckConsistency(str, 1));
13235 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013236}
13237
Victor Stinnerd3f08822012-05-29 12:57:52 +020013238void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013239_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013240{
13241 Py_CLEAR(writer->buffer);
13242}
13243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013244#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013245
13246PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013247 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013248\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013249Return a formatted version of S, using substitutions from args and kwargs.\n\
13250The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013251
Eric Smith27bbca62010-11-04 17:06:58 +000013252PyDoc_STRVAR(format_map__doc__,
13253 "S.format_map(mapping) -> str\n\
13254\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013255Return a formatted version of S, using substitutions from mapping.\n\
13256The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013257
Eric Smith4a7d76d2008-05-30 18:10:19 +000013258static PyObject *
13259unicode__format__(PyObject* self, PyObject* args)
13260{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013261 PyObject *format_spec;
13262 _PyUnicodeWriter writer;
13263 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013264
13265 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13266 return NULL;
13267
Victor Stinnerd3f08822012-05-29 12:57:52 +020013268 if (PyUnicode_READY(self) == -1)
13269 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013270 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013271 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13272 self, format_spec, 0,
13273 PyUnicode_GET_LENGTH(format_spec));
13274 if (ret == -1) {
13275 _PyUnicodeWriter_Dealloc(&writer);
13276 return NULL;
13277 }
13278 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013279}
13280
Eric Smith8c663262007-08-25 02:26:07 +000013281PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013283\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013284Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013285
13286static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013287unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013288{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013289 Py_ssize_t size;
13290
13291 /* If it's a compact object, account for base structure +
13292 character data. */
13293 if (PyUnicode_IS_COMPACT_ASCII(v))
13294 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13295 else if (PyUnicode_IS_COMPACT(v))
13296 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013297 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013298 else {
13299 /* If it is a two-block object, account for base object, and
13300 for character block if present. */
13301 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013302 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013303 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013304 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013305 }
13306 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013307 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013308 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013309 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013310 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013311 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013312
13313 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013314}
13315
13316PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013317 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013318
13319static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013320unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013321{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013322 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013323 if (!copy)
13324 return NULL;
13325 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013326}
13327
Guido van Rossumd57fd912000-03-10 22:53:23 +000013328static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013329 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013330 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013331 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13332 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013333 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13334 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013335 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013336 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13337 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13338 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13339 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13340 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013341 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013342 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13343 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13344 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013345 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013346 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13347 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13348 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013349 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013350 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013351 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013352 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013353 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13354 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13355 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13356 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13357 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13358 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13359 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13360 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13361 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13362 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13363 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13364 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13365 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13366 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013367 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013368 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013369 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013370 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013371 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013372 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013373 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013374 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013375#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013376 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013377 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013378#endif
13379
Benjamin Peterson14339b62009-01-31 16:36:08 +000013380 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013381 {NULL, NULL}
13382};
13383
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013384static PyObject *
13385unicode_mod(PyObject *v, PyObject *w)
13386{
Brian Curtindfc80e32011-08-10 20:28:54 -050013387 if (!PyUnicode_Check(v))
13388 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013389 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013390}
13391
13392static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013393 0, /*nb_add*/
13394 0, /*nb_subtract*/
13395 0, /*nb_multiply*/
13396 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013397};
13398
Guido van Rossumd57fd912000-03-10 22:53:23 +000013399static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013400 (lenfunc) unicode_length, /* sq_length */
13401 PyUnicode_Concat, /* sq_concat */
13402 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13403 (ssizeargfunc) unicode_getitem, /* sq_item */
13404 0, /* sq_slice */
13405 0, /* sq_ass_item */
13406 0, /* sq_ass_slice */
13407 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013408};
13409
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013410static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013411unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013412{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013413 if (PyUnicode_READY(self) == -1)
13414 return NULL;
13415
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013416 if (PyIndex_Check(item)) {
13417 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013418 if (i == -1 && PyErr_Occurred())
13419 return NULL;
13420 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013421 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013422 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013423 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013424 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013425 PyObject *result;
13426 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013427 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013428 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013430 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013431 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013432 return NULL;
13433 }
13434
13435 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013436 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013437 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013438 slicelength == PyUnicode_GET_LENGTH(self)) {
13439 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013440 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013441 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013442 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013443 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013444 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013445 src_kind = PyUnicode_KIND(self);
13446 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013447 if (!PyUnicode_IS_ASCII(self)) {
13448 kind_limit = kind_maxchar_limit(src_kind);
13449 max_char = 0;
13450 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13451 ch = PyUnicode_READ(src_kind, src_data, cur);
13452 if (ch > max_char) {
13453 max_char = ch;
13454 if (max_char >= kind_limit)
13455 break;
13456 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013457 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013458 }
Victor Stinner55c99112011-10-13 01:17:06 +020013459 else
13460 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013461 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013462 if (result == NULL)
13463 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013464 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013465 dest_data = PyUnicode_DATA(result);
13466
13467 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013468 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13469 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013470 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013471 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013472 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013473 } else {
13474 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13475 return NULL;
13476 }
13477}
13478
13479static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013480 (lenfunc)unicode_length, /* mp_length */
13481 (binaryfunc)unicode_subscript, /* mp_subscript */
13482 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013483};
13484
Guido van Rossumd57fd912000-03-10 22:53:23 +000013485
Guido van Rossumd57fd912000-03-10 22:53:23 +000013486/* Helpers for PyUnicode_Format() */
13487
Victor Stinnera47082312012-10-04 02:19:54 +020013488struct unicode_formatter_t {
13489 PyObject *args;
13490 int args_owned;
13491 Py_ssize_t arglen, argidx;
13492 PyObject *dict;
13493
13494 enum PyUnicode_Kind fmtkind;
13495 Py_ssize_t fmtcnt, fmtpos;
13496 void *fmtdata;
13497 PyObject *fmtstr;
13498
13499 _PyUnicodeWriter writer;
13500};
13501
13502struct unicode_format_arg_t {
13503 Py_UCS4 ch;
13504 int flags;
13505 Py_ssize_t width;
13506 int prec;
13507 int sign;
13508};
13509
Guido van Rossumd57fd912000-03-10 22:53:23 +000013510static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013511unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013512{
Victor Stinnera47082312012-10-04 02:19:54 +020013513 Py_ssize_t argidx = ctx->argidx;
13514
13515 if (argidx < ctx->arglen) {
13516 ctx->argidx++;
13517 if (ctx->arglen < 0)
13518 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013519 else
Victor Stinnera47082312012-10-04 02:19:54 +020013520 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013521 }
13522 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013524 return NULL;
13525}
13526
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013527/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013528
Victor Stinnera47082312012-10-04 02:19:54 +020013529/* Format a float into the writer if the writer is not NULL, or into *p_output
13530 otherwise.
13531
13532 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533static int
Victor Stinnera47082312012-10-04 02:19:54 +020013534formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13535 PyObject **p_output,
13536 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013537{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013538 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013539 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013540 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013541 int prec;
13542 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013543
Guido van Rossumd57fd912000-03-10 22:53:23 +000013544 x = PyFloat_AsDouble(v);
13545 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013546 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013547
Victor Stinnera47082312012-10-04 02:19:54 +020013548 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013549 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013551
Victor Stinnera47082312012-10-04 02:19:54 +020013552 if (arg->flags & F_ALT)
13553 dtoa_flags = Py_DTSF_ALT;
13554 else
13555 dtoa_flags = 0;
13556 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013557 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558 return -1;
13559 len = strlen(p);
13560 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013561 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13562 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013563 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013564 }
Victor Stinner184252a2012-06-16 02:57:41 +020013565 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013566 writer->pos += len;
13567 }
13568 else
13569 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013570 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013571 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013572}
13573
Victor Stinnerd0880d52012-04-27 23:40:13 +020013574/* formatlong() emulates the format codes d, u, o, x and X, and
13575 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13576 * Python's regular ints.
13577 * Return value: a new PyUnicodeObject*, or NULL if error.
13578 * The output string is of the form
13579 * "-"? ("0x" | "0X")? digit+
13580 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13581 * set in flags. The case of hex digits will be correct,
13582 * There will be at least prec digits, zero-filled on the left if
13583 * necessary to get that many.
13584 * val object to be converted
13585 * flags bitmask of format flags; only F_ALT is looked at
13586 * prec minimum number of digits; 0-fill on left if needed
13587 * type a character in [duoxX]; u acts the same as d
13588 *
13589 * CAUTION: o, x and X conversions on regular ints can never
13590 * produce a '-' sign, but can for Python's unbounded ints.
13591 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013592static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013593formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013594{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013595 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013596 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013597 Py_ssize_t i;
13598 int sign; /* 1 if '-', else 0 */
13599 int len; /* number of characters */
13600 Py_ssize_t llen;
13601 int numdigits; /* len == numnondigits + numdigits */
13602 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013603 int prec = arg->prec;
13604 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013605
Victor Stinnerd0880d52012-04-27 23:40:13 +020013606 /* Avoid exceeding SSIZE_T_MAX */
13607 if (prec > INT_MAX-3) {
13608 PyErr_SetString(PyExc_OverflowError,
13609 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013610 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013611 }
13612
13613 assert(PyLong_Check(val));
13614
13615 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013616 default:
13617 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013618 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013619 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013620 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013621 /* int and int subclasses should print numerically when a numeric */
13622 /* format code is used (see issue18780) */
13623 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013624 break;
13625 case 'o':
13626 numnondigits = 2;
13627 result = PyNumber_ToBase(val, 8);
13628 break;
13629 case 'x':
13630 case 'X':
13631 numnondigits = 2;
13632 result = PyNumber_ToBase(val, 16);
13633 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013634 }
13635 if (!result)
13636 return NULL;
13637
13638 assert(unicode_modifiable(result));
13639 assert(PyUnicode_IS_READY(result));
13640 assert(PyUnicode_IS_ASCII(result));
13641
13642 /* To modify the string in-place, there can only be one reference. */
13643 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013644 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013645 PyErr_BadInternalCall();
13646 return NULL;
13647 }
13648 buf = PyUnicode_DATA(result);
13649 llen = PyUnicode_GET_LENGTH(result);
13650 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013651 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013652 PyErr_SetString(PyExc_ValueError,
13653 "string too large in _PyBytes_FormatLong");
13654 return NULL;
13655 }
13656 len = (int)llen;
13657 sign = buf[0] == '-';
13658 numnondigits += sign;
13659 numdigits = len - numnondigits;
13660 assert(numdigits > 0);
13661
13662 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013663 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013664 (type == 'o' || type == 'x' || type == 'X'))) {
13665 assert(buf[sign] == '0');
13666 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13667 buf[sign+1] == 'o');
13668 numnondigits -= 2;
13669 buf += 2;
13670 len -= 2;
13671 if (sign)
13672 buf[0] = '-';
13673 assert(len == numnondigits + numdigits);
13674 assert(numdigits > 0);
13675 }
13676
13677 /* Fill with leading zeroes to meet minimum width. */
13678 if (prec > numdigits) {
13679 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13680 numnondigits + prec);
13681 char *b1;
13682 if (!r1) {
13683 Py_DECREF(result);
13684 return NULL;
13685 }
13686 b1 = PyBytes_AS_STRING(r1);
13687 for (i = 0; i < numnondigits; ++i)
13688 *b1++ = *buf++;
13689 for (i = 0; i < prec - numdigits; i++)
13690 *b1++ = '0';
13691 for (i = 0; i < numdigits; i++)
13692 *b1++ = *buf++;
13693 *b1 = '\0';
13694 Py_DECREF(result);
13695 result = r1;
13696 buf = PyBytes_AS_STRING(result);
13697 len = numnondigits + prec;
13698 }
13699
13700 /* Fix up case for hex conversions. */
13701 if (type == 'X') {
13702 /* Need to convert all lower case letters to upper case.
13703 and need to convert 0x to 0X (and -0x to -0X). */
13704 for (i = 0; i < len; i++)
13705 if (buf[i] >= 'a' && buf[i] <= 'x')
13706 buf[i] -= 'a'-'A';
13707 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013708 if (!PyUnicode_Check(result)
13709 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013710 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013711 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013712 Py_DECREF(result);
13713 result = unicode;
13714 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013715 else if (len != PyUnicode_GET_LENGTH(result)) {
13716 if (PyUnicode_Resize(&result, len) < 0)
13717 Py_CLEAR(result);
13718 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013719 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013720}
13721
Victor Stinner621ef3d2012-10-02 00:33:47 +020013722/* Format an integer.
13723 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013724 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013725 * -1 and raise an exception on error */
13726static int
Victor Stinnera47082312012-10-04 02:19:54 +020013727mainformatlong(PyObject *v,
13728 struct unicode_format_arg_t *arg,
13729 PyObject **p_output,
13730 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013731{
13732 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013733 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013734
13735 if (!PyNumber_Check(v))
13736 goto wrongtype;
13737
13738 if (!PyLong_Check(v)) {
13739 iobj = PyNumber_Long(v);
13740 if (iobj == NULL) {
13741 if (PyErr_ExceptionMatches(PyExc_TypeError))
13742 goto wrongtype;
13743 return -1;
13744 }
13745 assert(PyLong_Check(iobj));
13746 }
13747 else {
13748 iobj = v;
13749 Py_INCREF(iobj);
13750 }
13751
13752 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013753 && arg->width == -1 && arg->prec == -1
13754 && !(arg->flags & (F_SIGN | F_BLANK))
13755 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013756 {
13757 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013758 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013759 int base;
13760
Victor Stinnera47082312012-10-04 02:19:54 +020013761 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013762 {
13763 default:
13764 assert(0 && "'type' not in [diuoxX]");
13765 case 'd':
13766 case 'i':
13767 case 'u':
13768 base = 10;
13769 break;
13770 case 'o':
13771 base = 8;
13772 break;
13773 case 'x':
13774 case 'X':
13775 base = 16;
13776 break;
13777 }
13778
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013779 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13780 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013781 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013782 }
13783 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013784 return 1;
13785 }
13786
Victor Stinnera47082312012-10-04 02:19:54 +020013787 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013788 Py_DECREF(iobj);
13789 if (res == NULL)
13790 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013791 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013792 return 0;
13793
13794wrongtype:
13795 PyErr_Format(PyExc_TypeError,
13796 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013797 "not %.200s",
13798 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013799 return -1;
13800}
13801
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013802static Py_UCS4
13803formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013804{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013805 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013806 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013807 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013808 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013809 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013810 goto onError;
13811 }
13812 else {
13813 /* Integer input truncated to a character */
13814 long x;
13815 x = PyLong_AsLong(v);
13816 if (x == -1 && PyErr_Occurred())
13817 goto onError;
13818
Victor Stinner8faf8212011-12-08 22:14:11 +010013819 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013820 PyErr_SetString(PyExc_OverflowError,
13821 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013822 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013823 }
13824
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013825 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013826 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013827
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013829 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013830 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013831 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013832}
13833
Victor Stinnera47082312012-10-04 02:19:54 +020013834/* Parse options of an argument: flags, width, precision.
13835 Handle also "%(name)" syntax.
13836
13837 Return 0 if the argument has been formatted into arg->str.
13838 Return 1 if the argument has been written into ctx->writer,
13839 Raise an exception and return -1 on error. */
13840static int
13841unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13842 struct unicode_format_arg_t *arg)
13843{
13844#define FORMAT_READ(ctx) \
13845 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13846
13847 PyObject *v;
13848
Victor Stinnera47082312012-10-04 02:19:54 +020013849 if (arg->ch == '(') {
13850 /* Get argument value from a dictionary. Example: "%(name)s". */
13851 Py_ssize_t keystart;
13852 Py_ssize_t keylen;
13853 PyObject *key;
13854 int pcount = 1;
13855
13856 if (ctx->dict == NULL) {
13857 PyErr_SetString(PyExc_TypeError,
13858 "format requires a mapping");
13859 return -1;
13860 }
13861 ++ctx->fmtpos;
13862 --ctx->fmtcnt;
13863 keystart = ctx->fmtpos;
13864 /* Skip over balanced parentheses */
13865 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13866 arg->ch = FORMAT_READ(ctx);
13867 if (arg->ch == ')')
13868 --pcount;
13869 else if (arg->ch == '(')
13870 ++pcount;
13871 ctx->fmtpos++;
13872 }
13873 keylen = ctx->fmtpos - keystart - 1;
13874 if (ctx->fmtcnt < 0 || pcount > 0) {
13875 PyErr_SetString(PyExc_ValueError,
13876 "incomplete format key");
13877 return -1;
13878 }
13879 key = PyUnicode_Substring(ctx->fmtstr,
13880 keystart, keystart + keylen);
13881 if (key == NULL)
13882 return -1;
13883 if (ctx->args_owned) {
13884 Py_DECREF(ctx->args);
13885 ctx->args_owned = 0;
13886 }
13887 ctx->args = PyObject_GetItem(ctx->dict, key);
13888 Py_DECREF(key);
13889 if (ctx->args == NULL)
13890 return -1;
13891 ctx->args_owned = 1;
13892 ctx->arglen = -1;
13893 ctx->argidx = -2;
13894 }
13895
13896 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020013897 while (--ctx->fmtcnt >= 0) {
13898 arg->ch = FORMAT_READ(ctx);
13899 ctx->fmtpos++;
13900 switch (arg->ch) {
13901 case '-': arg->flags |= F_LJUST; continue;
13902 case '+': arg->flags |= F_SIGN; continue;
13903 case ' ': arg->flags |= F_BLANK; continue;
13904 case '#': arg->flags |= F_ALT; continue;
13905 case '0': arg->flags |= F_ZERO; continue;
13906 }
13907 break;
13908 }
13909
13910 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020013911 if (arg->ch == '*') {
13912 v = unicode_format_getnextarg(ctx);
13913 if (v == NULL)
13914 return -1;
13915 if (!PyLong_Check(v)) {
13916 PyErr_SetString(PyExc_TypeError,
13917 "* wants int");
13918 return -1;
13919 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013920 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013921 if (arg->width == -1 && PyErr_Occurred())
13922 return -1;
13923 if (arg->width < 0) {
13924 arg->flags |= F_LJUST;
13925 arg->width = -arg->width;
13926 }
13927 if (--ctx->fmtcnt >= 0) {
13928 arg->ch = FORMAT_READ(ctx);
13929 ctx->fmtpos++;
13930 }
13931 }
13932 else if (arg->ch >= '0' && arg->ch <= '9') {
13933 arg->width = arg->ch - '0';
13934 while (--ctx->fmtcnt >= 0) {
13935 arg->ch = FORMAT_READ(ctx);
13936 ctx->fmtpos++;
13937 if (arg->ch < '0' || arg->ch > '9')
13938 break;
13939 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13940 mixing signed and unsigned comparison. Since arg->ch is between
13941 '0' and '9', casting to int is safe. */
13942 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13943 PyErr_SetString(PyExc_ValueError,
13944 "width too big");
13945 return -1;
13946 }
13947 arg->width = arg->width*10 + (arg->ch - '0');
13948 }
13949 }
13950
13951 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020013952 if (arg->ch == '.') {
13953 arg->prec = 0;
13954 if (--ctx->fmtcnt >= 0) {
13955 arg->ch = FORMAT_READ(ctx);
13956 ctx->fmtpos++;
13957 }
13958 if (arg->ch == '*') {
13959 v = unicode_format_getnextarg(ctx);
13960 if (v == NULL)
13961 return -1;
13962 if (!PyLong_Check(v)) {
13963 PyErr_SetString(PyExc_TypeError,
13964 "* wants int");
13965 return -1;
13966 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013967 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013968 if (arg->prec == -1 && PyErr_Occurred())
13969 return -1;
13970 if (arg->prec < 0)
13971 arg->prec = 0;
13972 if (--ctx->fmtcnt >= 0) {
13973 arg->ch = FORMAT_READ(ctx);
13974 ctx->fmtpos++;
13975 }
13976 }
13977 else if (arg->ch >= '0' && arg->ch <= '9') {
13978 arg->prec = arg->ch - '0';
13979 while (--ctx->fmtcnt >= 0) {
13980 arg->ch = FORMAT_READ(ctx);
13981 ctx->fmtpos++;
13982 if (arg->ch < '0' || arg->ch > '9')
13983 break;
13984 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13985 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013986 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013987 return -1;
13988 }
13989 arg->prec = arg->prec*10 + (arg->ch - '0');
13990 }
13991 }
13992 }
13993
13994 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13995 if (ctx->fmtcnt >= 0) {
13996 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13997 if (--ctx->fmtcnt >= 0) {
13998 arg->ch = FORMAT_READ(ctx);
13999 ctx->fmtpos++;
14000 }
14001 }
14002 }
14003 if (ctx->fmtcnt < 0) {
14004 PyErr_SetString(PyExc_ValueError,
14005 "incomplete format");
14006 return -1;
14007 }
14008 return 0;
14009
14010#undef FORMAT_READ
14011}
14012
14013/* Format one argument. Supported conversion specifiers:
14014
14015 - "s", "r", "a": any type
14016 - "i", "d", "u", "o", "x", "X": int
14017 - "e", "E", "f", "F", "g", "G": float
14018 - "c": int or str (1 character)
14019
Victor Stinner8dbd4212012-12-04 09:30:24 +010014020 When possible, the output is written directly into the Unicode writer
14021 (ctx->writer). A string is created when padding is required.
14022
Victor Stinnera47082312012-10-04 02:19:54 +020014023 Return 0 if the argument has been formatted into *p_str,
14024 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014025 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014026static int
14027unicode_format_arg_format(struct unicode_formatter_t *ctx,
14028 struct unicode_format_arg_t *arg,
14029 PyObject **p_str)
14030{
14031 PyObject *v;
14032 _PyUnicodeWriter *writer = &ctx->writer;
14033
14034 if (ctx->fmtcnt == 0)
14035 ctx->writer.overallocate = 0;
14036
14037 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014038 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014039 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014040 return 1;
14041 }
14042
14043 v = unicode_format_getnextarg(ctx);
14044 if (v == NULL)
14045 return -1;
14046
Victor Stinnera47082312012-10-04 02:19:54 +020014047
14048 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014049 case 's':
14050 case 'r':
14051 case 'a':
14052 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14053 /* Fast path */
14054 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14055 return -1;
14056 return 1;
14057 }
14058
14059 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14060 *p_str = v;
14061 Py_INCREF(*p_str);
14062 }
14063 else {
14064 if (arg->ch == 's')
14065 *p_str = PyObject_Str(v);
14066 else if (arg->ch == 'r')
14067 *p_str = PyObject_Repr(v);
14068 else
14069 *p_str = PyObject_ASCII(v);
14070 }
14071 break;
14072
14073 case 'i':
14074 case 'd':
14075 case 'u':
14076 case 'o':
14077 case 'x':
14078 case 'X':
14079 {
14080 int ret = mainformatlong(v, arg, p_str, writer);
14081 if (ret != 0)
14082 return ret;
14083 arg->sign = 1;
14084 break;
14085 }
14086
14087 case 'e':
14088 case 'E':
14089 case 'f':
14090 case 'F':
14091 case 'g':
14092 case 'G':
14093 if (arg->width == -1 && arg->prec == -1
14094 && !(arg->flags & (F_SIGN | F_BLANK)))
14095 {
14096 /* Fast path */
14097 if (formatfloat(v, arg, NULL, writer) == -1)
14098 return -1;
14099 return 1;
14100 }
14101
14102 arg->sign = 1;
14103 if (formatfloat(v, arg, p_str, NULL) == -1)
14104 return -1;
14105 break;
14106
14107 case 'c':
14108 {
14109 Py_UCS4 ch = formatchar(v);
14110 if (ch == (Py_UCS4) -1)
14111 return -1;
14112 if (arg->width == -1 && arg->prec == -1) {
14113 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014114 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014115 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014116 return 1;
14117 }
14118 *p_str = PyUnicode_FromOrdinal(ch);
14119 break;
14120 }
14121
14122 default:
14123 PyErr_Format(PyExc_ValueError,
14124 "unsupported format character '%c' (0x%x) "
14125 "at index %zd",
14126 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14127 (int)arg->ch,
14128 ctx->fmtpos - 1);
14129 return -1;
14130 }
14131 if (*p_str == NULL)
14132 return -1;
14133 assert (PyUnicode_Check(*p_str));
14134 return 0;
14135}
14136
14137static int
14138unicode_format_arg_output(struct unicode_formatter_t *ctx,
14139 struct unicode_format_arg_t *arg,
14140 PyObject *str)
14141{
14142 Py_ssize_t len;
14143 enum PyUnicode_Kind kind;
14144 void *pbuf;
14145 Py_ssize_t pindex;
14146 Py_UCS4 signchar;
14147 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014148 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014149 Py_ssize_t sublen;
14150 _PyUnicodeWriter *writer = &ctx->writer;
14151 Py_UCS4 fill;
14152
14153 fill = ' ';
14154 if (arg->sign && arg->flags & F_ZERO)
14155 fill = '0';
14156
14157 if (PyUnicode_READY(str) == -1)
14158 return -1;
14159
14160 len = PyUnicode_GET_LENGTH(str);
14161 if ((arg->width == -1 || arg->width <= len)
14162 && (arg->prec == -1 || arg->prec >= len)
14163 && !(arg->flags & (F_SIGN | F_BLANK)))
14164 {
14165 /* Fast path */
14166 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14167 return -1;
14168 return 0;
14169 }
14170
14171 /* Truncate the string for "s", "r" and "a" formats
14172 if the precision is set */
14173 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14174 if (arg->prec >= 0 && len > arg->prec)
14175 len = arg->prec;
14176 }
14177
14178 /* Adjust sign and width */
14179 kind = PyUnicode_KIND(str);
14180 pbuf = PyUnicode_DATA(str);
14181 pindex = 0;
14182 signchar = '\0';
14183 if (arg->sign) {
14184 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14185 if (ch == '-' || ch == '+') {
14186 signchar = ch;
14187 len--;
14188 pindex++;
14189 }
14190 else if (arg->flags & F_SIGN)
14191 signchar = '+';
14192 else if (arg->flags & F_BLANK)
14193 signchar = ' ';
14194 else
14195 arg->sign = 0;
14196 }
14197 if (arg->width < len)
14198 arg->width = len;
14199
14200 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014201 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014202 if (!(arg->flags & F_LJUST)) {
14203 if (arg->sign) {
14204 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014205 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014206 }
14207 else {
14208 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014209 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014210 }
14211 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014212 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14213 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014214 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014215 }
14216
Victor Stinnera47082312012-10-04 02:19:54 +020014217 buflen = arg->width;
14218 if (arg->sign && len == arg->width)
14219 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014220 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014221 return -1;
14222
14223 /* Write the sign if needed */
14224 if (arg->sign) {
14225 if (fill != ' ') {
14226 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14227 writer->pos += 1;
14228 }
14229 if (arg->width > len)
14230 arg->width--;
14231 }
14232
14233 /* Write the numeric prefix for "x", "X" and "o" formats
14234 if the alternate form is used.
14235 For example, write "0x" for the "%#x" format. */
14236 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14237 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14238 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14239 if (fill != ' ') {
14240 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14241 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14242 writer->pos += 2;
14243 pindex += 2;
14244 }
14245 arg->width -= 2;
14246 if (arg->width < 0)
14247 arg->width = 0;
14248 len -= 2;
14249 }
14250
14251 /* Pad left with the fill character if needed */
14252 if (arg->width > len && !(arg->flags & F_LJUST)) {
14253 sublen = arg->width - len;
14254 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14255 writer->pos += sublen;
14256 arg->width = len;
14257 }
14258
14259 /* If padding with spaces: write sign if needed and/or numeric prefix if
14260 the alternate form is used */
14261 if (fill == ' ') {
14262 if (arg->sign) {
14263 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14264 writer->pos += 1;
14265 }
14266 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14267 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14268 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14269 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14270 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14271 writer->pos += 2;
14272 pindex += 2;
14273 }
14274 }
14275
14276 /* Write characters */
14277 if (len) {
14278 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14279 str, pindex, len);
14280 writer->pos += len;
14281 }
14282
14283 /* Pad right with the fill character if needed */
14284 if (arg->width > len) {
14285 sublen = arg->width - len;
14286 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14287 writer->pos += sublen;
14288 }
14289 return 0;
14290}
14291
14292/* Helper of PyUnicode_Format(): format one arg.
14293 Return 0 on success, raise an exception and return -1 on error. */
14294static int
14295unicode_format_arg(struct unicode_formatter_t *ctx)
14296{
14297 struct unicode_format_arg_t arg;
14298 PyObject *str;
14299 int ret;
14300
Victor Stinner8dbd4212012-12-04 09:30:24 +010014301 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14302 arg.flags = 0;
14303 arg.width = -1;
14304 arg.prec = -1;
14305 arg.sign = 0;
14306 str = NULL;
14307
Victor Stinnera47082312012-10-04 02:19:54 +020014308 ret = unicode_format_arg_parse(ctx, &arg);
14309 if (ret == -1)
14310 return -1;
14311
14312 ret = unicode_format_arg_format(ctx, &arg, &str);
14313 if (ret == -1)
14314 return -1;
14315
14316 if (ret != 1) {
14317 ret = unicode_format_arg_output(ctx, &arg, str);
14318 Py_DECREF(str);
14319 if (ret == -1)
14320 return -1;
14321 }
14322
14323 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14324 PyErr_SetString(PyExc_TypeError,
14325 "not all arguments converted during string formatting");
14326 return -1;
14327 }
14328 return 0;
14329}
14330
Alexander Belopolsky40018472011-02-26 01:02:56 +000014331PyObject *
14332PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014333{
Victor Stinnera47082312012-10-04 02:19:54 +020014334 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014335
Guido van Rossumd57fd912000-03-10 22:53:23 +000014336 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014337 PyErr_BadInternalCall();
14338 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014339 }
Victor Stinnera47082312012-10-04 02:19:54 +020014340
14341 ctx.fmtstr = PyUnicode_FromObject(format);
14342 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014343 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014344 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14345 Py_DECREF(ctx.fmtstr);
14346 return NULL;
14347 }
14348 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14349 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14350 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14351 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014352
Victor Stinner8f674cc2013-04-17 23:02:17 +020014353 _PyUnicodeWriter_Init(&ctx.writer);
14354 ctx.writer.min_length = ctx.fmtcnt + 100;
14355 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014356
Guido van Rossumd57fd912000-03-10 22:53:23 +000014357 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014358 ctx.arglen = PyTuple_Size(args);
14359 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014360 }
14361 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014362 ctx.arglen = -1;
14363 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014364 }
Victor Stinnera47082312012-10-04 02:19:54 +020014365 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014366 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014367 ctx.dict = args;
14368 else
14369 ctx.dict = NULL;
14370 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014371
Victor Stinnera47082312012-10-04 02:19:54 +020014372 while (--ctx.fmtcnt >= 0) {
14373 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014374 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014375
14376 nonfmtpos = ctx.fmtpos++;
14377 while (ctx.fmtcnt >= 0 &&
14378 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14379 ctx.fmtpos++;
14380 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014381 }
Victor Stinnera47082312012-10-04 02:19:54 +020014382 if (ctx.fmtcnt < 0) {
14383 ctx.fmtpos--;
14384 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014385 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014386
Victor Stinnercfc4c132013-04-03 01:48:39 +020014387 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14388 nonfmtpos, ctx.fmtpos) < 0)
14389 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 }
14391 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014392 ctx.fmtpos++;
14393 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014394 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014395 }
14396 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014397
Victor Stinnera47082312012-10-04 02:19:54 +020014398 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014399 PyErr_SetString(PyExc_TypeError,
14400 "not all arguments converted during string formatting");
14401 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014402 }
14403
Victor Stinnera47082312012-10-04 02:19:54 +020014404 if (ctx.args_owned) {
14405 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014406 }
Victor Stinnera47082312012-10-04 02:19:54 +020014407 Py_DECREF(ctx.fmtstr);
14408 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014409
Benjamin Peterson29060642009-01-31 22:14:21 +000014410 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014411 Py_DECREF(ctx.fmtstr);
14412 _PyUnicodeWriter_Dealloc(&ctx.writer);
14413 if (ctx.args_owned) {
14414 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014415 }
14416 return NULL;
14417}
14418
Jeremy Hylton938ace62002-07-17 16:30:39 +000014419static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014420unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14421
Tim Peters6d6c1a32001-08-02 04:15:00 +000014422static PyObject *
14423unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14424{
Benjamin Peterson29060642009-01-31 22:14:21 +000014425 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014426 static char *kwlist[] = {"object", "encoding", "errors", 0};
14427 char *encoding = NULL;
14428 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014429
Benjamin Peterson14339b62009-01-31 16:36:08 +000014430 if (type != &PyUnicode_Type)
14431 return unicode_subtype_new(type, args, kwds);
14432 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014433 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014434 return NULL;
14435 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014436 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014437 if (encoding == NULL && errors == NULL)
14438 return PyObject_Str(x);
14439 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014440 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014441}
14442
Guido van Rossume023fe02001-08-30 03:12:59 +000014443static PyObject *
14444unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14445{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014446 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014447 Py_ssize_t length, char_size;
14448 int share_wstr, share_utf8;
14449 unsigned int kind;
14450 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014451
Benjamin Peterson14339b62009-01-31 16:36:08 +000014452 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014453
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014454 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014455 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014456 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014457 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014458 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014459 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014460 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014461 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014462
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014463 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014464 if (self == NULL) {
14465 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014466 return NULL;
14467 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014468 kind = PyUnicode_KIND(unicode);
14469 length = PyUnicode_GET_LENGTH(unicode);
14470
14471 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014472#ifdef Py_DEBUG
14473 _PyUnicode_HASH(self) = -1;
14474#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014475 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014476#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014477 _PyUnicode_STATE(self).interned = 0;
14478 _PyUnicode_STATE(self).kind = kind;
14479 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014480 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014481 _PyUnicode_STATE(self).ready = 1;
14482 _PyUnicode_WSTR(self) = NULL;
14483 _PyUnicode_UTF8_LENGTH(self) = 0;
14484 _PyUnicode_UTF8(self) = NULL;
14485 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014486 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014487
14488 share_utf8 = 0;
14489 share_wstr = 0;
14490 if (kind == PyUnicode_1BYTE_KIND) {
14491 char_size = 1;
14492 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14493 share_utf8 = 1;
14494 }
14495 else if (kind == PyUnicode_2BYTE_KIND) {
14496 char_size = 2;
14497 if (sizeof(wchar_t) == 2)
14498 share_wstr = 1;
14499 }
14500 else {
14501 assert(kind == PyUnicode_4BYTE_KIND);
14502 char_size = 4;
14503 if (sizeof(wchar_t) == 4)
14504 share_wstr = 1;
14505 }
14506
14507 /* Ensure we won't overflow the length. */
14508 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14509 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014510 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014511 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014512 data = PyObject_MALLOC((length + 1) * char_size);
14513 if (data == NULL) {
14514 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014515 goto onError;
14516 }
14517
Victor Stinnerc3c74152011-10-02 20:39:55 +020014518 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014519 if (share_utf8) {
14520 _PyUnicode_UTF8_LENGTH(self) = length;
14521 _PyUnicode_UTF8(self) = data;
14522 }
14523 if (share_wstr) {
14524 _PyUnicode_WSTR_LENGTH(self) = length;
14525 _PyUnicode_WSTR(self) = (wchar_t *)data;
14526 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014527
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014528 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014529 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014530 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014531#ifdef Py_DEBUG
14532 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14533#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014534 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014535 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014536
14537onError:
14538 Py_DECREF(unicode);
14539 Py_DECREF(self);
14540 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014541}
14542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014543PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014544"str(object='') -> str\n\
14545str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014546\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014547Create a new string object from the given object. If encoding or\n\
14548errors is specified, then the object must expose a data buffer\n\
14549that will be decoded using the given encoding and error handler.\n\
14550Otherwise, returns the result of object.__str__() (if defined)\n\
14551or repr(object).\n\
14552encoding defaults to sys.getdefaultencoding().\n\
14553errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014554
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014555static PyObject *unicode_iter(PyObject *seq);
14556
Guido van Rossumd57fd912000-03-10 22:53:23 +000014557PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014558 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014559 "str", /* tp_name */
14560 sizeof(PyUnicodeObject), /* tp_size */
14561 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014562 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014563 (destructor)unicode_dealloc, /* tp_dealloc */
14564 0, /* tp_print */
14565 0, /* tp_getattr */
14566 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014567 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014568 unicode_repr, /* tp_repr */
14569 &unicode_as_number, /* tp_as_number */
14570 &unicode_as_sequence, /* tp_as_sequence */
14571 &unicode_as_mapping, /* tp_as_mapping */
14572 (hashfunc) unicode_hash, /* tp_hash*/
14573 0, /* tp_call*/
14574 (reprfunc) unicode_str, /* tp_str */
14575 PyObject_GenericGetAttr, /* tp_getattro */
14576 0, /* tp_setattro */
14577 0, /* tp_as_buffer */
14578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014579 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014580 unicode_doc, /* tp_doc */
14581 0, /* tp_traverse */
14582 0, /* tp_clear */
14583 PyUnicode_RichCompare, /* tp_richcompare */
14584 0, /* tp_weaklistoffset */
14585 unicode_iter, /* tp_iter */
14586 0, /* tp_iternext */
14587 unicode_methods, /* tp_methods */
14588 0, /* tp_members */
14589 0, /* tp_getset */
14590 &PyBaseObject_Type, /* tp_base */
14591 0, /* tp_dict */
14592 0, /* tp_descr_get */
14593 0, /* tp_descr_set */
14594 0, /* tp_dictoffset */
14595 0, /* tp_init */
14596 0, /* tp_alloc */
14597 unicode_new, /* tp_new */
14598 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014599};
14600
14601/* Initialize the Unicode implementation */
14602
Victor Stinner3a50e702011-10-18 21:21:00 +020014603int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014604{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014605 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014606 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014607 0x000A, /* LINE FEED */
14608 0x000D, /* CARRIAGE RETURN */
14609 0x001C, /* FILE SEPARATOR */
14610 0x001D, /* GROUP SEPARATOR */
14611 0x001E, /* RECORD SEPARATOR */
14612 0x0085, /* NEXT LINE */
14613 0x2028, /* LINE SEPARATOR */
14614 0x2029, /* PARAGRAPH SEPARATOR */
14615 };
14616
Fred Drakee4315f52000-05-09 19:53:39 +000014617 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014618 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014619 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014620 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014621 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014622
Guido van Rossumcacfc072002-05-24 19:01:59 +000014623 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014624 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014625
14626 /* initialize the linebreak bloom filter */
14627 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014628 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014629 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014630
Christian Heimes26532f72013-07-20 14:57:16 +020014631 if (PyType_Ready(&EncodingMapType) < 0)
14632 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014633
Benjamin Petersonc4311282012-10-30 23:21:10 -040014634 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14635 Py_FatalError("Can't initialize field name iterator type");
14636
14637 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14638 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014639
Victor Stinner3a50e702011-10-18 21:21:00 +020014640#ifdef HAVE_MBCS
14641 winver.dwOSVersionInfoSize = sizeof(winver);
14642 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14643 PyErr_SetFromWindowsErr(0);
14644 return -1;
14645 }
14646#endif
14647 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014648}
14649
14650/* Finalize the Unicode implementation */
14651
Christian Heimesa156e092008-02-16 07:38:31 +000014652int
14653PyUnicode_ClearFreeList(void)
14654{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014655 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014656}
14657
Guido van Rossumd57fd912000-03-10 22:53:23 +000014658void
Thomas Wouters78890102000-07-22 19:25:51 +000014659_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014660{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014661 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014662
Serhiy Storchaka05997252013-01-26 12:14:02 +020014663 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014664
Serhiy Storchaka05997252013-01-26 12:14:02 +020014665 for (i = 0; i < 256; i++)
14666 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014667 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014668 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014669}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014670
Walter Dörwald16807132007-05-25 13:52:07 +000014671void
14672PyUnicode_InternInPlace(PyObject **p)
14673{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014674 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014675 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014676#ifdef Py_DEBUG
14677 assert(s != NULL);
14678 assert(_PyUnicode_CHECK(s));
14679#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014680 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014681 return;
14682#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014683 /* If it's a subclass, we don't really know what putting
14684 it in the interned dict might do. */
14685 if (!PyUnicode_CheckExact(s))
14686 return;
14687 if (PyUnicode_CHECK_INTERNED(s))
14688 return;
14689 if (interned == NULL) {
14690 interned = PyDict_New();
14691 if (interned == NULL) {
14692 PyErr_Clear(); /* Don't leave an exception */
14693 return;
14694 }
14695 }
14696 /* It might be that the GetItem call fails even
14697 though the key is present in the dictionary,
14698 namely when this happens during a stack overflow. */
14699 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014700 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014701 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014702
Victor Stinnerf0335102013-04-14 19:13:03 +020014703 if (t) {
14704 Py_INCREF(t);
14705 Py_DECREF(*p);
14706 *p = t;
14707 return;
14708 }
Walter Dörwald16807132007-05-25 13:52:07 +000014709
Benjamin Peterson14339b62009-01-31 16:36:08 +000014710 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014711 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014712 PyErr_Clear();
14713 PyThreadState_GET()->recursion_critical = 0;
14714 return;
14715 }
14716 PyThreadState_GET()->recursion_critical = 0;
14717 /* The two references in interned are not counted by refcnt.
14718 The deallocator will take care of this */
14719 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014720 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014721}
14722
14723void
14724PyUnicode_InternImmortal(PyObject **p)
14725{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014726 PyUnicode_InternInPlace(p);
14727 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014728 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014729 Py_INCREF(*p);
14730 }
Walter Dörwald16807132007-05-25 13:52:07 +000014731}
14732
14733PyObject *
14734PyUnicode_InternFromString(const char *cp)
14735{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014736 PyObject *s = PyUnicode_FromString(cp);
14737 if (s == NULL)
14738 return NULL;
14739 PyUnicode_InternInPlace(&s);
14740 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014741}
14742
Alexander Belopolsky40018472011-02-26 01:02:56 +000014743void
14744_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014745{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014746 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014747 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014748 Py_ssize_t i, n;
14749 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014750
Benjamin Peterson14339b62009-01-31 16:36:08 +000014751 if (interned == NULL || !PyDict_Check(interned))
14752 return;
14753 keys = PyDict_Keys(interned);
14754 if (keys == NULL || !PyList_Check(keys)) {
14755 PyErr_Clear();
14756 return;
14757 }
Walter Dörwald16807132007-05-25 13:52:07 +000014758
Benjamin Peterson14339b62009-01-31 16:36:08 +000014759 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14760 detector, interned unicode strings are not forcibly deallocated;
14761 rather, we give them their stolen references back, and then clear
14762 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014763
Benjamin Peterson14339b62009-01-31 16:36:08 +000014764 n = PyList_GET_SIZE(keys);
14765 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014766 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014767 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014768 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014769 if (PyUnicode_READY(s) == -1) {
14770 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014771 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014772 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014773 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014774 case SSTATE_NOT_INTERNED:
14775 /* XXX Shouldn't happen */
14776 break;
14777 case SSTATE_INTERNED_IMMORTAL:
14778 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014779 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014780 break;
14781 case SSTATE_INTERNED_MORTAL:
14782 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014783 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014784 break;
14785 default:
14786 Py_FatalError("Inconsistent interned string state.");
14787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014788 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014789 }
14790 fprintf(stderr, "total size of all interned strings: "
14791 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14792 "mortal/immortal\n", mortal_size, immortal_size);
14793 Py_DECREF(keys);
14794 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014795 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014796}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014797
14798
14799/********************* Unicode Iterator **************************/
14800
14801typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014802 PyObject_HEAD
14803 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014804 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014805} unicodeiterobject;
14806
14807static void
14808unicodeiter_dealloc(unicodeiterobject *it)
14809{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014810 _PyObject_GC_UNTRACK(it);
14811 Py_XDECREF(it->it_seq);
14812 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014813}
14814
14815static int
14816unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14817{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014818 Py_VISIT(it->it_seq);
14819 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014820}
14821
14822static PyObject *
14823unicodeiter_next(unicodeiterobject *it)
14824{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014825 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014826
Benjamin Peterson14339b62009-01-31 16:36:08 +000014827 assert(it != NULL);
14828 seq = it->it_seq;
14829 if (seq == NULL)
14830 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014831 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014833 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14834 int kind = PyUnicode_KIND(seq);
14835 void *data = PyUnicode_DATA(seq);
14836 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14837 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014838 if (item != NULL)
14839 ++it->it_index;
14840 return item;
14841 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014842
Benjamin Peterson14339b62009-01-31 16:36:08 +000014843 Py_DECREF(seq);
14844 it->it_seq = NULL;
14845 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014846}
14847
14848static PyObject *
14849unicodeiter_len(unicodeiterobject *it)
14850{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014851 Py_ssize_t len = 0;
14852 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014853 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014854 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014855}
14856
14857PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14858
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014859static PyObject *
14860unicodeiter_reduce(unicodeiterobject *it)
14861{
14862 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014863 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014864 it->it_seq, it->it_index);
14865 } else {
14866 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14867 if (u == NULL)
14868 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014869 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014870 }
14871}
14872
14873PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14874
14875static PyObject *
14876unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14877{
14878 Py_ssize_t index = PyLong_AsSsize_t(state);
14879 if (index == -1 && PyErr_Occurred())
14880 return NULL;
14881 if (index < 0)
14882 index = 0;
14883 it->it_index = index;
14884 Py_RETURN_NONE;
14885}
14886
14887PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14888
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014889static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014890 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014891 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014892 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14893 reduce_doc},
14894 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14895 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014896 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014897};
14898
14899PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014900 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14901 "str_iterator", /* tp_name */
14902 sizeof(unicodeiterobject), /* tp_basicsize */
14903 0, /* tp_itemsize */
14904 /* methods */
14905 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14906 0, /* tp_print */
14907 0, /* tp_getattr */
14908 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014909 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014910 0, /* tp_repr */
14911 0, /* tp_as_number */
14912 0, /* tp_as_sequence */
14913 0, /* tp_as_mapping */
14914 0, /* tp_hash */
14915 0, /* tp_call */
14916 0, /* tp_str */
14917 PyObject_GenericGetAttr, /* tp_getattro */
14918 0, /* tp_setattro */
14919 0, /* tp_as_buffer */
14920 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14921 0, /* tp_doc */
14922 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14923 0, /* tp_clear */
14924 0, /* tp_richcompare */
14925 0, /* tp_weaklistoffset */
14926 PyObject_SelfIter, /* tp_iter */
14927 (iternextfunc)unicodeiter_next, /* tp_iternext */
14928 unicodeiter_methods, /* tp_methods */
14929 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014930};
14931
14932static PyObject *
14933unicode_iter(PyObject *seq)
14934{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014935 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014936
Benjamin Peterson14339b62009-01-31 16:36:08 +000014937 if (!PyUnicode_Check(seq)) {
14938 PyErr_BadInternalCall();
14939 return NULL;
14940 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014941 if (PyUnicode_READY(seq) == -1)
14942 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014943 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14944 if (it == NULL)
14945 return NULL;
14946 it->it_index = 0;
14947 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014948 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014949 _PyObject_GC_TRACK(it);
14950 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014951}
14952
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014953
14954size_t
14955Py_UNICODE_strlen(const Py_UNICODE *u)
14956{
14957 int res = 0;
14958 while(*u++)
14959 res++;
14960 return res;
14961}
14962
14963Py_UNICODE*
14964Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14965{
14966 Py_UNICODE *u = s1;
14967 while ((*u++ = *s2++));
14968 return s1;
14969}
14970
14971Py_UNICODE*
14972Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14973{
14974 Py_UNICODE *u = s1;
14975 while ((*u++ = *s2++))
14976 if (n-- == 0)
14977 break;
14978 return s1;
14979}
14980
14981Py_UNICODE*
14982Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14983{
14984 Py_UNICODE *u1 = s1;
14985 u1 += Py_UNICODE_strlen(u1);
14986 Py_UNICODE_strcpy(u1, s2);
14987 return s1;
14988}
14989
14990int
14991Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14992{
14993 while (*s1 && *s2 && *s1 == *s2)
14994 s1++, s2++;
14995 if (*s1 && *s2)
14996 return (*s1 < *s2) ? -1 : +1;
14997 if (*s1)
14998 return 1;
14999 if (*s2)
15000 return -1;
15001 return 0;
15002}
15003
15004int
15005Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15006{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015007 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015008 for (; n != 0; n--) {
15009 u1 = *s1;
15010 u2 = *s2;
15011 if (u1 != u2)
15012 return (u1 < u2) ? -1 : +1;
15013 if (u1 == '\0')
15014 return 0;
15015 s1++;
15016 s2++;
15017 }
15018 return 0;
15019}
15020
15021Py_UNICODE*
15022Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15023{
15024 const Py_UNICODE *p;
15025 for (p = s; *p; p++)
15026 if (*p == c)
15027 return (Py_UNICODE*)p;
15028 return NULL;
15029}
15030
15031Py_UNICODE*
15032Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15033{
15034 const Py_UNICODE *p;
15035 p = s + Py_UNICODE_strlen(s);
15036 while (p != s) {
15037 p--;
15038 if (*p == c)
15039 return (Py_UNICODE*)p;
15040 }
15041 return NULL;
15042}
Victor Stinner331ea922010-08-10 16:37:20 +000015043
Victor Stinner71133ff2010-09-01 23:43:53 +000015044Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015045PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015046{
Victor Stinner577db2c2011-10-11 22:12:48 +020015047 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015048 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015050 if (!PyUnicode_Check(unicode)) {
15051 PyErr_BadArgument();
15052 return NULL;
15053 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015054 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015055 if (u == NULL)
15056 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015057 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015058 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015059 PyErr_NoMemory();
15060 return NULL;
15061 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015062 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015063 size *= sizeof(Py_UNICODE);
15064 copy = PyMem_Malloc(size);
15065 if (copy == NULL) {
15066 PyErr_NoMemory();
15067 return NULL;
15068 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015069 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015070 return copy;
15071}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015072
Georg Brandl66c221e2010-10-14 07:04:07 +000015073/* A _string module, to export formatter_parser and formatter_field_name_split
15074 to the string.Formatter class implemented in Python. */
15075
15076static PyMethodDef _string_methods[] = {
15077 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15078 METH_O, PyDoc_STR("split the argument as a field name")},
15079 {"formatter_parser", (PyCFunction) formatter_parser,
15080 METH_O, PyDoc_STR("parse the argument as a format string")},
15081 {NULL, NULL}
15082};
15083
15084static struct PyModuleDef _string_module = {
15085 PyModuleDef_HEAD_INIT,
15086 "_string",
15087 PyDoc_STR("string helper module"),
15088 0,
15089 _string_methods,
15090 NULL,
15091 NULL,
15092 NULL,
15093 NULL
15094};
15095
15096PyMODINIT_FUNC
15097PyInit__string(void)
15098{
15099 return PyModule_Create(&_string_module);
15100}
15101
15102
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015103#ifdef __cplusplus
15104}
15105#endif