blob: 87c6472e6a1614e06cd5d481bf8e2c7dfa5e1239 [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 Stinner37296e82010-06-10 13:36:23 +00003024 (strcmp(lower, "iso-8859-1") == 0))
3025 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003026#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003027 else if (strcmp(lower, "mbcs") == 0)
3028 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003029#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003030 else if (strcmp(lower, "ascii") == 0)
3031 return PyUnicode_DecodeASCII(s, size, errors);
3032 else if (strcmp(lower, "utf-16") == 0)
3033 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3034 else if (strcmp(lower, "utf-32") == 0)
3035 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3036 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037
3038 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003039 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003040 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003041 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003042 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043 if (buffer == NULL)
3044 goto onError;
3045 unicode = PyCodec_Decode(buffer, encoding, errors);
3046 if (unicode == NULL)
3047 goto onError;
3048 if (!PyUnicode_Check(unicode)) {
3049 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003050 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003051 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 Py_DECREF(unicode);
3053 goto onError;
3054 }
3055 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003056 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003057
Benjamin Peterson29060642009-01-31 22:14:21 +00003058 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003059 Py_XDECREF(buffer);
3060 return NULL;
3061}
3062
Alexander Belopolsky40018472011-02-26 01:02:56 +00003063PyObject *
3064PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003065 const char *encoding,
3066 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003067{
3068 PyObject *v;
3069
3070 if (!PyUnicode_Check(unicode)) {
3071 PyErr_BadArgument();
3072 goto onError;
3073 }
3074
3075 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003076 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003077
3078 /* Decode via the codec registry */
3079 v = PyCodec_Decode(unicode, encoding, errors);
3080 if (v == NULL)
3081 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003082 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003083
Benjamin Peterson29060642009-01-31 22:14:21 +00003084 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003085 return NULL;
3086}
3087
Alexander Belopolsky40018472011-02-26 01:02:56 +00003088PyObject *
3089PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003090 const char *encoding,
3091 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003092{
3093 PyObject *v;
3094
3095 if (!PyUnicode_Check(unicode)) {
3096 PyErr_BadArgument();
3097 goto onError;
3098 }
3099
3100 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003101 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003102
3103 /* Decode via the codec registry */
3104 v = PyCodec_Decode(unicode, encoding, errors);
3105 if (v == NULL)
3106 goto onError;
3107 if (!PyUnicode_Check(v)) {
3108 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003109 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003110 Py_TYPE(v)->tp_name);
3111 Py_DECREF(v);
3112 goto onError;
3113 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003114 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003115
Benjamin Peterson29060642009-01-31 22:14:21 +00003116 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003117 return NULL;
3118}
3119
Alexander Belopolsky40018472011-02-26 01:02:56 +00003120PyObject *
3121PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003122 Py_ssize_t size,
3123 const char *encoding,
3124 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003125{
3126 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003127
Guido van Rossumd57fd912000-03-10 22:53:23 +00003128 unicode = PyUnicode_FromUnicode(s, size);
3129 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003130 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003131 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3132 Py_DECREF(unicode);
3133 return v;
3134}
3135
Alexander Belopolsky40018472011-02-26 01:02:56 +00003136PyObject *
3137PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003138 const char *encoding,
3139 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003140{
3141 PyObject *v;
3142
3143 if (!PyUnicode_Check(unicode)) {
3144 PyErr_BadArgument();
3145 goto onError;
3146 }
3147
3148 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003149 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003150
3151 /* Encode via the codec registry */
3152 v = PyCodec_Encode(unicode, encoding, errors);
3153 if (v == NULL)
3154 goto onError;
3155 return v;
3156
Benjamin Peterson29060642009-01-31 22:14:21 +00003157 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003158 return NULL;
3159}
3160
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003161static size_t
3162wcstombs_errorpos(const wchar_t *wstr)
3163{
3164 size_t len;
3165#if SIZEOF_WCHAR_T == 2
3166 wchar_t buf[3];
3167#else
3168 wchar_t buf[2];
3169#endif
3170 char outbuf[MB_LEN_MAX];
3171 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003172
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003173#if SIZEOF_WCHAR_T == 2
3174 buf[2] = 0;
3175#else
3176 buf[1] = 0;
3177#endif
3178 start = wstr;
3179 while (*wstr != L'\0')
3180 {
3181 previous = wstr;
3182#if SIZEOF_WCHAR_T == 2
3183 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3184 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3185 {
3186 buf[0] = wstr[0];
3187 buf[1] = wstr[1];
3188 wstr += 2;
3189 }
3190 else {
3191 buf[0] = *wstr;
3192 buf[1] = 0;
3193 wstr++;
3194 }
3195#else
3196 buf[0] = *wstr;
3197 wstr++;
3198#endif
3199 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003200 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003201 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003202 }
3203
3204 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003205 return 0;
3206}
3207
Victor Stinner1b579672011-12-17 05:47:23 +01003208static int
3209locale_error_handler(const char *errors, int *surrogateescape)
3210{
3211 if (errors == NULL) {
3212 *surrogateescape = 0;
3213 return 0;
3214 }
3215
3216 if (strcmp(errors, "strict") == 0) {
3217 *surrogateescape = 0;
3218 return 0;
3219 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003220 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003221 *surrogateescape = 1;
3222 return 0;
3223 }
3224 PyErr_Format(PyExc_ValueError,
3225 "only 'strict' and 'surrogateescape' error handlers "
3226 "are supported, not '%s'",
3227 errors);
3228 return -1;
3229}
3230
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003231PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003232PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003233{
3234 Py_ssize_t wlen, wlen2;
3235 wchar_t *wstr;
3236 PyObject *bytes = NULL;
3237 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003238 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003239 PyObject *exc;
3240 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003241 int surrogateescape;
3242
3243 if (locale_error_handler(errors, &surrogateescape) < 0)
3244 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003245
3246 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3247 if (wstr == NULL)
3248 return NULL;
3249
3250 wlen2 = wcslen(wstr);
3251 if (wlen2 != wlen) {
3252 PyMem_Free(wstr);
3253 PyErr_SetString(PyExc_TypeError, "embedded null character");
3254 return NULL;
3255 }
3256
3257 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003258 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003259 char *str;
3260
3261 str = _Py_wchar2char(wstr, &error_pos);
3262 if (str == NULL) {
3263 if (error_pos == (size_t)-1) {
3264 PyErr_NoMemory();
3265 PyMem_Free(wstr);
3266 return NULL;
3267 }
3268 else {
3269 goto encode_error;
3270 }
3271 }
3272 PyMem_Free(wstr);
3273
3274 bytes = PyBytes_FromString(str);
3275 PyMem_Free(str);
3276 }
3277 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003278 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003279 size_t len, len2;
3280
3281 len = wcstombs(NULL, wstr, 0);
3282 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003283 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003284 goto encode_error;
3285 }
3286
3287 bytes = PyBytes_FromStringAndSize(NULL, len);
3288 if (bytes == NULL) {
3289 PyMem_Free(wstr);
3290 return NULL;
3291 }
3292
3293 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3294 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003295 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003296 goto encode_error;
3297 }
3298 PyMem_Free(wstr);
3299 }
3300 return bytes;
3301
3302encode_error:
3303 errmsg = strerror(errno);
3304 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003305
3306 if (error_pos == (size_t)-1)
3307 error_pos = wcstombs_errorpos(wstr);
3308
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003309 PyMem_Free(wstr);
3310 Py_XDECREF(bytes);
3311
Victor Stinner2f197072011-12-17 07:08:30 +01003312 if (errmsg != NULL) {
3313 size_t errlen;
3314 wstr = _Py_char2wchar(errmsg, &errlen);
3315 if (wstr != NULL) {
3316 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003317 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003318 } else
3319 errmsg = NULL;
3320 }
3321 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003322 reason = PyUnicode_FromString(
3323 "wcstombs() encountered an unencodable "
3324 "wide character");
3325 if (reason == NULL)
3326 return NULL;
3327
3328 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3329 "locale", unicode,
3330 (Py_ssize_t)error_pos,
3331 (Py_ssize_t)(error_pos+1),
3332 reason);
3333 Py_DECREF(reason);
3334 if (exc != NULL) {
3335 PyCodec_StrictErrors(exc);
3336 Py_XDECREF(exc);
3337 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003338 return NULL;
3339}
3340
Victor Stinnerad158722010-10-27 00:25:46 +00003341PyObject *
3342PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003343{
Victor Stinner99b95382011-07-04 14:23:54 +02003344#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003345 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003346#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003347 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003348#else
Victor Stinner793b5312011-04-27 00:24:21 +02003349 PyInterpreterState *interp = PyThreadState_GET()->interp;
3350 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3351 cannot use it to encode and decode filenames before it is loaded. Load
3352 the Python codec requires to encode at least its own filename. Use the C
3353 version of the locale codec until the codec registry is initialized and
3354 the Python codec is loaded.
3355
3356 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3357 cannot only rely on it: check also interp->fscodec_initialized for
3358 subinterpreters. */
3359 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003360 return PyUnicode_AsEncodedString(unicode,
3361 Py_FileSystemDefaultEncoding,
3362 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003363 }
3364 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003365 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003366 }
Victor Stinnerad158722010-10-27 00:25:46 +00003367#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003368}
3369
Alexander Belopolsky40018472011-02-26 01:02:56 +00003370PyObject *
3371PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003372 const char *encoding,
3373 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003374{
3375 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003376 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003377
Guido van Rossumd57fd912000-03-10 22:53:23 +00003378 if (!PyUnicode_Check(unicode)) {
3379 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003380 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003381 }
Fred Drakee4315f52000-05-09 19:53:39 +00003382
Fred Drakee4315f52000-05-09 19:53:39 +00003383 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003384 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003385 if ((strcmp(lower, "utf-8") == 0) ||
3386 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003387 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003388 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003389 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003390 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003391 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003392 }
Victor Stinner37296e82010-06-10 13:36:23 +00003393 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003394 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003395 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003396 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003397#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003398 else if (strcmp(lower, "mbcs") == 0)
3399 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003400#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003401 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003402 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003403 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003404
3405 /* Encode via the codec registry */
3406 v = PyCodec_Encode(unicode, encoding, errors);
3407 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003408 return NULL;
3409
3410 /* The normal path */
3411 if (PyBytes_Check(v))
3412 return v;
3413
3414 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003415 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003416 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003417 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003418
3419 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3420 "encoder %s returned bytearray instead of bytes",
3421 encoding);
3422 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003423 Py_DECREF(v);
3424 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003425 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003426
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003427 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3428 Py_DECREF(v);
3429 return b;
3430 }
3431
3432 PyErr_Format(PyExc_TypeError,
3433 "encoder did not return a bytes object (type=%.400s)",
3434 Py_TYPE(v)->tp_name);
3435 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003436 return NULL;
3437}
3438
Alexander Belopolsky40018472011-02-26 01:02:56 +00003439PyObject *
3440PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003441 const char *encoding,
3442 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003443{
3444 PyObject *v;
3445
3446 if (!PyUnicode_Check(unicode)) {
3447 PyErr_BadArgument();
3448 goto onError;
3449 }
3450
3451 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003452 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003453
3454 /* Encode via the codec registry */
3455 v = PyCodec_Encode(unicode, encoding, errors);
3456 if (v == NULL)
3457 goto onError;
3458 if (!PyUnicode_Check(v)) {
3459 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003460 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003461 Py_TYPE(v)->tp_name);
3462 Py_DECREF(v);
3463 goto onError;
3464 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003465 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003466
Benjamin Peterson29060642009-01-31 22:14:21 +00003467 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468 return NULL;
3469}
3470
Victor Stinner2f197072011-12-17 07:08:30 +01003471static size_t
3472mbstowcs_errorpos(const char *str, size_t len)
3473{
3474#ifdef HAVE_MBRTOWC
3475 const char *start = str;
3476 mbstate_t mbs;
3477 size_t converted;
3478 wchar_t ch;
3479
3480 memset(&mbs, 0, sizeof mbs);
3481 while (len)
3482 {
3483 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3484 if (converted == 0)
3485 /* Reached end of string */
3486 break;
3487 if (converted == (size_t)-1 || converted == (size_t)-2) {
3488 /* Conversion error or incomplete character */
3489 return str - start;
3490 }
3491 else {
3492 str += converted;
3493 len -= converted;
3494 }
3495 }
3496 /* failed to find the undecodable byte sequence */
3497 return 0;
3498#endif
3499 return 0;
3500}
3501
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003502PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003503PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003504 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003505{
3506 wchar_t smallbuf[256];
3507 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3508 wchar_t *wstr;
3509 size_t wlen, wlen2;
3510 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003511 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003512 size_t error_pos;
3513 char *errmsg;
3514 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003515
3516 if (locale_error_handler(errors, &surrogateescape) < 0)
3517 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003518
3519 if (str[len] != '\0' || len != strlen(str)) {
3520 PyErr_SetString(PyExc_TypeError, "embedded null character");
3521 return NULL;
3522 }
3523
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003524 if (surrogateescape) {
3525 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003526 wstr = _Py_char2wchar(str, &wlen);
3527 if (wstr == NULL) {
3528 if (wlen == (size_t)-1)
3529 PyErr_NoMemory();
3530 else
3531 PyErr_SetFromErrno(PyExc_OSError);
3532 return NULL;
3533 }
3534
3535 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003536 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003537 }
3538 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003539 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003540#ifndef HAVE_BROKEN_MBSTOWCS
3541 wlen = mbstowcs(NULL, str, 0);
3542#else
3543 wlen = len;
3544#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003545 if (wlen == (size_t)-1)
3546 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003547 if (wlen+1 <= smallbuf_len) {
3548 wstr = smallbuf;
3549 }
3550 else {
3551 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3552 return PyErr_NoMemory();
3553
3554 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3555 if (!wstr)
3556 return PyErr_NoMemory();
3557 }
3558
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003559 wlen2 = mbstowcs(wstr, str, wlen+1);
3560 if (wlen2 == (size_t)-1) {
3561 if (wstr != smallbuf)
3562 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003563 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003564 }
3565#ifdef HAVE_BROKEN_MBSTOWCS
3566 assert(wlen2 == wlen);
3567#endif
3568 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3569 if (wstr != smallbuf)
3570 PyMem_Free(wstr);
3571 }
3572 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003573
3574decode_error:
3575 errmsg = strerror(errno);
3576 assert(errmsg != NULL);
3577
3578 error_pos = mbstowcs_errorpos(str, len);
3579 if (errmsg != NULL) {
3580 size_t errlen;
3581 wstr = _Py_char2wchar(errmsg, &errlen);
3582 if (wstr != NULL) {
3583 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003584 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003585 } else
3586 errmsg = NULL;
3587 }
3588 if (errmsg == NULL)
3589 reason = PyUnicode_FromString(
3590 "mbstowcs() encountered an invalid multibyte sequence");
3591 if (reason == NULL)
3592 return NULL;
3593
3594 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3595 "locale", str, len,
3596 (Py_ssize_t)error_pos,
3597 (Py_ssize_t)(error_pos+1),
3598 reason);
3599 Py_DECREF(reason);
3600 if (exc != NULL) {
3601 PyCodec_StrictErrors(exc);
3602 Py_XDECREF(exc);
3603 }
3604 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003605}
3606
3607PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003608PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003609{
3610 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003611 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003612}
3613
3614
3615PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003616PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003617 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003618 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3619}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620
Christian Heimes5894ba72007-11-04 11:43:14 +00003621PyObject*
3622PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3623{
Victor Stinner99b95382011-07-04 14:23:54 +02003624#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003625 return PyUnicode_DecodeMBCS(s, size, NULL);
3626#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003627 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003628#else
Victor Stinner793b5312011-04-27 00:24:21 +02003629 PyInterpreterState *interp = PyThreadState_GET()->interp;
3630 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3631 cannot use it to encode and decode filenames before it is loaded. Load
3632 the Python codec requires to encode at least its own filename. Use the C
3633 version of the locale codec until the codec registry is initialized and
3634 the Python codec is loaded.
3635
3636 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3637 cannot only rely on it: check also interp->fscodec_initialized for
3638 subinterpreters. */
3639 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003640 return PyUnicode_Decode(s, size,
3641 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003642 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003643 }
3644 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003645 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003646 }
Victor Stinnerad158722010-10-27 00:25:46 +00003647#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003648}
3649
Martin v. Löwis011e8422009-05-05 04:43:17 +00003650
3651int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003652_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003653{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003654 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003655
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003656 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003657 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003658 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3659 PyUnicode_GET_LENGTH(str), '\0', 1);
3660 if (pos == -1)
3661 return 0;
3662 else
3663 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003664}
3665
Antoine Pitrou13348842012-01-29 18:36:34 +01003666int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003667PyUnicode_FSConverter(PyObject* arg, void* addr)
3668{
3669 PyObject *output = NULL;
3670 Py_ssize_t size;
3671 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003672 if (arg == NULL) {
3673 Py_DECREF(*(PyObject**)addr);
3674 return 1;
3675 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003676 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003677 output = arg;
3678 Py_INCREF(output);
3679 }
3680 else {
3681 arg = PyUnicode_FromObject(arg);
3682 if (!arg)
3683 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003684 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003685 Py_DECREF(arg);
3686 if (!output)
3687 return 0;
3688 if (!PyBytes_Check(output)) {
3689 Py_DECREF(output);
3690 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3691 return 0;
3692 }
3693 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003694 size = PyBytes_GET_SIZE(output);
3695 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003696 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003697 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003698 Py_DECREF(output);
3699 return 0;
3700 }
3701 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003702 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003703}
3704
3705
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003706int
3707PyUnicode_FSDecoder(PyObject* arg, void* addr)
3708{
3709 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003710 if (arg == NULL) {
3711 Py_DECREF(*(PyObject**)addr);
3712 return 1;
3713 }
3714 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003715 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003716 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003717 output = arg;
3718 Py_INCREF(output);
3719 }
3720 else {
3721 arg = PyBytes_FromObject(arg);
3722 if (!arg)
3723 return 0;
3724 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3725 PyBytes_GET_SIZE(arg));
3726 Py_DECREF(arg);
3727 if (!output)
3728 return 0;
3729 if (!PyUnicode_Check(output)) {
3730 Py_DECREF(output);
3731 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3732 return 0;
3733 }
3734 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003735 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003736 Py_DECREF(output);
3737 return 0;
3738 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003740 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003741 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3742 Py_DECREF(output);
3743 return 0;
3744 }
3745 *(PyObject**)addr = output;
3746 return Py_CLEANUP_SUPPORTED;
3747}
3748
3749
Martin v. Löwis5b222132007-06-10 09:51:05 +00003750char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003752{
Christian Heimesf3863112007-11-22 07:46:41 +00003753 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003754
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003755 if (!PyUnicode_Check(unicode)) {
3756 PyErr_BadArgument();
3757 return NULL;
3758 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003759 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003760 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003762 if (PyUnicode_UTF8(unicode) == NULL) {
3763 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3765 if (bytes == NULL)
3766 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003767 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3768 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003769 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003770 Py_DECREF(bytes);
3771 return NULL;
3772 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003773 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3774 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3775 PyBytes_AS_STRING(bytes),
3776 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777 Py_DECREF(bytes);
3778 }
3779
3780 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003781 *psize = PyUnicode_UTF8_LENGTH(unicode);
3782 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003783}
3784
3785char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003786PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003787{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3789}
3790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791Py_UNICODE *
3792PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3793{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003794 const unsigned char *one_byte;
3795#if SIZEOF_WCHAR_T == 4
3796 const Py_UCS2 *two_bytes;
3797#else
3798 const Py_UCS4 *four_bytes;
3799 const Py_UCS4 *ucs4_end;
3800 Py_ssize_t num_surrogates;
3801#endif
3802 wchar_t *w;
3803 wchar_t *wchar_end;
3804
3805 if (!PyUnicode_Check(unicode)) {
3806 PyErr_BadArgument();
3807 return NULL;
3808 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003809 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003810 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003811 assert(_PyUnicode_KIND(unicode) != 0);
3812 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3817 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818 num_surrogates = 0;
3819
3820 for (; four_bytes < ucs4_end; ++four_bytes) {
3821 if (*four_bytes > 0xFFFF)
3822 ++num_surrogates;
3823 }
3824
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003825 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3826 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3827 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003828 PyErr_NoMemory();
3829 return NULL;
3830 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003831 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003832
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003833 w = _PyUnicode_WSTR(unicode);
3834 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3835 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3837 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003838 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003840 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3841 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 }
3843 else
3844 *w = *four_bytes;
3845
3846 if (w > wchar_end) {
3847 assert(0 && "Miscalculated string end");
3848 }
3849 }
3850 *w = 0;
3851#else
3852 /* sizeof(wchar_t) == 4 */
3853 Py_FatalError("Impossible unicode object state, wstr and str "
3854 "should share memory already.");
3855 return NULL;
3856#endif
3857 }
3858 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003859 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3860 (_PyUnicode_LENGTH(unicode) + 1));
3861 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862 PyErr_NoMemory();
3863 return NULL;
3864 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003865 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3866 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3867 w = _PyUnicode_WSTR(unicode);
3868 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003870 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3871 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872 for (; w < wchar_end; ++one_byte, ++w)
3873 *w = *one_byte;
3874 /* null-terminate the wstr */
3875 *w = 0;
3876 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003879 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880 for (; w < wchar_end; ++two_bytes, ++w)
3881 *w = *two_bytes;
3882 /* null-terminate the wstr */
3883 *w = 0;
3884#else
3885 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003886 PyObject_FREE(_PyUnicode_WSTR(unicode));
3887 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003888 Py_FatalError("Impossible unicode object state, wstr "
3889 "and str should share memory already.");
3890 return NULL;
3891#endif
3892 }
3893 else {
3894 assert(0 && "This should never happen.");
3895 }
3896 }
3897 }
3898 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003899 *size = PyUnicode_WSTR_LENGTH(unicode);
3900 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003901}
3902
Alexander Belopolsky40018472011-02-26 01:02:56 +00003903Py_UNICODE *
3904PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907}
3908
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909
Alexander Belopolsky40018472011-02-26 01:02:56 +00003910Py_ssize_t
3911PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003912{
3913 if (!PyUnicode_Check(unicode)) {
3914 PyErr_BadArgument();
3915 goto onError;
3916 }
3917 return PyUnicode_GET_SIZE(unicode);
3918
Benjamin Peterson29060642009-01-31 22:14:21 +00003919 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003920 return -1;
3921}
3922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923Py_ssize_t
3924PyUnicode_GetLength(PyObject *unicode)
3925{
Victor Stinner07621332012-06-16 04:53:46 +02003926 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003927 PyErr_BadArgument();
3928 return -1;
3929 }
Victor Stinner07621332012-06-16 04:53:46 +02003930 if (PyUnicode_READY(unicode) == -1)
3931 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003932 return PyUnicode_GET_LENGTH(unicode);
3933}
3934
3935Py_UCS4
3936PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3937{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003938 void *data;
3939 int kind;
3940
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003941 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3942 PyErr_BadArgument();
3943 return (Py_UCS4)-1;
3944 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003945 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003946 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003947 return (Py_UCS4)-1;
3948 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003949 data = PyUnicode_DATA(unicode);
3950 kind = PyUnicode_KIND(unicode);
3951 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952}
3953
3954int
3955PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3956{
3957 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003958 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959 return -1;
3960 }
Victor Stinner488fa492011-12-12 00:01:39 +01003961 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003962 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003963 PyErr_SetString(PyExc_IndexError, "string index out of range");
3964 return -1;
3965 }
Victor Stinner488fa492011-12-12 00:01:39 +01003966 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003967 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003968 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3969 PyErr_SetString(PyExc_ValueError, "character out of range");
3970 return -1;
3971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3973 index, ch);
3974 return 0;
3975}
3976
Alexander Belopolsky40018472011-02-26 01:02:56 +00003977const char *
3978PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003979{
Victor Stinner42cb4622010-09-01 19:39:01 +00003980 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003981}
3982
Victor Stinner554f3f02010-06-16 23:33:54 +00003983/* create or adjust a UnicodeDecodeError */
3984static void
3985make_decode_exception(PyObject **exceptionObject,
3986 const char *encoding,
3987 const char *input, Py_ssize_t length,
3988 Py_ssize_t startpos, Py_ssize_t endpos,
3989 const char *reason)
3990{
3991 if (*exceptionObject == NULL) {
3992 *exceptionObject = PyUnicodeDecodeError_Create(
3993 encoding, input, length, startpos, endpos, reason);
3994 }
3995 else {
3996 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3997 goto onError;
3998 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3999 goto onError;
4000 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4001 goto onError;
4002 }
4003 return;
4004
4005onError:
4006 Py_DECREF(*exceptionObject);
4007 *exceptionObject = NULL;
4008}
4009
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004010#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004011/* error handling callback helper:
4012 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004013 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014 and adjust various state variables.
4015 return 0 on success, -1 on error
4016*/
4017
Alexander Belopolsky40018472011-02-26 01:02:56 +00004018static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004019unicode_decode_call_errorhandler_wchar(
4020 const char *errors, PyObject **errorHandler,
4021 const char *encoding, const char *reason,
4022 const char **input, const char **inend, Py_ssize_t *startinpos,
4023 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4024 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004026 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027
4028 PyObject *restuple = NULL;
4029 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004030 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004031 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004032 Py_ssize_t requiredsize;
4033 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004034 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004035 wchar_t *repwstr;
4036 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004037
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004038 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4039 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004040
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004041 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004042 *errorHandler = PyCodec_LookupError(errors);
4043 if (*errorHandler == NULL)
4044 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004045 }
4046
Victor Stinner554f3f02010-06-16 23:33:54 +00004047 make_decode_exception(exceptionObject,
4048 encoding,
4049 *input, *inend - *input,
4050 *startinpos, *endinpos,
4051 reason);
4052 if (*exceptionObject == NULL)
4053 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004054
4055 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4056 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004057 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004058 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004059 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004060 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004061 }
4062 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004063 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004064
4065 /* Copy back the bytes variables, which might have been modified by the
4066 callback */
4067 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4068 if (!inputobj)
4069 goto onError;
4070 if (!PyBytes_Check(inputobj)) {
4071 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4072 }
4073 *input = PyBytes_AS_STRING(inputobj);
4074 insize = PyBytes_GET_SIZE(inputobj);
4075 *inend = *input + insize;
4076 /* we can DECREF safely, as the exception has another reference,
4077 so the object won't go away. */
4078 Py_DECREF(inputobj);
4079
4080 if (newpos<0)
4081 newpos = insize+newpos;
4082 if (newpos<0 || newpos>insize) {
4083 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4084 goto onError;
4085 }
4086
4087 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4088 if (repwstr == NULL)
4089 goto onError;
4090 /* need more space? (at least enough for what we
4091 have+the replacement+the rest of the string (starting
4092 at the new input position), so we won't have to check space
4093 when there are no errors in the rest of the string) */
4094 requiredsize = *outpos + repwlen + insize-newpos;
4095 if (requiredsize > outsize) {
4096 if (requiredsize < 2*outsize)
4097 requiredsize = 2*outsize;
4098 if (unicode_resize(output, requiredsize) < 0)
4099 goto onError;
4100 }
4101 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4102 *outpos += repwlen;
4103
4104 *endinpos = newpos;
4105 *inptr = *input + newpos;
4106
4107 /* we made it! */
4108 Py_XDECREF(restuple);
4109 return 0;
4110
4111 onError:
4112 Py_XDECREF(restuple);
4113 return -1;
4114}
4115#endif /* HAVE_MBCS */
4116
4117static int
4118unicode_decode_call_errorhandler_writer(
4119 const char *errors, PyObject **errorHandler,
4120 const char *encoding, const char *reason,
4121 const char **input, const char **inend, Py_ssize_t *startinpos,
4122 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4123 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4124{
4125 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4126
4127 PyObject *restuple = NULL;
4128 PyObject *repunicode = NULL;
4129 Py_ssize_t insize;
4130 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004131 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004132 PyObject *inputobj = NULL;
4133
4134 if (*errorHandler == NULL) {
4135 *errorHandler = PyCodec_LookupError(errors);
4136 if (*errorHandler == NULL)
4137 goto onError;
4138 }
4139
4140 make_decode_exception(exceptionObject,
4141 encoding,
4142 *input, *inend - *input,
4143 *startinpos, *endinpos,
4144 reason);
4145 if (*exceptionObject == NULL)
4146 goto onError;
4147
4148 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4149 if (restuple == NULL)
4150 goto onError;
4151 if (!PyTuple_Check(restuple)) {
4152 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4153 goto onError;
4154 }
4155 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004156 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004157
4158 /* Copy back the bytes variables, which might have been modified by the
4159 callback */
4160 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4161 if (!inputobj)
4162 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004163 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004164 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004165 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004166 *input = PyBytes_AS_STRING(inputobj);
4167 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004168 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004169 /* we can DECREF safely, as the exception has another reference,
4170 so the object won't go away. */
4171 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004172
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004173 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004174 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004175 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4177 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004178 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004179
Victor Stinner8f674cc2013-04-17 23:02:17 +02004180 if (PyUnicode_READY(repunicode) < 0)
4181 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004182 replen = PyUnicode_GET_LENGTH(repunicode);
4183 writer->min_length += replen;
4184 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004185 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004186 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004187 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004189 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004190 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004191
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004192 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004193 Py_XDECREF(restuple);
4194 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004195
Benjamin Peterson29060642009-01-31 22:14:21 +00004196 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004198 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199}
4200
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004201/* --- UTF-7 Codec -------------------------------------------------------- */
4202
Antoine Pitrou244651a2009-05-04 18:56:13 +00004203/* See RFC2152 for details. We encode conservatively and decode liberally. */
4204
4205/* Three simple macros defining base-64. */
4206
4207/* Is c a base-64 character? */
4208
4209#define IS_BASE64(c) \
4210 (((c) >= 'A' && (c) <= 'Z') || \
4211 ((c) >= 'a' && (c) <= 'z') || \
4212 ((c) >= '0' && (c) <= '9') || \
4213 (c) == '+' || (c) == '/')
4214
4215/* given that c is a base-64 character, what is its base-64 value? */
4216
4217#define FROM_BASE64(c) \
4218 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4219 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4220 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4221 (c) == '+' ? 62 : 63)
4222
4223/* What is the base-64 character of the bottom 6 bits of n? */
4224
4225#define TO_BASE64(n) \
4226 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4227
4228/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4229 * decoded as itself. We are permissive on decoding; the only ASCII
4230 * byte not decoding to itself is the + which begins a base64
4231 * string. */
4232
4233#define DECODE_DIRECT(c) \
4234 ((c) <= 127 && (c) != '+')
4235
4236/* The UTF-7 encoder treats ASCII characters differently according to
4237 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4238 * the above). See RFC2152. This array identifies these different
4239 * sets:
4240 * 0 : "Set D"
4241 * alphanumeric and '(),-./:?
4242 * 1 : "Set O"
4243 * !"#$%&*;<=>@[]^_`{|}
4244 * 2 : "whitespace"
4245 * ht nl cr sp
4246 * 3 : special (must be base64 encoded)
4247 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4248 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004249
Tim Petersced69f82003-09-16 20:30:58 +00004250static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004251char utf7_category[128] = {
4252/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4253 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4254/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4255 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4256/* sp ! " # $ % & ' ( ) * + , - . / */
4257 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4258/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4259 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4260/* @ A B C D E F G H I J K L M N O */
4261 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4262/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4263 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4264/* ` a b c d e f g h i j k l m n o */
4265 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4266/* p q r s t u v w x y z { | } ~ del */
4267 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004268};
4269
Antoine Pitrou244651a2009-05-04 18:56:13 +00004270/* ENCODE_DIRECT: this character should be encoded as itself. The
4271 * answer depends on whether we are encoding set O as itself, and also
4272 * on whether we are encoding whitespace as itself. RFC2152 makes it
4273 * clear that the answers to these questions vary between
4274 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004275
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276#define ENCODE_DIRECT(c, directO, directWS) \
4277 ((c) < 128 && (c) > 0 && \
4278 ((utf7_category[(c)] == 0) || \
4279 (directWS && (utf7_category[(c)] == 2)) || \
4280 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281
Alexander Belopolsky40018472011-02-26 01:02:56 +00004282PyObject *
4283PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004284 Py_ssize_t size,
4285 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004286{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004287 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4288}
4289
Antoine Pitrou244651a2009-05-04 18:56:13 +00004290/* The decoder. The only state we preserve is our read position,
4291 * i.e. how many characters we have consumed. So if we end in the
4292 * middle of a shift sequence we have to back off the read position
4293 * and the output to the beginning of the sequence, otherwise we lose
4294 * all the shift state (seen bits, number of bits seen, high
4295 * surrogate). */
4296
Alexander Belopolsky40018472011-02-26 01:02:56 +00004297PyObject *
4298PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004299 Py_ssize_t size,
4300 const char *errors,
4301 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004302{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004303 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004304 Py_ssize_t startinpos;
4305 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004306 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004307 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 const char *errmsg = "";
4309 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004310 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004311 unsigned int base64bits = 0;
4312 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004313 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004314 PyObject *errorHandler = NULL;
4315 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004317 if (size == 0) {
4318 if (consumed)
4319 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004320 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004321 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004323 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004324 _PyUnicodeWriter_Init(&writer);
4325 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004326
4327 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004328 e = s + size;
4329
4330 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004331 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004332 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004333 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004334
Antoine Pitrou244651a2009-05-04 18:56:13 +00004335 if (inShift) { /* in a base-64 section */
4336 if (IS_BASE64(ch)) { /* consume a base-64 character */
4337 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4338 base64bits += 6;
4339 s++;
4340 if (base64bits >= 16) {
4341 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004342 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343 base64bits -= 16;
4344 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004345 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 if (surrogate) {
4347 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004348 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4349 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004350 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004351 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004353 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 }
4355 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004356 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004357 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 }
4360 }
Victor Stinner551ac952011-11-29 22:58:13 +01004361 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 /* first surrogate */
4363 surrogate = outCh;
4364 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004366 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004367 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 }
4369 }
4370 }
4371 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004372 inShift = 0;
4373 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004375 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004376 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004377 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 if (base64bits > 0) { /* left-over bits */
4380 if (base64bits >= 6) {
4381 /* We've seen at least one base-64 character */
4382 errmsg = "partial character in shift sequence";
4383 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 else {
4386 /* Some bits remain; they should be zero */
4387 if (base64buffer != 0) {
4388 errmsg = "non-zero padding bits in shift sequence";
4389 goto utf7Error;
4390 }
4391 }
4392 }
4393 if (ch != '-') {
4394 /* '-' is absorbed; other terminating
4395 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004396 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004397 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004398 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004399 }
4400 }
4401 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004402 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 s++; /* consume '+' */
4404 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004406 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004407 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 }
4409 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004411 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004413 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 }
4415 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004418 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004419 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004420 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004421 else {
4422 startinpos = s-starts;
4423 s++;
4424 errmsg = "unexpected special character";
4425 goto utf7Error;
4426 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004427 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004428utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004429 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004430 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004431 errors, &errorHandler,
4432 "utf7", errmsg,
4433 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004434 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004435 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004436 }
4437
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 /* end of string */
4439
4440 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4441 /* if we're in an inconsistent state, that's an error */
4442 if (surrogate ||
4443 (base64bits >= 6) ||
4444 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004446 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 errors, &errorHandler,
4448 "utf7", "unterminated shift sequence",
4449 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004450 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 goto onError;
4452 if (s < e)
4453 goto restart;
4454 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004455 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456
4457 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004458 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004459 if (inShift) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004460 writer.pos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004461 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 }
4463 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004464 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004465 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004467
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004468 Py_XDECREF(errorHandler);
4469 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 Py_XDECREF(errorHandler);
4474 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004475 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004476 return NULL;
4477}
4478
4479
Alexander Belopolsky40018472011-02-26 01:02:56 +00004480PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004481_PyUnicode_EncodeUTF7(PyObject *str,
4482 int base64SetO,
4483 int base64WhiteSpace,
4484 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004486 int kind;
4487 void *data;
4488 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004489 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492 unsigned int base64bits = 0;
4493 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 char * out;
4495 char * start;
4496
Benjamin Petersonbac79492012-01-14 13:34:47 -05004497 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004498 return NULL;
4499 kind = PyUnicode_KIND(str);
4500 data = PyUnicode_DATA(str);
4501 len = PyUnicode_GET_LENGTH(str);
4502
4503 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004504 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004506 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004507 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004508 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004509 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004510 if (v == NULL)
4511 return NULL;
4512
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004513 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004514 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004515 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004516
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 if (inShift) {
4518 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4519 /* shifting out */
4520 if (base64bits) { /* output remaining bits */
4521 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4522 base64buffer = 0;
4523 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 }
4525 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 /* Characters not in the BASE64 set implicitly unshift the sequence
4527 so no '-' is required, except if the character is itself a '-' */
4528 if (IS_BASE64(ch) || ch == '-') {
4529 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 *out++ = (char) ch;
4532 }
4533 else {
4534 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004535 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004537 else { /* not in a shift sequence */
4538 if (ch == '+') {
4539 *out++ = '+';
4540 *out++ = '-';
4541 }
4542 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4543 *out++ = (char) ch;
4544 }
4545 else {
4546 *out++ = '+';
4547 inShift = 1;
4548 goto encode_char;
4549 }
4550 }
4551 continue;
4552encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004553 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004554 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004555
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556 /* code first surrogate */
4557 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004558 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004559 while (base64bits >= 6) {
4560 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4561 base64bits -= 6;
4562 }
4563 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004564 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 base64bits += 16;
4567 base64buffer = (base64buffer << 16) | ch;
4568 while (base64bits >= 6) {
4569 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4570 base64bits -= 6;
4571 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004572 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 if (base64bits)
4574 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4575 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004576 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004577 if (_PyBytes_Resize(&v, out - start) < 0)
4578 return NULL;
4579 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004580}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004581PyObject *
4582PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4583 Py_ssize_t size,
4584 int base64SetO,
4585 int base64WhiteSpace,
4586 const char *errors)
4587{
4588 PyObject *result;
4589 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4590 if (tmp == NULL)
4591 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004592 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004593 base64WhiteSpace, errors);
4594 Py_DECREF(tmp);
4595 return result;
4596}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004597
Antoine Pitrou244651a2009-05-04 18:56:13 +00004598#undef IS_BASE64
4599#undef FROM_BASE64
4600#undef TO_BASE64
4601#undef DECODE_DIRECT
4602#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603
Guido van Rossumd57fd912000-03-10 22:53:23 +00004604/* --- UTF-8 Codec -------------------------------------------------------- */
4605
Alexander Belopolsky40018472011-02-26 01:02:56 +00004606PyObject *
4607PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004608 Py_ssize_t size,
4609 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004610{
Walter Dörwald69652032004-09-07 20:24:22 +00004611 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4612}
4613
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004614#include "stringlib/asciilib.h"
4615#include "stringlib/codecs.h"
4616#include "stringlib/undef.h"
4617
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004618#include "stringlib/ucs1lib.h"
4619#include "stringlib/codecs.h"
4620#include "stringlib/undef.h"
4621
4622#include "stringlib/ucs2lib.h"
4623#include "stringlib/codecs.h"
4624#include "stringlib/undef.h"
4625
4626#include "stringlib/ucs4lib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
Antoine Pitrouab868312009-01-10 15:40:25 +00004630/* Mask to quickly check whether a C 'long' contains a
4631 non-ASCII, UTF8-encoded char. */
4632#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004633# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004634#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004635# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004636#else
4637# error C 'long' size should be either 4 or 8!
4638#endif
4639
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004640static Py_ssize_t
4641ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004642{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004643 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004644 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004645
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004646 /*
4647 * Issue #17237: m68k is a bit different from most architectures in
4648 * that objects do not use "natural alignment" - for example, int and
4649 * long are only aligned at 2-byte boundaries. Therefore the assert()
4650 * won't work; also, tests have shown that skipping the "optimised
4651 * version" will even speed up m68k.
4652 */
4653#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004655 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4656 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 /* Fast path, see in STRINGLIB(utf8_decode) for
4658 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004659 /* Help allocation */
4660 const char *_p = p;
4661 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004662 while (_p < aligned_end) {
4663 unsigned long value = *(const unsigned long *) _p;
4664 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004665 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004666 *((unsigned long *)q) = value;
4667 _p += SIZEOF_LONG;
4668 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004669 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004670 p = _p;
4671 while (p < end) {
4672 if ((unsigned char)*p & 0x80)
4673 break;
4674 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004675 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004677 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004679#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 while (p < end) {
4681 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4682 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004683 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004684 /* Help allocation */
4685 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004686 while (_p < aligned_end) {
4687 unsigned long value = *(unsigned long *) _p;
4688 if (value & ASCII_CHAR_MASK)
4689 break;
4690 _p += SIZEOF_LONG;
4691 }
4692 p = _p;
4693 if (_p == end)
4694 break;
4695 }
4696 if ((unsigned char)*p & 0x80)
4697 break;
4698 ++p;
4699 }
4700 memcpy(dest, start, p - start);
4701 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004702}
Antoine Pitrouab868312009-01-10 15:40:25 +00004703
Victor Stinner785938e2011-12-11 20:09:03 +01004704PyObject *
4705PyUnicode_DecodeUTF8Stateful(const char *s,
4706 Py_ssize_t size,
4707 const char *errors,
4708 Py_ssize_t *consumed)
4709{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004710 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004711 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004713
4714 Py_ssize_t startinpos;
4715 Py_ssize_t endinpos;
4716 const char *errmsg = "";
4717 PyObject *errorHandler = NULL;
4718 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004719
4720 if (size == 0) {
4721 if (consumed)
4722 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004723 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004724 }
4725
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4727 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004728 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004729 *consumed = 1;
4730 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004731 }
4732
Victor Stinner8f674cc2013-04-17 23:02:17 +02004733 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004734 writer.min_length = size;
4735 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004736 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004737
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004738 writer.pos = ascii_decode(s, end, writer.data);
4739 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004740 while (s < end) {
4741 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004742 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004743 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004744 if (PyUnicode_IS_ASCII(writer.buffer))
4745 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004746 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004747 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004749 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 } else {
4751 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004752 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 }
4754
4755 switch (ch) {
4756 case 0:
4757 if (s == end || consumed)
4758 goto End;
4759 errmsg = "unexpected end of data";
4760 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004761 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 break;
4763 case 1:
4764 errmsg = "invalid start byte";
4765 startinpos = s - starts;
4766 endinpos = startinpos + 1;
4767 break;
4768 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004769 case 3:
4770 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 errmsg = "invalid continuation byte";
4772 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004773 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774 break;
4775 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004776 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777 goto onError;
4778 continue;
4779 }
4780
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004781 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004782 errors, &errorHandler,
4783 "utf-8", errmsg,
4784 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004785 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004786 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004787 }
4788
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004789End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004790 if (consumed)
4791 *consumed = s - starts;
4792
4793 Py_XDECREF(errorHandler);
4794 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004795 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796
4797onError:
4798 Py_XDECREF(errorHandler);
4799 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004800 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004802}
4803
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004804#ifdef __APPLE__
4805
4806/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004807 used to decode the command line arguments on Mac OS X.
4808
4809 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004810 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004811
4812wchar_t*
4813_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4814{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004815 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004816 wchar_t *unicode;
4817 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004818
4819 /* Note: size will always be longer than the resulting Unicode
4820 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004821 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004823 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004824 if (!unicode)
4825 return NULL;
4826
4827 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004828 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004829 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004830 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004831 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 if (ch > 0xFF) {
4838#if SIZEOF_WCHAR_T == 4
4839 assert(0);
4840#else
4841 assert(Py_UNICODE_IS_SURROGATE(ch));
4842 /* compute and append the two surrogates: */
4843 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4844 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4845#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 else {
4848 if (!ch && s == e)
4849 break;
4850 /* surrogateescape */
4851 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4852 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004853 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004854 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004855 return unicode;
4856}
4857
4858#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004860/* Primary internal function which creates utf8 encoded bytes objects.
4861
4862 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004863 and allocate exactly as much space needed at the end. Else allocate the
4864 maximum possible needed (4 result bytes per Unicode character), and return
4865 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004866*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004867PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004868_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004869{
Victor Stinner6099a032011-12-18 14:22:26 +01004870 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004871 void *data;
4872 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004874 if (!PyUnicode_Check(unicode)) {
4875 PyErr_BadArgument();
4876 return NULL;
4877 }
4878
4879 if (PyUnicode_READY(unicode) == -1)
4880 return NULL;
4881
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004882 if (PyUnicode_UTF8(unicode))
4883 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4884 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004885
4886 kind = PyUnicode_KIND(unicode);
4887 data = PyUnicode_DATA(unicode);
4888 size = PyUnicode_GET_LENGTH(unicode);
4889
Benjamin Petersonead6b532011-12-20 17:23:42 -06004890 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004891 default:
4892 assert(0);
4893 case PyUnicode_1BYTE_KIND:
4894 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4895 assert(!PyUnicode_IS_ASCII(unicode));
4896 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4897 case PyUnicode_2BYTE_KIND:
4898 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4899 case PyUnicode_4BYTE_KIND:
4900 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004901 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004902}
4903
Alexander Belopolsky40018472011-02-26 01:02:56 +00004904PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004905PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4906 Py_ssize_t size,
4907 const char *errors)
4908{
4909 PyObject *v, *unicode;
4910
4911 unicode = PyUnicode_FromUnicode(s, size);
4912 if (unicode == NULL)
4913 return NULL;
4914 v = _PyUnicode_AsUTF8String(unicode, errors);
4915 Py_DECREF(unicode);
4916 return v;
4917}
4918
4919PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004920PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004921{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004922 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004923}
4924
Walter Dörwald41980ca2007-08-16 21:55:45 +00004925/* --- UTF-32 Codec ------------------------------------------------------- */
4926
4927PyObject *
4928PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004929 Py_ssize_t size,
4930 const char *errors,
4931 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004932{
4933 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4934}
4935
4936PyObject *
4937PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004938 Py_ssize_t size,
4939 const char *errors,
4940 int *byteorder,
4941 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942{
4943 const char *starts = s;
4944 Py_ssize_t startinpos;
4945 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004946 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004947 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004948 int le, bo = 0; /* assume native ordering by default */
Walter Dörwald41980ca2007-08-16 21:55:45 +00004949 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950 PyObject *errorHandler = NULL;
4951 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004952
Walter Dörwald41980ca2007-08-16 21:55:45 +00004953 q = (unsigned char *)s;
4954 e = q + size;
4955
4956 if (byteorder)
4957 bo = *byteorder;
4958
4959 /* Check for BOM marks (U+FEFF) in the input and adjust current
4960 byte order setting accordingly. In native mode, the leading BOM
4961 mark is skipped, in all other modes, it is copied to the output
4962 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004963 if (bo == 0 && size >= 4) {
4964 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4965 if (bom == 0x0000FEFF) {
4966 bo = -1;
4967 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004968 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004969 else if (bom == 0xFFFE0000) {
4970 bo = 1;
4971 q += 4;
4972 }
4973 if (byteorder)
4974 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004975 }
4976
Victor Stinnere64322e2012-10-30 23:12:47 +01004977 if (q == e) {
4978 if (consumed)
4979 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004980 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004981 }
4982
Victor Stinnere64322e2012-10-30 23:12:47 +01004983#ifdef WORDS_BIGENDIAN
4984 le = bo < 0;
4985#else
4986 le = bo <= 0;
4987#endif
4988
Victor Stinner8f674cc2013-04-17 23:02:17 +02004989 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004990 writer.min_length = (e - q + 3) / 4;
4991 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004992 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004993
Victor Stinnere64322e2012-10-30 23:12:47 +01004994 while (1) {
4995 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004996 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004997
Victor Stinnere64322e2012-10-30 23:12:47 +01004998 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004999 enum PyUnicode_Kind kind = writer.kind;
5000 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005001 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005002 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005003 if (le) {
5004 do {
5005 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5006 if (ch > maxch)
5007 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005009 q += 4;
5010 } while (q <= last);
5011 }
5012 else {
5013 do {
5014 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5015 if (ch > maxch)
5016 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005017 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005018 q += 4;
5019 } while (q <= last);
5020 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005021 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005022 }
5023
5024 if (ch <= maxch) {
5025 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005026 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005027 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005028 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005029 startinpos = ((const char *)q) - starts;
5030 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005032 else {
5033 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005034 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005035 goto onError;
5036 q += 4;
5037 continue;
5038 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005040 startinpos = ((const char *)q) - starts;
5041 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005043
5044 /* The remaining input chars are ignored if the callback
5045 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005046 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005047 errors, &errorHandler,
5048 "utf32", errmsg,
5049 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005050 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052 }
5053
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057 Py_XDECREF(errorHandler);
5058 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005059 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060
Benjamin Peterson29060642009-01-31 22:14:21 +00005061 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005062 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005063 Py_XDECREF(errorHandler);
5064 Py_XDECREF(exc);
5065 return NULL;
5066}
5067
5068PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005069_PyUnicode_EncodeUTF32(PyObject *str,
5070 const char *errors,
5071 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005073 int kind;
5074 void *data;
5075 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005076 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005078 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005080#if PY_LITTLE_ENDIAN
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081 int iorder[] = {0, 1, 2, 3};
5082#else
5083 int iorder[] = {3, 2, 1, 0};
5084#endif
5085
Benjamin Peterson29060642009-01-31 22:14:21 +00005086#define STORECHAR(CH) \
5087 do { \
5088 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5089 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5090 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5091 p[iorder[0]] = (CH) & 0xff; \
5092 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093 } while(0)
5094
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005095 if (!PyUnicode_Check(str)) {
5096 PyErr_BadArgument();
5097 return NULL;
5098 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005099 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005100 return NULL;
5101 kind = PyUnicode_KIND(str);
5102 data = PyUnicode_DATA(str);
5103 len = PyUnicode_GET_LENGTH(str);
5104
5105 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005106 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005107 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005108 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005109 if (v == NULL)
5110 return NULL;
5111
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005112 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005114 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005115 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005116 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117
5118 if (byteorder == -1) {
5119 /* force LE */
5120 iorder[0] = 0;
5121 iorder[1] = 1;
5122 iorder[2] = 2;
5123 iorder[3] = 3;
5124 }
5125 else if (byteorder == 1) {
5126 /* force BE */
5127 iorder[0] = 3;
5128 iorder[1] = 2;
5129 iorder[2] = 1;
5130 iorder[3] = 0;
5131 }
5132
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005133 for (i = 0; i < len; i++)
5134 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005135
5136 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005137 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138#undef STORECHAR
5139}
5140
Alexander Belopolsky40018472011-02-26 01:02:56 +00005141PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005142PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5143 Py_ssize_t size,
5144 const char *errors,
5145 int byteorder)
5146{
5147 PyObject *result;
5148 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5149 if (tmp == NULL)
5150 return NULL;
5151 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5152 Py_DECREF(tmp);
5153 return result;
5154}
5155
5156PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005157PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005158{
Victor Stinnerb960b342011-11-20 19:12:52 +01005159 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005160}
5161
Guido van Rossumd57fd912000-03-10 22:53:23 +00005162/* --- UTF-16 Codec ------------------------------------------------------- */
5163
Tim Peters772747b2001-08-09 22:21:55 +00005164PyObject *
5165PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005166 Py_ssize_t size,
5167 const char *errors,
5168 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005169{
Walter Dörwald69652032004-09-07 20:24:22 +00005170 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5171}
5172
5173PyObject *
5174PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005175 Py_ssize_t size,
5176 const char *errors,
5177 int *byteorder,
5178 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005179{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005180 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005181 Py_ssize_t startinpos;
5182 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005183 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005184 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005185 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005186 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005187 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005188 PyObject *errorHandler = NULL;
5189 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005190
Tim Peters772747b2001-08-09 22:21:55 +00005191 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005192 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005193
5194 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005195 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005197 /* Check for BOM marks (U+FEFF) in the input and adjust current
5198 byte order setting accordingly. In native mode, the leading BOM
5199 mark is skipped, in all other modes, it is copied to the output
5200 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005201 if (bo == 0 && size >= 2) {
5202 const Py_UCS4 bom = (q[1] << 8) | q[0];
5203 if (bom == 0xFEFF) {
5204 q += 2;
5205 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005207 else if (bom == 0xFFFE) {
5208 q += 2;
5209 bo = 1;
5210 }
5211 if (byteorder)
5212 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005213 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005214
Antoine Pitrou63065d72012-05-15 23:48:04 +02005215 if (q == e) {
5216 if (consumed)
5217 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005218 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005219 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005220
Christian Heimes743e0cd2012-10-17 23:52:17 +02005221#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005222 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005223#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005224 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005225#endif
Tim Peters772747b2001-08-09 22:21:55 +00005226
Antoine Pitrou63065d72012-05-15 23:48:04 +02005227 /* Note: size will always be longer than the resulting Unicode
5228 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005229 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005230 writer.min_length = (e - q + 1) / 2;
5231 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005232 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005233
Antoine Pitrou63065d72012-05-15 23:48:04 +02005234 while (1) {
5235 Py_UCS4 ch = 0;
5236 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005237 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005238 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005239 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005240 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005241 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005242 native_ordering);
5243 else
5244 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005245 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005246 native_ordering);
5247 } else if (kind == PyUnicode_2BYTE_KIND) {
5248 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005249 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005250 native_ordering);
5251 } else {
5252 assert(kind == PyUnicode_4BYTE_KIND);
5253 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005254 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005255 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005256 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005257 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005258
Antoine Pitrou63065d72012-05-15 23:48:04 +02005259 switch (ch)
5260 {
5261 case 0:
5262 /* remaining byte at the end? (size should be even) */
5263 if (q == e || consumed)
5264 goto End;
5265 errmsg = "truncated data";
5266 startinpos = ((const char *)q) - starts;
5267 endinpos = ((const char *)e) - starts;
5268 break;
5269 /* The remaining input chars are ignored if the callback
5270 chooses to skip the input */
5271 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005272 q -= 2;
5273 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005274 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005275 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005276 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005277 endinpos = ((const char *)e) - starts;
5278 break;
5279 case 2:
5280 errmsg = "illegal encoding";
5281 startinpos = ((const char *)q) - 2 - starts;
5282 endinpos = startinpos + 2;
5283 break;
5284 case 3:
5285 errmsg = "illegal UTF-16 surrogate";
5286 startinpos = ((const char *)q) - 4 - starts;
5287 endinpos = startinpos + 2;
5288 break;
5289 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005290 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005291 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005292 continue;
5293 }
5294
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005295 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005296 errors,
5297 &errorHandler,
5298 "utf16", errmsg,
5299 &starts,
5300 (const char **)&e,
5301 &startinpos,
5302 &endinpos,
5303 &exc,
5304 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005305 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005307 }
5308
Antoine Pitrou63065d72012-05-15 23:48:04 +02005309End:
Walter Dörwald69652032004-09-07 20:24:22 +00005310 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005311 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005312
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005313 Py_XDECREF(errorHandler);
5314 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005315 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005316
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005318 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005319 Py_XDECREF(errorHandler);
5320 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005321 return NULL;
5322}
5323
Tim Peters772747b2001-08-09 22:21:55 +00005324PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005325_PyUnicode_EncodeUTF16(PyObject *str,
5326 const char *errors,
5327 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005328{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005329 enum PyUnicode_Kind kind;
5330 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005331 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005332 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005333 unsigned short *out;
5334 Py_ssize_t bytesize;
5335 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005336#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005337 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005338#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005339 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005340#endif
5341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005342 if (!PyUnicode_Check(str)) {
5343 PyErr_BadArgument();
5344 return NULL;
5345 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005346 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347 return NULL;
5348 kind = PyUnicode_KIND(str);
5349 data = PyUnicode_DATA(str);
5350 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005351
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005352 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005353 if (kind == PyUnicode_4BYTE_KIND) {
5354 const Py_UCS4 *in = (const Py_UCS4 *)data;
5355 const Py_UCS4 *end = in + len;
5356 while (in < end)
5357 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005358 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005359 }
5360 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005362 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005363 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005364 if (v == NULL)
5365 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005366
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005367 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005368 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005369 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005370 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005371 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005372 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005373 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005374
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005375 switch (kind) {
5376 case PyUnicode_1BYTE_KIND: {
5377 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5378 break;
Tim Peters772747b2001-08-09 22:21:55 +00005379 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005380 case PyUnicode_2BYTE_KIND: {
5381 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5382 break;
Tim Peters772747b2001-08-09 22:21:55 +00005383 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005384 case PyUnicode_4BYTE_KIND: {
5385 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5386 break;
5387 }
5388 default:
5389 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005390 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005391
5392 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005393 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005394}
5395
Alexander Belopolsky40018472011-02-26 01:02:56 +00005396PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005397PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5398 Py_ssize_t size,
5399 const char *errors,
5400 int byteorder)
5401{
5402 PyObject *result;
5403 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5404 if (tmp == NULL)
5405 return NULL;
5406 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5407 Py_DECREF(tmp);
5408 return result;
5409}
5410
5411PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005412PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005414 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415}
5416
5417/* --- Unicode Escape Codec ----------------------------------------------- */
5418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005419/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5420 if all the escapes in the string make it still a valid ASCII string.
5421 Returns -1 if any escapes were found which cause the string to
5422 pop out of ASCII range. Otherwise returns the length of the
5423 required buffer to hold the string.
5424 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005425static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005426length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5427{
5428 const unsigned char *p = (const unsigned char *)s;
5429 const unsigned char *end = p + size;
5430 Py_ssize_t length = 0;
5431
5432 if (size < 0)
5433 return -1;
5434
5435 for (; p < end; ++p) {
5436 if (*p > 127) {
5437 /* Non-ASCII */
5438 return -1;
5439 }
5440 else if (*p != '\\') {
5441 /* Normal character */
5442 ++length;
5443 }
5444 else {
5445 /* Backslash-escape, check next char */
5446 ++p;
5447 /* Escape sequence reaches till end of string or
5448 non-ASCII follow-up. */
5449 if (p >= end || *p > 127)
5450 return -1;
5451 switch (*p) {
5452 case '\n':
5453 /* backslash + \n result in zero characters */
5454 break;
5455 case '\\': case '\'': case '\"':
5456 case 'b': case 'f': case 't':
5457 case 'n': case 'r': case 'v': case 'a':
5458 ++length;
5459 break;
5460 case '0': case '1': case '2': case '3':
5461 case '4': case '5': case '6': case '7':
5462 case 'x': case 'u': case 'U': case 'N':
5463 /* these do not guarantee ASCII characters */
5464 return -1;
5465 default:
5466 /* count the backslash + the other character */
5467 length += 2;
5468 }
5469 }
5470 }
5471 return length;
5472}
5473
Fredrik Lundh06d12682001-01-24 07:59:11 +00005474static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005475
Alexander Belopolsky40018472011-02-26 01:02:56 +00005476PyObject *
5477PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005478 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005479 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005481 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005482 Py_ssize_t startinpos;
5483 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005484 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005485 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005486 char* message;
5487 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005488 PyObject *errorHandler = NULL;
5489 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005490 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005491
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005492 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005493 if (len == 0)
5494 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005495
5496 /* After length_of_escaped_ascii_string() there are two alternatives,
5497 either the string is pure ASCII with named escapes like \n, etc.
5498 and we determined it's exact size (common case)
5499 or it contains \x, \u, ... escape sequences. then we create a
5500 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005501 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005502 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005503 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005504 }
5505 else {
5506 /* Escaped strings will always be longer than the resulting
5507 Unicode string, so we start with size here and then reduce the
5508 length after conversion to the true value.
5509 (but if the error callback returns a long replacement string
5510 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005511 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005512 }
5513
Guido van Rossumd57fd912000-03-10 22:53:23 +00005514 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005515 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005516 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005517
Guido van Rossumd57fd912000-03-10 22:53:23 +00005518 while (s < end) {
5519 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005520 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005521 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005522
5523 /* Non-escape characters are interpreted as Unicode ordinals */
5524 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005525 x = (unsigned char)*s;
5526 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005527 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005528 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005529 continue;
5530 }
5531
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005532 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533 /* \ - Escapes */
5534 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005535 c = *s++;
5536 if (s > end)
5537 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005538
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005539 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005540
Benjamin Peterson29060642009-01-31 22:14:21 +00005541 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005542#define WRITECHAR(ch) \
5543 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005544 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005545 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005546 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005547
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005549 case '\\': WRITECHAR('\\'); break;
5550 case '\'': WRITECHAR('\''); break;
5551 case '\"': WRITECHAR('\"'); break;
5552 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005553 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005554 case 'f': WRITECHAR('\014'); break;
5555 case 't': WRITECHAR('\t'); break;
5556 case 'n': WRITECHAR('\n'); break;
5557 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005558 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005559 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005560 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005561 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005562
Benjamin Peterson29060642009-01-31 22:14:21 +00005563 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564 case '0': case '1': case '2': case '3':
5565 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005566 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005567 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005568 x = (x<<3) + *s++ - '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 Rossumd57fd912000-03-10 22:53:23 +00005571 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005572 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005573 break;
5574
Benjamin Peterson29060642009-01-31 22:14:21 +00005575 /* hex escapes */
5576 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005578 digits = 2;
5579 message = "truncated \\xXX escape";
5580 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005581
Benjamin Peterson29060642009-01-31 22:14:21 +00005582 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005584 digits = 4;
5585 message = "truncated \\uXXXX escape";
5586 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005587
Benjamin Peterson29060642009-01-31 22:14:21 +00005588 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005589 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005590 digits = 8;
5591 message = "truncated \\UXXXXXXXX escape";
5592 hexescape:
5593 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005594 if (end - s < digits) {
5595 /* count only hex digits */
5596 for (; s < end; ++s) {
5597 c = (unsigned char)*s;
5598 if (!Py_ISXDIGIT(c))
5599 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005600 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005601 goto error;
5602 }
5603 for (; digits--; ++s) {
5604 c = (unsigned char)*s;
5605 if (!Py_ISXDIGIT(c))
5606 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005607 chr = (chr<<4) & ~0xF;
5608 if (c >= '0' && c <= '9')
5609 chr += c - '0';
5610 else if (c >= 'a' && c <= 'f')
5611 chr += 10 + c - 'a';
5612 else
5613 chr += 10 + c - 'A';
5614 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005615 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005616 /* _decoding_error will have already written into the
5617 target buffer. */
5618 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005619 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005620 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005621 message = "illegal Unicode character";
5622 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005623 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005624 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005625 break;
5626
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005628 case 'N':
5629 message = "malformed \\N character escape";
5630 if (ucnhash_CAPI == NULL) {
5631 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005632 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5633 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005634 if (ucnhash_CAPI == NULL)
5635 goto ucnhashError;
5636 }
5637 if (*s == '{') {
5638 const char *start = s+1;
5639 /* look for the closing brace */
5640 while (*s != '}' && s < end)
5641 s++;
5642 if (s > start && s < end && *s == '}') {
5643 /* found a name. look it up in the unicode database */
5644 message = "unknown Unicode character name";
5645 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005646 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005647 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005648 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005649 goto store;
5650 }
5651 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005652 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005653
5654 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005655 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005656 message = "\\ at end of string";
5657 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005658 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005659 }
5660 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005661 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005662 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005663 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005664 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005666 continue;
5667
5668 error:
5669 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005670 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005671 errors, &errorHandler,
5672 "unicodeescape", message,
5673 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005674 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005675 goto onError;
5676 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005678#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005679
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005680 Py_XDECREF(errorHandler);
5681 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005682 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005683
Benjamin Peterson29060642009-01-31 22:14:21 +00005684 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005685 PyErr_SetString(
5686 PyExc_UnicodeError,
5687 "\\N escapes not supported (can't load unicodedata module)"
5688 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005689 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005690 Py_XDECREF(errorHandler);
5691 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005692 return NULL;
5693
Benjamin Peterson29060642009-01-31 22:14:21 +00005694 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005695 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005696 Py_XDECREF(errorHandler);
5697 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005698 return NULL;
5699}
5700
5701/* Return a Unicode-Escape string version of the Unicode object.
5702
5703 If quotes is true, the string is enclosed in u"" or u'' quotes as
5704 appropriate.
5705
5706*/
5707
Alexander Belopolsky40018472011-02-26 01:02:56 +00005708PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005709PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005710{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005711 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005712 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005713 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005714 int kind;
5715 void *data;
5716 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717
Ezio Melottie7f90372012-10-05 03:33:31 +03005718 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005719 escape.
5720
Ezio Melottie7f90372012-10-05 03:33:31 +03005721 For UCS1 strings it's '\xxx', 4 bytes per source character.
5722 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5723 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005724 */
5725
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726 if (!PyUnicode_Check(unicode)) {
5727 PyErr_BadArgument();
5728 return NULL;
5729 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005730 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005731 return NULL;
5732 len = PyUnicode_GET_LENGTH(unicode);
5733 kind = PyUnicode_KIND(unicode);
5734 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005735 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005736 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5737 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5738 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5739 }
5740
5741 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005742 return PyBytes_FromStringAndSize(NULL, 0);
5743
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005744 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005745 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005746
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005747 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005749 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005750 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 if (repr == NULL)
5752 return NULL;
5753
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005754 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005756 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005757 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005758
Walter Dörwald79e913e2007-05-12 11:08:06 +00005759 /* Escape backslashes */
5760 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761 *p++ = '\\';
5762 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005763 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005764 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005765
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005766 /* Map 21-bit characters to '\U00xxxxxx' */
5767 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005768 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005769 *p++ = '\\';
5770 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005771 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5772 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5773 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5774 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5775 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5776 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5777 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5778 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005780 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005781
Guido van Rossumd57fd912000-03-10 22:53:23 +00005782 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005783 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 *p++ = '\\';
5785 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005786 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5787 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5788 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5789 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005791
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005792 /* Map special whitespace to '\t', \n', '\r' */
5793 else if (ch == '\t') {
5794 *p++ = '\\';
5795 *p++ = 't';
5796 }
5797 else if (ch == '\n') {
5798 *p++ = '\\';
5799 *p++ = 'n';
5800 }
5801 else if (ch == '\r') {
5802 *p++ = '\\';
5803 *p++ = 'r';
5804 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005805
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005806 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005807 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005808 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005809 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005810 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5811 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005812 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005813
Guido van Rossumd57fd912000-03-10 22:53:23 +00005814 /* Copy everything else as-is */
5815 else
5816 *p++ = (char) ch;
5817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005819 assert(p - PyBytes_AS_STRING(repr) > 0);
5820 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5821 return NULL;
5822 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005823}
5824
Alexander Belopolsky40018472011-02-26 01:02:56 +00005825PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005826PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5827 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005828{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005829 PyObject *result;
5830 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5831 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005832 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005833 result = PyUnicode_AsUnicodeEscapeString(tmp);
5834 Py_DECREF(tmp);
5835 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005836}
5837
5838/* --- Raw Unicode Escape Codec ------------------------------------------- */
5839
Alexander Belopolsky40018472011-02-26 01:02:56 +00005840PyObject *
5841PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005842 Py_ssize_t size,
5843 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005844{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005845 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005846 Py_ssize_t startinpos;
5847 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005848 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849 const char *end;
5850 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005851 PyObject *errorHandler = NULL;
5852 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005853
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005854 if (size == 0)
5855 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005856
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 /* Escaped strings will always be longer than the resulting
5858 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005859 length after conversion to the true value. (But decoding error
5860 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005861 _PyUnicodeWriter_Init(&writer);
5862 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005863
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 end = s + size;
5865 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 unsigned char c;
5867 Py_UCS4 x;
5868 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005869 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870
Benjamin Peterson29060642009-01-31 22:14:21 +00005871 /* Non-escape characters are interpreted as Unicode ordinals */
5872 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005873 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005874 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005875 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005876 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005877 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005878 startinpos = s-starts;
5879
5880 /* \u-escapes are only interpreted iff the number of leading
5881 backslashes if odd */
5882 bs = s;
5883 for (;s < end;) {
5884 if (*s != '\\')
5885 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005886 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005887 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005888 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 }
5890 if (((s - bs) & 1) == 0 ||
5891 s >= end ||
5892 (*s != 'u' && *s != 'U')) {
5893 continue;
5894 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005895 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 count = *s=='u' ? 4 : 8;
5897 s++;
5898
5899 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005900 for (x = 0, i = 0; i < count; ++i, ++s) {
5901 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005902 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005904 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 errors, &errorHandler,
5906 "rawunicodeescape", "truncated \\uXXXX",
5907 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005908 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 goto onError;
5910 goto nextByte;
5911 }
5912 x = (x<<4) & ~0xF;
5913 if (c >= '0' && c <= '9')
5914 x += c - '0';
5915 else if (c >= 'a' && c <= 'f')
5916 x += 10 + c - 'a';
5917 else
5918 x += 10 + c - 'A';
5919 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005920 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005921 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005922 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005923 }
5924 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00005925 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005926 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005927 errors, &errorHandler,
5928 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005930 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005931 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005932 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005933 nextByte:
5934 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005936 Py_XDECREF(errorHandler);
5937 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005938 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00005939
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005941 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 Py_XDECREF(errorHandler);
5943 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944 return NULL;
5945}
5946
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005947
Alexander Belopolsky40018472011-02-26 01:02:56 +00005948PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005949PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005951 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952 char *p;
5953 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005954 Py_ssize_t expandsize, pos;
5955 int kind;
5956 void *data;
5957 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005959 if (!PyUnicode_Check(unicode)) {
5960 PyErr_BadArgument();
5961 return NULL;
5962 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005963 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005964 return NULL;
5965 kind = PyUnicode_KIND(unicode);
5966 data = PyUnicode_DATA(unicode);
5967 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06005968 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
5969 bytes, and 1 byte characters 4. */
5970 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01005971
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005972 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005974
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005975 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 if (repr == NULL)
5977 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005978 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005979 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005981 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005982 for (pos = 0; pos < len; pos++) {
5983 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00005984 /* Map 32-bit characters to '\Uxxxxxxxx' */
5985 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005986 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005987 *p++ = '\\';
5988 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005989 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
5990 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
5991 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
5992 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
5993 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5994 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5995 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5996 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005997 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005999 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 *p++ = '\\';
6001 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006002 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6003 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6004 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6005 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 /* Copy everything else as-is */
6008 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009 *p++ = (char) ch;
6010 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006011
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006012 assert(p > q);
6013 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006014 return NULL;
6015 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016}
6017
Alexander Belopolsky40018472011-02-26 01:02:56 +00006018PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006019PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6020 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006022 PyObject *result;
6023 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6024 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006025 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006026 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6027 Py_DECREF(tmp);
6028 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029}
6030
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006031/* --- Unicode Internal Codec ------------------------------------------- */
6032
Alexander Belopolsky40018472011-02-26 01:02:56 +00006033PyObject *
6034_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006035 Py_ssize_t size,
6036 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006037{
6038 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006039 Py_ssize_t startinpos;
6040 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006041 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006042 const char *end;
6043 const char *reason;
6044 PyObject *errorHandler = NULL;
6045 PyObject *exc = NULL;
6046
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006047 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006048 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006049 1))
6050 return NULL;
6051
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006052 if (size == 0)
6053 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006054
Victor Stinner8f674cc2013-04-17 23:02:17 +02006055 _PyUnicodeWriter_Init(&writer);
6056 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6057 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006059 }
6060 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006061
Victor Stinner8f674cc2013-04-17 23:02:17 +02006062 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006063 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006064 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006065 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006066 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006067 endinpos = end-starts;
6068 reason = "truncated input";
6069 goto error;
6070 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006071 /* We copy the raw representation one byte at a time because the
6072 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006073 ((char *) &uch)[0] = s[0];
6074 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006075#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006076 ((char *) &uch)[2] = s[2];
6077 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006078#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006079 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006080#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006081 /* We have to sanity check the raw data, otherwise doom looms for
6082 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006083 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006084 endinpos = s - starts + Py_UNICODE_SIZE;
6085 reason = "illegal code point (> 0x10FFFF)";
6086 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006087 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006088#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006089 s += Py_UNICODE_SIZE;
6090#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006091 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006092 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006093 Py_UNICODE uch2;
6094 ((char *) &uch2)[0] = s[0];
6095 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006096 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006097 {
Victor Stinner551ac952011-11-29 22:58:13 +01006098 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006099 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006100 }
6101 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006102#endif
6103
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006104 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006105 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006106 continue;
6107
6108 error:
6109 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006110 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006111 errors, &errorHandler,
6112 "unicode_internal", reason,
6113 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006114 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006115 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006116 }
6117
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006118 Py_XDECREF(errorHandler);
6119 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006120 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006121
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006123 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006124 Py_XDECREF(errorHandler);
6125 Py_XDECREF(exc);
6126 return NULL;
6127}
6128
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129/* --- Latin-1 Codec ------------------------------------------------------ */
6130
Alexander Belopolsky40018472011-02-26 01:02:56 +00006131PyObject *
6132PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006133 Py_ssize_t size,
6134 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006137 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138}
6139
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006140/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006141static void
6142make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006143 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006144 PyObject *unicode,
6145 Py_ssize_t startpos, Py_ssize_t endpos,
6146 const char *reason)
6147{
6148 if (*exceptionObject == NULL) {
6149 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006150 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006151 encoding, unicode, startpos, endpos, reason);
6152 }
6153 else {
6154 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6155 goto onError;
6156 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6157 goto onError;
6158 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6159 goto onError;
6160 return;
6161 onError:
6162 Py_DECREF(*exceptionObject);
6163 *exceptionObject = NULL;
6164 }
6165}
6166
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006167/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006168static void
6169raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006170 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006171 PyObject *unicode,
6172 Py_ssize_t startpos, Py_ssize_t endpos,
6173 const char *reason)
6174{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006175 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006176 encoding, unicode, startpos, endpos, reason);
6177 if (*exceptionObject != NULL)
6178 PyCodec_StrictErrors(*exceptionObject);
6179}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006180
6181/* error handling callback helper:
6182 build arguments, call the callback and check the arguments,
6183 put the result into newpos and return the replacement string, which
6184 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006185static PyObject *
6186unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006187 PyObject **errorHandler,
6188 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006189 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006190 Py_ssize_t startpos, Py_ssize_t endpos,
6191 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006192{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006193 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006194 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006195 PyObject *restuple;
6196 PyObject *resunicode;
6197
6198 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006199 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006200 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006202 }
6203
Benjamin Petersonbac79492012-01-14 13:34:47 -05006204 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006205 return NULL;
6206 len = PyUnicode_GET_LENGTH(unicode);
6207
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006208 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006209 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006210 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006211 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212
6213 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006214 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006215 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006216 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006217 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006218 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006219 Py_DECREF(restuple);
6220 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006221 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006222 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 &resunicode, newpos)) {
6224 Py_DECREF(restuple);
6225 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006226 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006227 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6228 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6229 Py_DECREF(restuple);
6230 return NULL;
6231 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006232 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006233 *newpos = len + *newpos;
6234 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006235 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6236 Py_DECREF(restuple);
6237 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006238 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006239 Py_INCREF(resunicode);
6240 Py_DECREF(restuple);
6241 return resunicode;
6242}
6243
Alexander Belopolsky40018472011-02-26 01:02:56 +00006244static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006245unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006246 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006247 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006248{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006249 /* input state */
6250 Py_ssize_t pos=0, size;
6251 int kind;
6252 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006253 /* output object */
6254 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006255 /* pointer into the output */
6256 char *str;
6257 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006258 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006259 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6260 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006261 PyObject *errorHandler = NULL;
6262 PyObject *exc = NULL;
6263 /* the following variable is used for caching string comparisons
6264 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6265 int known_errorHandler = -1;
6266
Benjamin Petersonbac79492012-01-14 13:34:47 -05006267 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006268 return NULL;
6269 size = PyUnicode_GET_LENGTH(unicode);
6270 kind = PyUnicode_KIND(unicode);
6271 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006272 /* allocate enough for a simple encoding without
6273 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006274 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006275 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006276 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006277 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006278 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006279 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280 ressize = size;
6281
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006282 while (pos < size) {
6283 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006284
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 /* can we encode this? */
6286 if (c<limit) {
6287 /* no overflow check, because we know that the space is enough */
6288 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006289 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006290 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 Py_ssize_t requiredsize;
6293 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006294 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006296 Py_ssize_t collstart = pos;
6297 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006299 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 ++collend;
6301 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6302 if (known_errorHandler==-1) {
6303 if ((errors==NULL) || (!strcmp(errors, "strict")))
6304 known_errorHandler = 1;
6305 else if (!strcmp(errors, "replace"))
6306 known_errorHandler = 2;
6307 else if (!strcmp(errors, "ignore"))
6308 known_errorHandler = 3;
6309 else if (!strcmp(errors, "xmlcharrefreplace"))
6310 known_errorHandler = 4;
6311 else
6312 known_errorHandler = 0;
6313 }
6314 switch (known_errorHandler) {
6315 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006316 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 goto onError;
6318 case 2: /* replace */
6319 while (collstart++<collend)
6320 *str++ = '?'; /* fall through */
6321 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006322 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 break;
6324 case 4: /* xmlcharrefreplace */
6325 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006326 /* determine replacement size */
6327 for (i = collstart, repsize = 0; i < collend; ++i) {
6328 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6329 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006330 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006331 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006332 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006333 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006334 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006335 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006336 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006337 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006338 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006339 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006341 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006342 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006343 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006344 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006345 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006346 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006347 if (requiredsize > ressize) {
6348 if (requiredsize<2*ressize)
6349 requiredsize = 2*ressize;
6350 if (_PyBytes_Resize(&res, requiredsize))
6351 goto onError;
6352 str = PyBytes_AS_STRING(res) + respos;
6353 ressize = requiredsize;
6354 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006355 /* generate replacement */
6356 for (i = collstart; i < collend; ++i) {
6357 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006358 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 break;
6361 default:
6362 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006363 encoding, reason, unicode, &exc,
6364 collstart, collend, &newpos);
6365 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006366 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006367 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006368 if (PyBytes_Check(repunicode)) {
6369 /* Directly copy bytes result to output. */
6370 repsize = PyBytes_Size(repunicode);
6371 if (repsize > 1) {
6372 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006373 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006374 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6375 Py_DECREF(repunicode);
6376 goto onError;
6377 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006378 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006379 ressize += repsize-1;
6380 }
6381 memcpy(str, PyBytes_AsString(repunicode), repsize);
6382 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006383 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006384 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006385 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006386 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 /* need more space? (at least enough for what we
6388 have+the replacement+the rest of the string, so
6389 we won't have to check space for encodable characters) */
6390 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006391 repsize = PyUnicode_GET_LENGTH(repunicode);
6392 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 if (requiredsize > ressize) {
6394 if (requiredsize<2*ressize)
6395 requiredsize = 2*ressize;
6396 if (_PyBytes_Resize(&res, requiredsize)) {
6397 Py_DECREF(repunicode);
6398 goto onError;
6399 }
6400 str = PyBytes_AS_STRING(res) + respos;
6401 ressize = requiredsize;
6402 }
6403 /* check if there is anything unencodable in the replacement
6404 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006405 for (i = 0; repsize-->0; ++i, ++str) {
6406 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006408 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006409 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 Py_DECREF(repunicode);
6411 goto onError;
6412 }
6413 *str = (char)c;
6414 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006416 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006417 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006418 }
6419 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006420 /* Resize if we allocated to much */
6421 size = str - PyBytes_AS_STRING(res);
6422 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006423 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006424 if (_PyBytes_Resize(&res, size) < 0)
6425 goto onError;
6426 }
6427
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 Py_XDECREF(errorHandler);
6429 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006430 return res;
6431
6432 onError:
6433 Py_XDECREF(res);
6434 Py_XDECREF(errorHandler);
6435 Py_XDECREF(exc);
6436 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006437}
6438
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006440PyObject *
6441PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006442 Py_ssize_t size,
6443 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006444{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006445 PyObject *result;
6446 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6447 if (unicode == NULL)
6448 return NULL;
6449 result = unicode_encode_ucs1(unicode, errors, 256);
6450 Py_DECREF(unicode);
6451 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006452}
6453
Alexander Belopolsky40018472011-02-26 01:02:56 +00006454PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006455_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006456{
6457 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 PyErr_BadArgument();
6459 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006460 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006461 if (PyUnicode_READY(unicode) == -1)
6462 return NULL;
6463 /* Fast path: if it is a one-byte string, construct
6464 bytes object directly. */
6465 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6466 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6467 PyUnicode_GET_LENGTH(unicode));
6468 /* Non-Latin-1 characters present. Defer to above function to
6469 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006470 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006471}
6472
6473PyObject*
6474PyUnicode_AsLatin1String(PyObject *unicode)
6475{
6476 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006477}
6478
6479/* --- 7-bit ASCII Codec -------------------------------------------------- */
6480
Alexander Belopolsky40018472011-02-26 01:02:56 +00006481PyObject *
6482PyUnicode_DecodeASCII(const char *s,
6483 Py_ssize_t size,
6484 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006485{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006487 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006488 int kind;
6489 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006490 Py_ssize_t startinpos;
6491 Py_ssize_t endinpos;
6492 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493 const char *e;
6494 PyObject *errorHandler = NULL;
6495 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006496
Guido van Rossumd57fd912000-03-10 22:53:23 +00006497 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006498 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006499
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006501 if (size == 1 && (unsigned char)s[0] < 128)
6502 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006503
Victor Stinner8f674cc2013-04-17 23:02:17 +02006504 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006505 writer.min_length = size;
6506 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006507 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006508
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006509 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006510 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006511 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006512 writer.pos = outpos;
6513 if (writer.pos == size)
6514 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006515
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006516 s += writer.pos;
6517 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006518 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006519 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006521 PyUnicode_WRITE(kind, data, writer.pos, c);
6522 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 ++s;
6524 }
6525 else {
6526 startinpos = s-starts;
6527 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006528 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 errors, &errorHandler,
6530 "ascii", "ordinal not in range(128)",
6531 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006532 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006534 kind = writer.kind;
6535 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006537 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006538 Py_XDECREF(errorHandler);
6539 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006540 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006541
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006543 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006544 Py_XDECREF(errorHandler);
6545 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006546 return NULL;
6547}
6548
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006550PyObject *
6551PyUnicode_EncodeASCII(const Py_UNICODE *p,
6552 Py_ssize_t size,
6553 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006554{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 PyObject *result;
6556 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6557 if (unicode == NULL)
6558 return NULL;
6559 result = unicode_encode_ucs1(unicode, errors, 128);
6560 Py_DECREF(unicode);
6561 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006562}
6563
Alexander Belopolsky40018472011-02-26 01:02:56 +00006564PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006565_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566{
6567 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006568 PyErr_BadArgument();
6569 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006571 if (PyUnicode_READY(unicode) == -1)
6572 return NULL;
6573 /* Fast path: if it is an ASCII-only string, construct bytes object
6574 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006575 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006576 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6577 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006579}
6580
6581PyObject *
6582PyUnicode_AsASCIIString(PyObject *unicode)
6583{
6584 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006585}
6586
Victor Stinner99b95382011-07-04 14:23:54 +02006587#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006588
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006589/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006590
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006591#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006592#define NEED_RETRY
6593#endif
6594
Victor Stinner3a50e702011-10-18 21:21:00 +02006595#ifndef WC_ERR_INVALID_CHARS
6596# define WC_ERR_INVALID_CHARS 0x0080
6597#endif
6598
6599static char*
6600code_page_name(UINT code_page, PyObject **obj)
6601{
6602 *obj = NULL;
6603 if (code_page == CP_ACP)
6604 return "mbcs";
6605 if (code_page == CP_UTF7)
6606 return "CP_UTF7";
6607 if (code_page == CP_UTF8)
6608 return "CP_UTF8";
6609
6610 *obj = PyBytes_FromFormat("cp%u", code_page);
6611 if (*obj == NULL)
6612 return NULL;
6613 return PyBytes_AS_STRING(*obj);
6614}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006615
Alexander Belopolsky40018472011-02-26 01:02:56 +00006616static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006617is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006618{
6619 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006620 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006621
Victor Stinner3a50e702011-10-18 21:21:00 +02006622 if (!IsDBCSLeadByteEx(code_page, *curr))
6623 return 0;
6624
6625 prev = CharPrevExA(code_page, s, curr, 0);
6626 if (prev == curr)
6627 return 1;
6628 /* FIXME: This code is limited to "true" double-byte encodings,
6629 as it assumes an incomplete character consists of a single
6630 byte. */
6631 if (curr - prev == 2)
6632 return 1;
6633 if (!IsDBCSLeadByteEx(code_page, *prev))
6634 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006635 return 0;
6636}
6637
Victor Stinner3a50e702011-10-18 21:21:00 +02006638static DWORD
6639decode_code_page_flags(UINT code_page)
6640{
6641 if (code_page == CP_UTF7) {
6642 /* The CP_UTF7 decoder only supports flags=0 */
6643 return 0;
6644 }
6645 else
6646 return MB_ERR_INVALID_CHARS;
6647}
6648
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006649/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006650 * Decode a byte string from a Windows code page into unicode object in strict
6651 * mode.
6652 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006653 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6654 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006655 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006656static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006657decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006658 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006659 const char *in,
6660 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006661{
Victor Stinner3a50e702011-10-18 21:21:00 +02006662 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006663 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006664 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006665
6666 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006667 assert(insize > 0);
6668 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6669 if (outsize <= 0)
6670 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006671
6672 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006674 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006675 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 if (*v == NULL)
6677 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006678 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006679 }
6680 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006682 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006683 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006685 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006686 }
6687
6688 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006689 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6690 if (outsize <= 0)
6691 goto error;
6692 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006693
Victor Stinner3a50e702011-10-18 21:21:00 +02006694error:
6695 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6696 return -2;
6697 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006698 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006699}
6700
Victor Stinner3a50e702011-10-18 21:21:00 +02006701/*
6702 * Decode a byte string from a code page into unicode object with an error
6703 * handler.
6704 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006705 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006706 * UnicodeDecodeError exception and returns -1 on error.
6707 */
6708static int
6709decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006710 PyObject **v,
6711 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006712 const char *errors)
6713{
6714 const char *startin = in;
6715 const char *endin = in + size;
6716 const DWORD flags = decode_code_page_flags(code_page);
6717 /* Ideally, we should get reason from FormatMessage. This is the Windows
6718 2000 English version of the message. */
6719 const char *reason = "No mapping for the Unicode character exists "
6720 "in the target code page.";
6721 /* each step cannot decode more than 1 character, but a character can be
6722 represented as a surrogate pair */
6723 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006724 int insize;
6725 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006726 PyObject *errorHandler = NULL;
6727 PyObject *exc = NULL;
6728 PyObject *encoding_obj = NULL;
6729 char *encoding;
6730 DWORD err;
6731 int ret = -1;
6732
6733 assert(size > 0);
6734
6735 encoding = code_page_name(code_page, &encoding_obj);
6736 if (encoding == NULL)
6737 return -1;
6738
6739 if (errors == NULL || strcmp(errors, "strict") == 0) {
6740 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6741 UnicodeDecodeError. */
6742 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6743 if (exc != NULL) {
6744 PyCodec_StrictErrors(exc);
6745 Py_CLEAR(exc);
6746 }
6747 goto error;
6748 }
6749
6750 if (*v == NULL) {
6751 /* Create unicode object */
6752 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6753 PyErr_NoMemory();
6754 goto error;
6755 }
Victor Stinnerab595942011-12-17 04:59:06 +01006756 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006757 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006758 if (*v == NULL)
6759 goto error;
6760 startout = PyUnicode_AS_UNICODE(*v);
6761 }
6762 else {
6763 /* Extend unicode object */
6764 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6765 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6766 PyErr_NoMemory();
6767 goto error;
6768 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006769 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006770 goto error;
6771 startout = PyUnicode_AS_UNICODE(*v) + n;
6772 }
6773
6774 /* Decode the byte string character per character */
6775 out = startout;
6776 while (in < endin)
6777 {
6778 /* Decode a character */
6779 insize = 1;
6780 do
6781 {
6782 outsize = MultiByteToWideChar(code_page, flags,
6783 in, insize,
6784 buffer, Py_ARRAY_LENGTH(buffer));
6785 if (outsize > 0)
6786 break;
6787 err = GetLastError();
6788 if (err != ERROR_NO_UNICODE_TRANSLATION
6789 && err != ERROR_INSUFFICIENT_BUFFER)
6790 {
6791 PyErr_SetFromWindowsErr(0);
6792 goto error;
6793 }
6794 insize++;
6795 }
6796 /* 4=maximum length of a UTF-8 sequence */
6797 while (insize <= 4 && (in + insize) <= endin);
6798
6799 if (outsize <= 0) {
6800 Py_ssize_t startinpos, endinpos, outpos;
6801
6802 startinpos = in - startin;
6803 endinpos = startinpos + 1;
6804 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006805 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006806 errors, &errorHandler,
6807 encoding, reason,
6808 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006809 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006810 {
6811 goto error;
6812 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006813 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006814 }
6815 else {
6816 in += insize;
6817 memcpy(out, buffer, outsize * sizeof(wchar_t));
6818 out += outsize;
6819 }
6820 }
6821
6822 /* write a NUL character at the end */
6823 *out = 0;
6824
6825 /* Extend unicode object */
6826 outsize = out - startout;
6827 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006828 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006829 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006830 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006831
6832error:
6833 Py_XDECREF(encoding_obj);
6834 Py_XDECREF(errorHandler);
6835 Py_XDECREF(exc);
6836 return ret;
6837}
6838
Victor Stinner3a50e702011-10-18 21:21:00 +02006839static PyObject *
6840decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006841 const char *s, Py_ssize_t size,
6842 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006843{
Victor Stinner76a31a62011-11-04 00:05:13 +01006844 PyObject *v = NULL;
6845 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006846
Victor Stinner3a50e702011-10-18 21:21:00 +02006847 if (code_page < 0) {
6848 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6849 return NULL;
6850 }
6851
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006852 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006853 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006854
Victor Stinner76a31a62011-11-04 00:05:13 +01006855 do
6856 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006858 if (size > INT_MAX) {
6859 chunk_size = INT_MAX;
6860 final = 0;
6861 done = 0;
6862 }
6863 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006864#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006865 {
6866 chunk_size = (int)size;
6867 final = (consumed == NULL);
6868 done = 1;
6869 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006870
Victor Stinner76a31a62011-11-04 00:05:13 +01006871 /* Skip trailing lead-byte unless 'final' is set */
6872 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6873 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874
Victor Stinner76a31a62011-11-04 00:05:13 +01006875 if (chunk_size == 0 && done) {
6876 if (v != NULL)
6877 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006878 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006879 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880
Victor Stinner76a31a62011-11-04 00:05:13 +01006881
6882 converted = decode_code_page_strict(code_page, &v,
6883 s, chunk_size);
6884 if (converted == -2)
6885 converted = decode_code_page_errors(code_page, &v,
6886 s, chunk_size,
6887 errors);
6888 assert(converted != 0);
6889
6890 if (converted < 0) {
6891 Py_XDECREF(v);
6892 return NULL;
6893 }
6894
6895 if (consumed)
6896 *consumed += converted;
6897
6898 s += converted;
6899 size -= converted;
6900 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006901
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006902 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006903}
6904
Alexander Belopolsky40018472011-02-26 01:02:56 +00006905PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006906PyUnicode_DecodeCodePageStateful(int code_page,
6907 const char *s,
6908 Py_ssize_t size,
6909 const char *errors,
6910 Py_ssize_t *consumed)
6911{
6912 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6913}
6914
6915PyObject *
6916PyUnicode_DecodeMBCSStateful(const char *s,
6917 Py_ssize_t size,
6918 const char *errors,
6919 Py_ssize_t *consumed)
6920{
6921 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6922}
6923
6924PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006925PyUnicode_DecodeMBCS(const char *s,
6926 Py_ssize_t size,
6927 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006928{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006929 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6930}
6931
Victor Stinner3a50e702011-10-18 21:21:00 +02006932static DWORD
6933encode_code_page_flags(UINT code_page, const char *errors)
6934{
6935 if (code_page == CP_UTF8) {
6936 if (winver.dwMajorVersion >= 6)
6937 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6938 and later */
6939 return WC_ERR_INVALID_CHARS;
6940 else
6941 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
6942 return 0;
6943 }
6944 else if (code_page == CP_UTF7) {
6945 /* CP_UTF7 only supports flags=0 */
6946 return 0;
6947 }
6948 else {
6949 if (errors != NULL && strcmp(errors, "replace") == 0)
6950 return 0;
6951 else
6952 return WC_NO_BEST_FIT_CHARS;
6953 }
6954}
6955
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006956/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006957 * Encode a Unicode string to a Windows code page into a byte string in strict
6958 * mode.
6959 *
6960 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006961 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006962 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006963static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006964encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01006965 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02006966 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006967{
Victor Stinner554f3f02010-06-16 23:33:54 +00006968 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02006969 BOOL *pusedDefaultChar = &usedDefaultChar;
6970 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006971 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01006972 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006973 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006974 const DWORD flags = encode_code_page_flags(code_page, NULL);
6975 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006976 /* Create a substring so that we can get the UTF-16 representation
6977 of just the slice under consideration. */
6978 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006979
Martin v. Löwis3d325192011-11-04 18:23:06 +01006980 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006981
Victor Stinner3a50e702011-10-18 21:21:00 +02006982 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00006983 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02006984 else
Victor Stinner554f3f02010-06-16 23:33:54 +00006985 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00006986
Victor Stinner2fc507f2011-11-04 20:06:39 +01006987 substring = PyUnicode_Substring(unicode, offset, offset+len);
6988 if (substring == NULL)
6989 return -1;
6990 p = PyUnicode_AsUnicodeAndSize(substring, &size);
6991 if (p == NULL) {
6992 Py_DECREF(substring);
6993 return -1;
6994 }
Victor Stinner9f067f42013-06-05 00:21:31 +02006995 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01006996
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006997 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006998 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02006999 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007000 NULL, 0,
7001 NULL, pusedDefaultChar);
7002 if (outsize <= 0)
7003 goto error;
7004 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007005 if (pusedDefaultChar && *pusedDefaultChar) {
7006 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007007 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007008 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007009
Victor Stinner3a50e702011-10-18 21:21:00 +02007010 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007011 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007012 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007013 if (*outbytes == NULL) {
7014 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007015 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007016 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007018 }
7019 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007020 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007021 const Py_ssize_t n = PyBytes_Size(*outbytes);
7022 if (outsize > PY_SSIZE_T_MAX - n) {
7023 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007024 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007025 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007026 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007027 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7028 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007029 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007030 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007031 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007032 }
7033
7034 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007036 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007037 out, outsize,
7038 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007039 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007040 if (outsize <= 0)
7041 goto error;
7042 if (pusedDefaultChar && *pusedDefaultChar)
7043 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007044 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007045
Victor Stinner3a50e702011-10-18 21:21:00 +02007046error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007047 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7049 return -2;
7050 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007051 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007052}
7053
Victor Stinner3a50e702011-10-18 21:21:00 +02007054/*
7055 * Encode a Unicode string to a Windows code page into a byte string using a
7056 * error handler.
7057 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007058 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007059 * -1 on other error.
7060 */
7061static int
7062encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007063 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007064 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007065{
Victor Stinner3a50e702011-10-18 21:21:00 +02007066 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007067 Py_ssize_t pos = unicode_offset;
7068 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 /* Ideally, we should get reason from FormatMessage. This is the Windows
7070 2000 English version of the message. */
7071 const char *reason = "invalid character";
7072 /* 4=maximum length of a UTF-8 sequence */
7073 char buffer[4];
7074 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7075 Py_ssize_t outsize;
7076 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 PyObject *errorHandler = NULL;
7078 PyObject *exc = NULL;
7079 PyObject *encoding_obj = NULL;
7080 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007081 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 PyObject *rep;
7083 int ret = -1;
7084
7085 assert(insize > 0);
7086
7087 encoding = code_page_name(code_page, &encoding_obj);
7088 if (encoding == NULL)
7089 return -1;
7090
7091 if (errors == NULL || strcmp(errors, "strict") == 0) {
7092 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7093 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007094 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 if (exc != NULL) {
7096 PyCodec_StrictErrors(exc);
7097 Py_DECREF(exc);
7098 }
7099 Py_XDECREF(encoding_obj);
7100 return -1;
7101 }
7102
7103 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7104 pusedDefaultChar = &usedDefaultChar;
7105 else
7106 pusedDefaultChar = NULL;
7107
7108 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7109 PyErr_NoMemory();
7110 goto error;
7111 }
7112 outsize = insize * Py_ARRAY_LENGTH(buffer);
7113
7114 if (*outbytes == NULL) {
7115 /* Create string object */
7116 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7117 if (*outbytes == NULL)
7118 goto error;
7119 out = PyBytes_AS_STRING(*outbytes);
7120 }
7121 else {
7122 /* Extend string object */
7123 Py_ssize_t n = PyBytes_Size(*outbytes);
7124 if (n > PY_SSIZE_T_MAX - outsize) {
7125 PyErr_NoMemory();
7126 goto error;
7127 }
7128 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7129 goto error;
7130 out = PyBytes_AS_STRING(*outbytes) + n;
7131 }
7132
7133 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007134 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007136 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7137 wchar_t chars[2];
7138 int charsize;
7139 if (ch < 0x10000) {
7140 chars[0] = (wchar_t)ch;
7141 charsize = 1;
7142 }
7143 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007144 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7145 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007146 charsize = 2;
7147 }
7148
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007150 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 buffer, Py_ARRAY_LENGTH(buffer),
7152 NULL, pusedDefaultChar);
7153 if (outsize > 0) {
7154 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7155 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007156 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 memcpy(out, buffer, outsize);
7158 out += outsize;
7159 continue;
7160 }
7161 }
7162 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7163 PyErr_SetFromWindowsErr(0);
7164 goto error;
7165 }
7166
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 rep = unicode_encode_call_errorhandler(
7168 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007169 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007170 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 if (rep == NULL)
7172 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007173 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007174
7175 if (PyBytes_Check(rep)) {
7176 outsize = PyBytes_GET_SIZE(rep);
7177 if (outsize != 1) {
7178 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7179 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7180 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7181 Py_DECREF(rep);
7182 goto error;
7183 }
7184 out = PyBytes_AS_STRING(*outbytes) + offset;
7185 }
7186 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7187 out += outsize;
7188 }
7189 else {
7190 Py_ssize_t i;
7191 enum PyUnicode_Kind kind;
7192 void *data;
7193
Benjamin Petersonbac79492012-01-14 13:34:47 -05007194 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 Py_DECREF(rep);
7196 goto error;
7197 }
7198
7199 outsize = PyUnicode_GET_LENGTH(rep);
7200 if (outsize != 1) {
7201 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7202 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7203 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7204 Py_DECREF(rep);
7205 goto error;
7206 }
7207 out = PyBytes_AS_STRING(*outbytes) + offset;
7208 }
7209 kind = PyUnicode_KIND(rep);
7210 data = PyUnicode_DATA(rep);
7211 for (i=0; i < outsize; i++) {
7212 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7213 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007214 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 encoding, unicode,
7216 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 "unable to encode error handler result to ASCII");
7218 Py_DECREF(rep);
7219 goto error;
7220 }
7221 *out = (unsigned char)ch;
7222 out++;
7223 }
7224 }
7225 Py_DECREF(rep);
7226 }
7227 /* write a NUL byte */
7228 *out = 0;
7229 outsize = out - PyBytes_AS_STRING(*outbytes);
7230 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7231 if (_PyBytes_Resize(outbytes, outsize) < 0)
7232 goto error;
7233 ret = 0;
7234
7235error:
7236 Py_XDECREF(encoding_obj);
7237 Py_XDECREF(errorHandler);
7238 Py_XDECREF(exc);
7239 return ret;
7240}
7241
Victor Stinner3a50e702011-10-18 21:21:00 +02007242static PyObject *
7243encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007244 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 const char *errors)
7246{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007247 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007249 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007251
Benjamin Petersonbac79492012-01-14 13:34:47 -05007252 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 return NULL;
7254 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 if (code_page < 0) {
7257 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7258 return NULL;
7259 }
7260
Martin v. Löwis3d325192011-11-04 18:23:06 +01007261 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007262 return PyBytes_FromStringAndSize(NULL, 0);
7263
Victor Stinner7581cef2011-11-03 22:32:33 +01007264 offset = 0;
7265 do
7266 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007268 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007269 chunks. */
7270 if (len > INT_MAX/2) {
7271 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 done = 0;
7273 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007274 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007276 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007277 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 done = 1;
7279 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007280
Victor Stinner76a31a62011-11-04 00:05:13 +01007281 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007282 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 errors);
7284 if (ret == -2)
7285 ret = encode_code_page_errors(code_page, &outbytes,
7286 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007287 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007288 if (ret < 0) {
7289 Py_XDECREF(outbytes);
7290 return NULL;
7291 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292
Victor Stinner7581cef2011-11-03 22:32:33 +01007293 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007294 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007296
Victor Stinner3a50e702011-10-18 21:21:00 +02007297 return outbytes;
7298}
7299
7300PyObject *
7301PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7302 Py_ssize_t size,
7303 const char *errors)
7304{
Victor Stinner7581cef2011-11-03 22:32:33 +01007305 PyObject *unicode, *res;
7306 unicode = PyUnicode_FromUnicode(p, size);
7307 if (unicode == NULL)
7308 return NULL;
7309 res = encode_code_page(CP_ACP, unicode, errors);
7310 Py_DECREF(unicode);
7311 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312}
7313
7314PyObject *
7315PyUnicode_EncodeCodePage(int code_page,
7316 PyObject *unicode,
7317 const char *errors)
7318{
Victor Stinner7581cef2011-11-03 22:32:33 +01007319 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007320}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007321
Alexander Belopolsky40018472011-02-26 01:02:56 +00007322PyObject *
7323PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007324{
7325 if (!PyUnicode_Check(unicode)) {
7326 PyErr_BadArgument();
7327 return NULL;
7328 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007329 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007330}
7331
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007332#undef NEED_RETRY
7333
Victor Stinner99b95382011-07-04 14:23:54 +02007334#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007335
Guido van Rossumd57fd912000-03-10 22:53:23 +00007336/* --- Character Mapping Codec -------------------------------------------- */
7337
Victor Stinnerfb161b12013-04-18 01:44:27 +02007338static int
7339charmap_decode_string(const char *s,
7340 Py_ssize_t size,
7341 PyObject *mapping,
7342 const char *errors,
7343 _PyUnicodeWriter *writer)
7344{
7345 const char *starts = s;
7346 const char *e;
7347 Py_ssize_t startinpos, endinpos;
7348 PyObject *errorHandler = NULL, *exc = NULL;
7349 Py_ssize_t maplen;
7350 enum PyUnicode_Kind mapkind;
7351 void *mapdata;
7352 Py_UCS4 x;
7353 unsigned char ch;
7354
7355 if (PyUnicode_READY(mapping) == -1)
7356 return -1;
7357
7358 maplen = PyUnicode_GET_LENGTH(mapping);
7359 mapdata = PyUnicode_DATA(mapping);
7360 mapkind = PyUnicode_KIND(mapping);
7361
7362 e = s + size;
7363
7364 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7365 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7366 * is disabled in encoding aliases, latin1 is preferred because
7367 * its implementation is faster. */
7368 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7369 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7370 Py_UCS4 maxchar = writer->maxchar;
7371
7372 assert (writer->kind == PyUnicode_1BYTE_KIND);
7373 while (s < e) {
7374 ch = *s;
7375 x = mapdata_ucs1[ch];
7376 if (x > maxchar) {
7377 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7378 goto onError;
7379 maxchar = writer->maxchar;
7380 outdata = (Py_UCS1 *)writer->data;
7381 }
7382 outdata[writer->pos] = x;
7383 writer->pos++;
7384 ++s;
7385 }
7386 return 0;
7387 }
7388
7389 while (s < e) {
7390 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7391 enum PyUnicode_Kind outkind = writer->kind;
7392 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7393 if (outkind == PyUnicode_1BYTE_KIND) {
7394 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7395 Py_UCS4 maxchar = writer->maxchar;
7396 while (s < e) {
7397 ch = *s;
7398 x = mapdata_ucs2[ch];
7399 if (x > maxchar)
7400 goto Error;
7401 outdata[writer->pos] = x;
7402 writer->pos++;
7403 ++s;
7404 }
7405 break;
7406 }
7407 else if (outkind == PyUnicode_2BYTE_KIND) {
7408 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7409 while (s < e) {
7410 ch = *s;
7411 x = mapdata_ucs2[ch];
7412 if (x == 0xFFFE)
7413 goto Error;
7414 outdata[writer->pos] = x;
7415 writer->pos++;
7416 ++s;
7417 }
7418 break;
7419 }
7420 }
7421 ch = *s;
7422
7423 if (ch < maplen)
7424 x = PyUnicode_READ(mapkind, mapdata, ch);
7425 else
7426 x = 0xfffe; /* invalid value */
7427Error:
7428 if (x == 0xfffe)
7429 {
7430 /* undefined mapping */
7431 startinpos = s-starts;
7432 endinpos = startinpos+1;
7433 if (unicode_decode_call_errorhandler_writer(
7434 errors, &errorHandler,
7435 "charmap", "character maps to <undefined>",
7436 &starts, &e, &startinpos, &endinpos, &exc, &s,
7437 writer)) {
7438 goto onError;
7439 }
7440 continue;
7441 }
7442
7443 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7444 goto onError;
7445 ++s;
7446 }
7447 Py_XDECREF(errorHandler);
7448 Py_XDECREF(exc);
7449 return 0;
7450
7451onError:
7452 Py_XDECREF(errorHandler);
7453 Py_XDECREF(exc);
7454 return -1;
7455}
7456
7457static int
7458charmap_decode_mapping(const char *s,
7459 Py_ssize_t size,
7460 PyObject *mapping,
7461 const char *errors,
7462 _PyUnicodeWriter *writer)
7463{
7464 const char *starts = s;
7465 const char *e;
7466 Py_ssize_t startinpos, endinpos;
7467 PyObject *errorHandler = NULL, *exc = NULL;
7468 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007469 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007470
7471 e = s + size;
7472
7473 while (s < e) {
7474 ch = *s;
7475
7476 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7477 key = PyLong_FromLong((long)ch);
7478 if (key == NULL)
7479 goto onError;
7480
7481 item = PyObject_GetItem(mapping, key);
7482 Py_DECREF(key);
7483 if (item == NULL) {
7484 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7485 /* No mapping found means: mapping is undefined. */
7486 PyErr_Clear();
7487 goto Undefined;
7488 } else
7489 goto onError;
7490 }
7491
7492 /* Apply mapping */
7493 if (item == Py_None)
7494 goto Undefined;
7495 if (PyLong_Check(item)) {
7496 long value = PyLong_AS_LONG(item);
7497 if (value == 0xFFFE)
7498 goto Undefined;
7499 if (value < 0 || value > MAX_UNICODE) {
7500 PyErr_Format(PyExc_TypeError,
7501 "character mapping must be in range(0x%lx)",
7502 (unsigned long)MAX_UNICODE + 1);
7503 goto onError;
7504 }
7505
7506 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7507 goto onError;
7508 }
7509 else if (PyUnicode_Check(item)) {
7510 if (PyUnicode_READY(item) == -1)
7511 goto onError;
7512 if (PyUnicode_GET_LENGTH(item) == 1) {
7513 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7514 if (value == 0xFFFE)
7515 goto Undefined;
7516 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7517 goto onError;
7518 }
7519 else {
7520 writer->overallocate = 1;
7521 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7522 goto onError;
7523 }
7524 }
7525 else {
7526 /* wrong return value */
7527 PyErr_SetString(PyExc_TypeError,
7528 "character mapping must return integer, None or str");
7529 goto onError;
7530 }
7531 Py_CLEAR(item);
7532 ++s;
7533 continue;
7534
7535Undefined:
7536 /* undefined mapping */
7537 Py_CLEAR(item);
7538 startinpos = s-starts;
7539 endinpos = startinpos+1;
7540 if (unicode_decode_call_errorhandler_writer(
7541 errors, &errorHandler,
7542 "charmap", "character maps to <undefined>",
7543 &starts, &e, &startinpos, &endinpos, &exc, &s,
7544 writer)) {
7545 goto onError;
7546 }
7547 }
7548 Py_XDECREF(errorHandler);
7549 Py_XDECREF(exc);
7550 return 0;
7551
7552onError:
7553 Py_XDECREF(item);
7554 Py_XDECREF(errorHandler);
7555 Py_XDECREF(exc);
7556 return -1;
7557}
7558
Alexander Belopolsky40018472011-02-26 01:02:56 +00007559PyObject *
7560PyUnicode_DecodeCharmap(const char *s,
7561 Py_ssize_t size,
7562 PyObject *mapping,
7563 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007564{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007565 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007566
Guido van Rossumd57fd912000-03-10 22:53:23 +00007567 /* Default to Latin-1 */
7568 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007570
Guido van Rossumd57fd912000-03-10 22:53:23 +00007571 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007572 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007573 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007574 writer.min_length = size;
7575 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007576 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007577
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007578 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007579 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7580 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007581 }
7582 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007583 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7584 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007586 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007587
Benjamin Peterson29060642009-01-31 22:14:21 +00007588 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007589 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007590 return NULL;
7591}
7592
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007593/* Charmap encoding: the lookup table */
7594
Alexander Belopolsky40018472011-02-26 01:02:56 +00007595struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007596 PyObject_HEAD
7597 unsigned char level1[32];
7598 int count2, count3;
7599 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007600};
7601
7602static PyObject*
7603encoding_map_size(PyObject *obj, PyObject* args)
7604{
7605 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007606 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007607 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007608}
7609
7610static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007611 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007612 PyDoc_STR("Return the size (in bytes) of this object") },
7613 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007614};
7615
7616static void
7617encoding_map_dealloc(PyObject* o)
7618{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007619 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007620}
7621
7622static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007623 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007624 "EncodingMap", /*tp_name*/
7625 sizeof(struct encoding_map), /*tp_basicsize*/
7626 0, /*tp_itemsize*/
7627 /* methods */
7628 encoding_map_dealloc, /*tp_dealloc*/
7629 0, /*tp_print*/
7630 0, /*tp_getattr*/
7631 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007632 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 0, /*tp_repr*/
7634 0, /*tp_as_number*/
7635 0, /*tp_as_sequence*/
7636 0, /*tp_as_mapping*/
7637 0, /*tp_hash*/
7638 0, /*tp_call*/
7639 0, /*tp_str*/
7640 0, /*tp_getattro*/
7641 0, /*tp_setattro*/
7642 0, /*tp_as_buffer*/
7643 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7644 0, /*tp_doc*/
7645 0, /*tp_traverse*/
7646 0, /*tp_clear*/
7647 0, /*tp_richcompare*/
7648 0, /*tp_weaklistoffset*/
7649 0, /*tp_iter*/
7650 0, /*tp_iternext*/
7651 encoding_map_methods, /*tp_methods*/
7652 0, /*tp_members*/
7653 0, /*tp_getset*/
7654 0, /*tp_base*/
7655 0, /*tp_dict*/
7656 0, /*tp_descr_get*/
7657 0, /*tp_descr_set*/
7658 0, /*tp_dictoffset*/
7659 0, /*tp_init*/
7660 0, /*tp_alloc*/
7661 0, /*tp_new*/
7662 0, /*tp_free*/
7663 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007664};
7665
7666PyObject*
7667PyUnicode_BuildEncodingMap(PyObject* string)
7668{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007669 PyObject *result;
7670 struct encoding_map *mresult;
7671 int i;
7672 int need_dict = 0;
7673 unsigned char level1[32];
7674 unsigned char level2[512];
7675 unsigned char *mlevel1, *mlevel2, *mlevel3;
7676 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007677 int kind;
7678 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007679 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007680 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007681
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007682 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007683 PyErr_BadArgument();
7684 return NULL;
7685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007686 kind = PyUnicode_KIND(string);
7687 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007688 length = PyUnicode_GET_LENGTH(string);
7689 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007690 memset(level1, 0xFF, sizeof level1);
7691 memset(level2, 0xFF, sizeof level2);
7692
7693 /* If there isn't a one-to-one mapping of NULL to \0,
7694 or if there are non-BMP characters, we need to use
7695 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007696 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007697 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007698 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007699 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007700 ch = PyUnicode_READ(kind, data, i);
7701 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007702 need_dict = 1;
7703 break;
7704 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007705 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007706 /* unmapped character */
7707 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007708 l1 = ch >> 11;
7709 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007710 if (level1[l1] == 0xFF)
7711 level1[l1] = count2++;
7712 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007713 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007714 }
7715
7716 if (count2 >= 0xFF || count3 >= 0xFF)
7717 need_dict = 1;
7718
7719 if (need_dict) {
7720 PyObject *result = PyDict_New();
7721 PyObject *key, *value;
7722 if (!result)
7723 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007724 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007725 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007726 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007727 if (!key || !value)
7728 goto failed1;
7729 if (PyDict_SetItem(result, key, value) == -1)
7730 goto failed1;
7731 Py_DECREF(key);
7732 Py_DECREF(value);
7733 }
7734 return result;
7735 failed1:
7736 Py_XDECREF(key);
7737 Py_XDECREF(value);
7738 Py_DECREF(result);
7739 return NULL;
7740 }
7741
7742 /* Create a three-level trie */
7743 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7744 16*count2 + 128*count3 - 1);
7745 if (!result)
7746 return PyErr_NoMemory();
7747 PyObject_Init(result, &EncodingMapType);
7748 mresult = (struct encoding_map*)result;
7749 mresult->count2 = count2;
7750 mresult->count3 = count3;
7751 mlevel1 = mresult->level1;
7752 mlevel2 = mresult->level23;
7753 mlevel3 = mresult->level23 + 16*count2;
7754 memcpy(mlevel1, level1, 32);
7755 memset(mlevel2, 0xFF, 16*count2);
7756 memset(mlevel3, 0, 128*count3);
7757 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007758 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007759 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007760 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7761 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007762 /* unmapped character */
7763 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007764 o1 = ch>>11;
7765 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007766 i2 = 16*mlevel1[o1] + o2;
7767 if (mlevel2[i2] == 0xFF)
7768 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007769 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007770 i3 = 128*mlevel2[i2] + o3;
7771 mlevel3[i3] = i;
7772 }
7773 return result;
7774}
7775
7776static int
Victor Stinner22168992011-11-20 17:09:18 +01007777encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007778{
7779 struct encoding_map *map = (struct encoding_map*)mapping;
7780 int l1 = c>>11;
7781 int l2 = (c>>7) & 0xF;
7782 int l3 = c & 0x7F;
7783 int i;
7784
Victor Stinner22168992011-11-20 17:09:18 +01007785 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007786 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007787 if (c == 0)
7788 return 0;
7789 /* level 1*/
7790 i = map->level1[l1];
7791 if (i == 0xFF) {
7792 return -1;
7793 }
7794 /* level 2*/
7795 i = map->level23[16*i+l2];
7796 if (i == 0xFF) {
7797 return -1;
7798 }
7799 /* level 3 */
7800 i = map->level23[16*map->count2 + 128*i + l3];
7801 if (i == 0) {
7802 return -1;
7803 }
7804 return i;
7805}
7806
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007807/* Lookup the character ch in the mapping. If the character
7808 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007809 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007810static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007811charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007812{
Christian Heimes217cfd12007-12-02 14:31:20 +00007813 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007814 PyObject *x;
7815
7816 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007817 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007818 x = PyObject_GetItem(mapping, w);
7819 Py_DECREF(w);
7820 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007821 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7822 /* No mapping found means: mapping is undefined. */
7823 PyErr_Clear();
7824 x = Py_None;
7825 Py_INCREF(x);
7826 return x;
7827 } else
7828 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007829 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007830 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007832 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 long value = PyLong_AS_LONG(x);
7834 if (value < 0 || value > 255) {
7835 PyErr_SetString(PyExc_TypeError,
7836 "character mapping must be in range(256)");
7837 Py_DECREF(x);
7838 return NULL;
7839 }
7840 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007841 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007842 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007844 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007845 /* wrong return value */
7846 PyErr_Format(PyExc_TypeError,
7847 "character mapping must return integer, bytes or None, not %.400s",
7848 x->ob_type->tp_name);
7849 Py_DECREF(x);
7850 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007851 }
7852}
7853
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007855charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007856{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007857 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7858 /* exponentially overallocate to minimize reallocations */
7859 if (requiredsize < 2*outsize)
7860 requiredsize = 2*outsize;
7861 if (_PyBytes_Resize(outobj, requiredsize))
7862 return -1;
7863 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007864}
7865
Benjamin Peterson14339b62009-01-31 16:36:08 +00007866typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007868} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007869/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007870 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007871 space is available. Return a new reference to the object that
7872 was put in the output buffer, or Py_None, if the mapping was undefined
7873 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007874 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007875static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007876charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007877 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007878{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007879 PyObject *rep;
7880 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007881 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007882
Christian Heimes90aa7642007-12-19 02:45:37 +00007883 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007885 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007886 if (res == -1)
7887 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007888 if (outsize<requiredsize)
7889 if (charmapencode_resize(outobj, outpos, requiredsize))
7890 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007891 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007892 outstart[(*outpos)++] = (char)res;
7893 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007894 }
7895
7896 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007897 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007900 Py_DECREF(rep);
7901 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007902 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 if (PyLong_Check(rep)) {
7904 Py_ssize_t requiredsize = *outpos+1;
7905 if (outsize<requiredsize)
7906 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7907 Py_DECREF(rep);
7908 return enc_EXCEPTION;
7909 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007910 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007912 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 else {
7914 const char *repchars = PyBytes_AS_STRING(rep);
7915 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7916 Py_ssize_t requiredsize = *outpos+repsize;
7917 if (outsize<requiredsize)
7918 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7919 Py_DECREF(rep);
7920 return enc_EXCEPTION;
7921 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007922 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007923 memcpy(outstart + *outpos, repchars, repsize);
7924 *outpos += repsize;
7925 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007926 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007927 Py_DECREF(rep);
7928 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007929}
7930
7931/* handle an error in PyUnicode_EncodeCharmap
7932 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007933static int
7934charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007935 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007936 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007937 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007938 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007939{
7940 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007941 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007942 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007943 enum PyUnicode_Kind kind;
7944 void *data;
7945 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007946 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007947 Py_ssize_t collstartpos = *inpos;
7948 Py_ssize_t collendpos = *inpos+1;
7949 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007950 char *encoding = "charmap";
7951 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007953 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007954 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007955
Benjamin Petersonbac79492012-01-14 13:34:47 -05007956 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007957 return -1;
7958 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007959 /* find all unencodable characters */
7960 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007961 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007962 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007963 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007964 val = encoding_map_lookup(ch, mapping);
7965 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007966 break;
7967 ++collendpos;
7968 continue;
7969 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007970
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007971 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7972 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007973 if (rep==NULL)
7974 return -1;
7975 else if (rep!=Py_None) {
7976 Py_DECREF(rep);
7977 break;
7978 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007979 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007980 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007981 }
7982 /* cache callback name lookup
7983 * (if not done yet, i.e. it's the first error) */
7984 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007985 if ((errors==NULL) || (!strcmp(errors, "strict")))
7986 *known_errorHandler = 1;
7987 else if (!strcmp(errors, "replace"))
7988 *known_errorHandler = 2;
7989 else if (!strcmp(errors, "ignore"))
7990 *known_errorHandler = 3;
7991 else if (!strcmp(errors, "xmlcharrefreplace"))
7992 *known_errorHandler = 4;
7993 else
7994 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007995 }
7996 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007998 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007999 return -1;
8000 case 2: /* replace */
8001 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008002 x = charmapencode_output('?', mapping, res, respos);
8003 if (x==enc_EXCEPTION) {
8004 return -1;
8005 }
8006 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008007 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 return -1;
8009 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008010 }
8011 /* fall through */
8012 case 3: /* ignore */
8013 *inpos = collendpos;
8014 break;
8015 case 4: /* xmlcharrefreplace */
8016 /* generate replacement (temporarily (mis)uses p) */
8017 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008018 char buffer[2+29+1+1];
8019 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008020 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 for (cp = buffer; *cp; ++cp) {
8022 x = charmapencode_output(*cp, mapping, res, respos);
8023 if (x==enc_EXCEPTION)
8024 return -1;
8025 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008026 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 return -1;
8028 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008029 }
8030 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008031 *inpos = collendpos;
8032 break;
8033 default:
8034 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008035 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008037 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008039 if (PyBytes_Check(repunicode)) {
8040 /* Directly copy bytes result to output. */
8041 Py_ssize_t outsize = PyBytes_Size(*res);
8042 Py_ssize_t requiredsize;
8043 repsize = PyBytes_Size(repunicode);
8044 requiredsize = *respos + repsize;
8045 if (requiredsize > outsize)
8046 /* Make room for all additional bytes. */
8047 if (charmapencode_resize(res, respos, requiredsize)) {
8048 Py_DECREF(repunicode);
8049 return -1;
8050 }
8051 memcpy(PyBytes_AsString(*res) + *respos,
8052 PyBytes_AsString(repunicode), repsize);
8053 *respos += repsize;
8054 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008055 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008056 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008057 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008058 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008059 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008060 Py_DECREF(repunicode);
8061 return -1;
8062 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008063 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008064 data = PyUnicode_DATA(repunicode);
8065 kind = PyUnicode_KIND(repunicode);
8066 for (index = 0; index < repsize; index++) {
8067 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8068 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008070 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 return -1;
8072 }
8073 else if (x==enc_FAILED) {
8074 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008075 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 return -1;
8077 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008078 }
8079 *inpos = newpos;
8080 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008081 }
8082 return 0;
8083}
8084
Alexander Belopolsky40018472011-02-26 01:02:56 +00008085PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008086_PyUnicode_EncodeCharmap(PyObject *unicode,
8087 PyObject *mapping,
8088 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008089{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008090 /* output object */
8091 PyObject *res = NULL;
8092 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008093 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008094 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008096 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008097 PyObject *errorHandler = NULL;
8098 PyObject *exc = NULL;
8099 /* the following variable is used for caching string comparisons
8100 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8101 * 3=ignore, 4=xmlcharrefreplace */
8102 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008103 void *data;
8104 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008105
Benjamin Petersonbac79492012-01-14 13:34:47 -05008106 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008107 return NULL;
8108 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008109 data = PyUnicode_DATA(unicode);
8110 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008111
Guido van Rossumd57fd912000-03-10 22:53:23 +00008112 /* Default to Latin-1 */
8113 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008114 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008115
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008116 /* allocate enough for a simple encoding without
8117 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008118 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008119 if (res == NULL)
8120 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008121 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008123
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008124 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008125 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008127 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 if (x==enc_EXCEPTION) /* error */
8129 goto onError;
8130 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008131 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 &exc,
8133 &known_errorHandler, &errorHandler, errors,
8134 &res, &respos)) {
8135 goto onError;
8136 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 else
8139 /* done with this character => adjust input position */
8140 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008141 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008142
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008143 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008144 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008145 if (_PyBytes_Resize(&res, respos) < 0)
8146 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008147
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008148 Py_XDECREF(exc);
8149 Py_XDECREF(errorHandler);
8150 return res;
8151
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008153 Py_XDECREF(res);
8154 Py_XDECREF(exc);
8155 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008156 return NULL;
8157}
8158
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008159/* Deprecated */
8160PyObject *
8161PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8162 Py_ssize_t size,
8163 PyObject *mapping,
8164 const char *errors)
8165{
8166 PyObject *result;
8167 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8168 if (unicode == NULL)
8169 return NULL;
8170 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8171 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008172 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008173}
8174
Alexander Belopolsky40018472011-02-26 01:02:56 +00008175PyObject *
8176PyUnicode_AsCharmapString(PyObject *unicode,
8177 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178{
8179 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 PyErr_BadArgument();
8181 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008182 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008183 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008184}
8185
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008186/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008187static void
8188make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008189 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008190 Py_ssize_t startpos, Py_ssize_t endpos,
8191 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008192{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008193 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008194 *exceptionObject = _PyUnicodeTranslateError_Create(
8195 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008196 }
8197 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8199 goto onError;
8200 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8201 goto onError;
8202 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8203 goto onError;
8204 return;
8205 onError:
8206 Py_DECREF(*exceptionObject);
8207 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008208 }
8209}
8210
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008211/* error handling callback helper:
8212 build arguments, call the callback and check the arguments,
8213 put the result into newpos and return the replacement string, which
8214 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008215static PyObject *
8216unicode_translate_call_errorhandler(const char *errors,
8217 PyObject **errorHandler,
8218 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008219 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008220 Py_ssize_t startpos, Py_ssize_t endpos,
8221 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008223 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008225 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008226 PyObject *restuple;
8227 PyObject *resunicode;
8228
8229 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233 }
8234
8235 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008236 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008239
8240 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008245 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008246 Py_DECREF(restuple);
8247 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008248 }
8249 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 &resunicode, &i_newpos)) {
8251 Py_DECREF(restuple);
8252 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008254 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008255 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008256 else
8257 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008258 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8260 Py_DECREF(restuple);
8261 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008262 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008263 Py_INCREF(resunicode);
8264 Py_DECREF(restuple);
8265 return resunicode;
8266}
8267
8268/* Lookup the character ch in the mapping and put the result in result,
8269 which must be decrefed by the caller.
8270 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008271static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008272charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008273{
Christian Heimes217cfd12007-12-02 14:31:20 +00008274 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275 PyObject *x;
8276
8277 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279 x = PyObject_GetItem(mapping, w);
8280 Py_DECREF(w);
8281 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8283 /* No mapping found means: use 1:1 mapping. */
8284 PyErr_Clear();
8285 *result = NULL;
8286 return 0;
8287 } else
8288 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289 }
8290 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 *result = x;
8292 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008294 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 long value = PyLong_AS_LONG(x);
8296 long max = PyUnicode_GetMax();
8297 if (value < 0 || value > max) {
8298 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008299 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 Py_DECREF(x);
8301 return -1;
8302 }
8303 *result = x;
8304 return 0;
8305 }
8306 else if (PyUnicode_Check(x)) {
8307 *result = x;
8308 return 0;
8309 }
8310 else {
8311 /* wrong return value */
8312 PyErr_SetString(PyExc_TypeError,
8313 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 Py_DECREF(x);
8315 return -1;
8316 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317}
8318/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 if not reallocate and adjust various state variables.
8320 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008321static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008322charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008325 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008326 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008327 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 /* exponentially overallocate to minimize reallocations */
8329 if (requiredsize < 2 * oldsize)
8330 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008331 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8332 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008334 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008335 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336 }
8337 return 0;
8338}
8339/* lookup the character, put the result in the output string and adjust
8340 various state variables. Return a new reference to the object that
8341 was put in the output buffer in *result, or Py_None, if the mapping was
8342 undefined (in which case no character was written).
8343 The called must decref result.
8344 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008345static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008346charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8347 PyObject *mapping, Py_UCS4 **output,
8348 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008349 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008351 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8352 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008356 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 }
8358 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008359 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008360 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008362 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 }
8364 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008365 Py_ssize_t repsize;
8366 if (PyUnicode_READY(*res) == -1)
8367 return -1;
8368 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 if (repsize==1) {
8370 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008371 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 }
8373 else if (repsize!=0) {
8374 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008375 Py_ssize_t requiredsize = *opos +
8376 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378 Py_ssize_t i;
8379 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008381 for(i = 0; i < repsize; i++)
8382 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008383 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 }
8385 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008387 return 0;
8388}
8389
Alexander Belopolsky40018472011-02-26 01:02:56 +00008390PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008391_PyUnicode_TranslateCharmap(PyObject *input,
8392 PyObject *mapping,
8393 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008395 /* input object */
8396 char *idata;
8397 Py_ssize_t size, i;
8398 int kind;
8399 /* output buffer */
8400 Py_UCS4 *output = NULL;
8401 Py_ssize_t osize;
8402 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008404 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405 char *reason = "character maps to <undefined>";
8406 PyObject *errorHandler = NULL;
8407 PyObject *exc = NULL;
8408 /* the following variable is used for caching string comparisons
8409 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8410 * 3=ignore, 4=xmlcharrefreplace */
8411 int known_errorHandler = -1;
8412
Guido van Rossumd57fd912000-03-10 22:53:23 +00008413 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 PyErr_BadArgument();
8415 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008416 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008418 if (PyUnicode_READY(input) == -1)
8419 return NULL;
8420 idata = (char*)PyUnicode_DATA(input);
8421 kind = PyUnicode_KIND(input);
8422 size = PyUnicode_GET_LENGTH(input);
8423 i = 0;
8424
8425 if (size == 0) {
8426 Py_INCREF(input);
8427 return input;
8428 }
8429
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 /* allocate enough for a simple 1:1 translation without
8431 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 osize = size;
8433 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8434 opos = 0;
8435 if (output == NULL) {
8436 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008440 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 /* try to encode it */
8442 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008443 if (charmaptranslate_output(input, i, mapping,
8444 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 Py_XDECREF(x);
8446 goto onError;
8447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008450 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 else { /* untranslatable character */
8452 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8453 Py_ssize_t repsize;
8454 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457 Py_ssize_t collstart = i;
8458 Py_ssize_t collend = i+1;
8459 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008460
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 while (collend < size) {
8463 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 goto onError;
8465 Py_XDECREF(x);
8466 if (x!=Py_None)
8467 break;
8468 ++collend;
8469 }
8470 /* cache callback name lookup
8471 * (if not done yet, i.e. it's the first error) */
8472 if (known_errorHandler==-1) {
8473 if ((errors==NULL) || (!strcmp(errors, "strict")))
8474 known_errorHandler = 1;
8475 else if (!strcmp(errors, "replace"))
8476 known_errorHandler = 2;
8477 else if (!strcmp(errors, "ignore"))
8478 known_errorHandler = 3;
8479 else if (!strcmp(errors, "xmlcharrefreplace"))
8480 known_errorHandler = 4;
8481 else
8482 known_errorHandler = 0;
8483 }
8484 switch (known_errorHandler) {
8485 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008486 make_translate_exception(&exc,
8487 input, collstart, collend, reason);
8488 if (exc != NULL)
8489 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008490 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 case 2: /* replace */
8492 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008493 for (coll = collstart; coll<collend; coll++)
8494 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 /* fall through */
8496 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 break;
8499 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500 /* generate replacement (temporarily (mis)uses i) */
8501 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 char buffer[2+29+1+1];
8503 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8505 if (charmaptranslate_makespace(&output, &osize,
8506 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 goto onError;
8508 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 break;
8513 default:
8514 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 reason, input, &exc,
8516 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008517 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008519 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008520 Py_DECREF(repunicode);
8521 goto onError;
8522 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008524 repsize = PyUnicode_GET_LENGTH(repunicode);
8525 if (charmaptranslate_makespace(&output, &osize,
8526 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 Py_DECREF(repunicode);
8528 goto onError;
8529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 for (uni2 = 0; repsize-->0; ++uni2)
8531 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8532 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008534 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008535 }
8536 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8538 if (!res)
8539 goto onError;
8540 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 Py_XDECREF(exc);
8542 Py_XDECREF(errorHandler);
8543 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008544
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008546 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008547 Py_XDECREF(exc);
8548 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549 return NULL;
8550}
8551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552/* Deprecated. Use PyUnicode_Translate instead. */
8553PyObject *
8554PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8555 Py_ssize_t size,
8556 PyObject *mapping,
8557 const char *errors)
8558{
Christian Heimes5f520f42012-09-11 14:03:25 +02008559 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008560 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8561 if (!unicode)
8562 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008563 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8564 Py_DECREF(unicode);
8565 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566}
8567
Alexander Belopolsky40018472011-02-26 01:02:56 +00008568PyObject *
8569PyUnicode_Translate(PyObject *str,
8570 PyObject *mapping,
8571 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572{
8573 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008574
Guido van Rossumd57fd912000-03-10 22:53:23 +00008575 str = PyUnicode_FromObject(str);
8576 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008577 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008578 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579 Py_DECREF(str);
8580 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581}
Tim Petersced69f82003-09-16 20:30:58 +00008582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008584fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585{
8586 /* No need to call PyUnicode_READY(self) because this function is only
8587 called as a callback from fixup() which does it already. */
8588 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8589 const int kind = PyUnicode_KIND(self);
8590 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008591 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008592 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 Py_ssize_t i;
8594
8595 for (i = 0; i < len; ++i) {
8596 ch = PyUnicode_READ(kind, data, i);
8597 fixed = 0;
8598 if (ch > 127) {
8599 if (Py_UNICODE_ISSPACE(ch))
8600 fixed = ' ';
8601 else {
8602 const int decimal = Py_UNICODE_TODECIMAL(ch);
8603 if (decimal >= 0)
8604 fixed = '0' + decimal;
8605 }
8606 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008607 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008608 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 PyUnicode_WRITE(kind, data, i, fixed);
8610 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008611 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008612 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 }
8615
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008616 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008617}
8618
8619PyObject *
8620_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8621{
8622 if (!PyUnicode_Check(unicode)) {
8623 PyErr_BadInternalCall();
8624 return NULL;
8625 }
8626 if (PyUnicode_READY(unicode) == -1)
8627 return NULL;
8628 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8629 /* If the string is already ASCII, just return the same string */
8630 Py_INCREF(unicode);
8631 return unicode;
8632 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008633 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634}
8635
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008636PyObject *
8637PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8638 Py_ssize_t length)
8639{
Victor Stinnerf0124502011-11-21 23:12:56 +01008640 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008641 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008642 Py_UCS4 maxchar;
8643 enum PyUnicode_Kind kind;
8644 void *data;
8645
Victor Stinner99d7ad02012-02-22 13:37:39 +01008646 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008647 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008648 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008649 if (ch > 127) {
8650 int decimal = Py_UNICODE_TODECIMAL(ch);
8651 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008652 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008653 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008654 }
8655 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008656
8657 /* Copy to a new string */
8658 decimal = PyUnicode_New(length, maxchar);
8659 if (decimal == NULL)
8660 return decimal;
8661 kind = PyUnicode_KIND(decimal);
8662 data = PyUnicode_DATA(decimal);
8663 /* Iterate over code points */
8664 for (i = 0; i < length; i++) {
8665 Py_UNICODE ch = s[i];
8666 if (ch > 127) {
8667 int decimal = Py_UNICODE_TODECIMAL(ch);
8668 if (decimal >= 0)
8669 ch = '0' + decimal;
8670 }
8671 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008673 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008674}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008675/* --- Decimal Encoder ---------------------------------------------------- */
8676
Alexander Belopolsky40018472011-02-26 01:02:56 +00008677int
8678PyUnicode_EncodeDecimal(Py_UNICODE *s,
8679 Py_ssize_t length,
8680 char *output,
8681 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008682{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008683 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008684 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008685 enum PyUnicode_Kind kind;
8686 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008687
8688 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 PyErr_BadArgument();
8690 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008691 }
8692
Victor Stinner42bf7752011-11-21 22:52:58 +01008693 unicode = PyUnicode_FromUnicode(s, length);
8694 if (unicode == NULL)
8695 return -1;
8696
Benjamin Petersonbac79492012-01-14 13:34:47 -05008697 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008698 Py_DECREF(unicode);
8699 return -1;
8700 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008701 kind = PyUnicode_KIND(unicode);
8702 data = PyUnicode_DATA(unicode);
8703
Victor Stinnerb84d7232011-11-22 01:50:07 +01008704 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008705 PyObject *exc;
8706 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008708 Py_ssize_t startpos;
8709
8710 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008711
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008713 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008714 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008716 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 decimal = Py_UNICODE_TODECIMAL(ch);
8718 if (decimal >= 0) {
8719 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008720 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 continue;
8722 }
8723 if (0 < ch && ch < 256) {
8724 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008725 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 continue;
8727 }
Victor Stinner6345be92011-11-25 20:09:01 +01008728
Victor Stinner42bf7752011-11-21 22:52:58 +01008729 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008730 exc = NULL;
8731 raise_encode_exception(&exc, "decimal", unicode,
8732 startpos, startpos+1,
8733 "invalid decimal Unicode string");
8734 Py_XDECREF(exc);
8735 Py_DECREF(unicode);
8736 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008737 }
8738 /* 0-terminate the output string */
8739 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008740 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008741 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008742}
8743
Guido van Rossumd57fd912000-03-10 22:53:23 +00008744/* --- Helpers ------------------------------------------------------------ */
8745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008747any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748 Py_ssize_t start,
8749 Py_ssize_t end)
8750{
8751 int kind1, kind2, kind;
8752 void *buf1, *buf2;
8753 Py_ssize_t len1, len2, result;
8754
8755 kind1 = PyUnicode_KIND(s1);
8756 kind2 = PyUnicode_KIND(s2);
8757 kind = kind1 > kind2 ? kind1 : kind2;
8758 buf1 = PyUnicode_DATA(s1);
8759 buf2 = PyUnicode_DATA(s2);
8760 if (kind1 != kind)
8761 buf1 = _PyUnicode_AsKind(s1, kind);
8762 if (!buf1)
8763 return -2;
8764 if (kind2 != kind)
8765 buf2 = _PyUnicode_AsKind(s2, kind);
8766 if (!buf2) {
8767 if (kind1 != kind) PyMem_Free(buf1);
8768 return -2;
8769 }
8770 len1 = PyUnicode_GET_LENGTH(s1);
8771 len2 = PyUnicode_GET_LENGTH(s2);
8772
Victor Stinner794d5672011-10-10 03:21:36 +02008773 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008774 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008775 case PyUnicode_1BYTE_KIND:
8776 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8777 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8778 else
8779 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8780 break;
8781 case PyUnicode_2BYTE_KIND:
8782 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8783 break;
8784 case PyUnicode_4BYTE_KIND:
8785 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8786 break;
8787 default:
8788 assert(0); result = -2;
8789 }
8790 }
8791 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008792 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008793 case PyUnicode_1BYTE_KIND:
8794 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8795 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8796 else
8797 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8798 break;
8799 case PyUnicode_2BYTE_KIND:
8800 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8801 break;
8802 case PyUnicode_4BYTE_KIND:
8803 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8804 break;
8805 default:
8806 assert(0); result = -2;
8807 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808 }
8809
8810 if (kind1 != kind)
8811 PyMem_Free(buf1);
8812 if (kind2 != kind)
8813 PyMem_Free(buf2);
8814
8815 return result;
8816}
8817
8818Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008819_PyUnicode_InsertThousandsGrouping(
8820 PyObject *unicode, Py_ssize_t index,
8821 Py_ssize_t n_buffer,
8822 void *digits, Py_ssize_t n_digits,
8823 Py_ssize_t min_width,
8824 const char *grouping, PyObject *thousands_sep,
8825 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008826{
Victor Stinner41a863c2012-02-24 00:37:51 +01008827 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008828 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008829 Py_ssize_t thousands_sep_len;
8830 Py_ssize_t len;
8831
8832 if (unicode != NULL) {
8833 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008834 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008835 }
8836 else {
8837 kind = PyUnicode_1BYTE_KIND;
8838 data = NULL;
8839 }
8840 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8841 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8842 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8843 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008844 if (thousands_sep_kind < kind) {
8845 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8846 if (!thousands_sep_data)
8847 return -1;
8848 }
8849 else {
8850 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8851 if (!data)
8852 return -1;
8853 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008854 }
8855
Benjamin Petersonead6b532011-12-20 17:23:42 -06008856 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008858 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008859 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008860 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008861 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008862 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008863 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008864 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008865 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008866 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008867 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008868 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008870 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008871 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008872 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008873 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008874 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008875 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008876 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008877 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008878 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008879 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008880 break;
8881 default:
8882 assert(0);
8883 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008885 if (unicode != NULL && thousands_sep_kind != kind) {
8886 if (thousands_sep_kind < kind)
8887 PyMem_Free(thousands_sep_data);
8888 else
8889 PyMem_Free(data);
8890 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008891 if (unicode == NULL) {
8892 *maxchar = 127;
8893 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07008894 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02008895 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008896 }
8897 }
8898 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899}
8900
8901
Thomas Wouters477c8d52006-05-27 19:21:47 +00008902/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008903#define ADJUST_INDICES(start, end, len) \
8904 if (end > len) \
8905 end = len; \
8906 else if (end < 0) { \
8907 end += len; \
8908 if (end < 0) \
8909 end = 0; \
8910 } \
8911 if (start < 0) { \
8912 start += len; \
8913 if (start < 0) \
8914 start = 0; \
8915 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008916
Alexander Belopolsky40018472011-02-26 01:02:56 +00008917Py_ssize_t
8918PyUnicode_Count(PyObject *str,
8919 PyObject *substr,
8920 Py_ssize_t start,
8921 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008922{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008923 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008924 PyObject* str_obj;
8925 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926 int kind1, kind2, kind;
8927 void *buf1 = NULL, *buf2 = NULL;
8928 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008929
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008930 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008931 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008933 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008934 if (!sub_obj) {
8935 Py_DECREF(str_obj);
8936 return -1;
8937 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008938 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008939 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008940 Py_DECREF(str_obj);
8941 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008942 }
Tim Petersced69f82003-09-16 20:30:58 +00008943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008944 kind1 = PyUnicode_KIND(str_obj);
8945 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008946 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008947 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008949 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008950 if (kind2 > kind) {
8951 Py_DECREF(sub_obj);
8952 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008953 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008954 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008955 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008956 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008957 if (!buf2)
8958 goto onError;
8959 len1 = PyUnicode_GET_LENGTH(str_obj);
8960 len2 = PyUnicode_GET_LENGTH(sub_obj);
8961
8962 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008963 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008965 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8966 result = asciilib_count(
8967 ((Py_UCS1*)buf1) + start, end - start,
8968 buf2, len2, PY_SSIZE_T_MAX
8969 );
8970 else
8971 result = ucs1lib_count(
8972 ((Py_UCS1*)buf1) + start, end - start,
8973 buf2, len2, PY_SSIZE_T_MAX
8974 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975 break;
8976 case PyUnicode_2BYTE_KIND:
8977 result = ucs2lib_count(
8978 ((Py_UCS2*)buf1) + start, end - start,
8979 buf2, len2, PY_SSIZE_T_MAX
8980 );
8981 break;
8982 case PyUnicode_4BYTE_KIND:
8983 result = ucs4lib_count(
8984 ((Py_UCS4*)buf1) + start, end - start,
8985 buf2, len2, PY_SSIZE_T_MAX
8986 );
8987 break;
8988 default:
8989 assert(0); result = 0;
8990 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008991
8992 Py_DECREF(sub_obj);
8993 Py_DECREF(str_obj);
8994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008995 if (kind2 != kind)
8996 PyMem_Free(buf2);
8997
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008999 onError:
9000 Py_DECREF(sub_obj);
9001 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002 if (kind2 != kind && buf2)
9003 PyMem_Free(buf2);
9004 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009005}
9006
Alexander Belopolsky40018472011-02-26 01:02:56 +00009007Py_ssize_t
9008PyUnicode_Find(PyObject *str,
9009 PyObject *sub,
9010 Py_ssize_t start,
9011 Py_ssize_t end,
9012 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009014 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009015
Guido van Rossumd57fd912000-03-10 22:53:23 +00009016 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009017 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009018 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009019 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009020 if (!sub) {
9021 Py_DECREF(str);
9022 return -2;
9023 }
9024 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9025 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009026 Py_DECREF(str);
9027 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009028 }
Tim Petersced69f82003-09-16 20:30:58 +00009029
Victor Stinner794d5672011-10-10 03:21:36 +02009030 result = any_find_slice(direction,
9031 str, sub, start, end
9032 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009033
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009035 Py_DECREF(sub);
9036
Guido van Rossumd57fd912000-03-10 22:53:23 +00009037 return result;
9038}
9039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040Py_ssize_t
9041PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9042 Py_ssize_t start, Py_ssize_t end,
9043 int direction)
9044{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009045 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009046 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 if (PyUnicode_READY(str) == -1)
9048 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009049 if (start < 0 || end < 0) {
9050 PyErr_SetString(PyExc_IndexError, "string index out of range");
9051 return -2;
9052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 if (end > PyUnicode_GET_LENGTH(str))
9054 end = PyUnicode_GET_LENGTH(str);
9055 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009056 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9057 kind, end-start, ch, direction);
9058 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009060 else
9061 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062}
9063
Alexander Belopolsky40018472011-02-26 01:02:56 +00009064static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009065tailmatch(PyObject *self,
9066 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009067 Py_ssize_t start,
9068 Py_ssize_t end,
9069 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009070{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071 int kind_self;
9072 int kind_sub;
9073 void *data_self;
9074 void *data_sub;
9075 Py_ssize_t offset;
9076 Py_ssize_t i;
9077 Py_ssize_t end_sub;
9078
9079 if (PyUnicode_READY(self) == -1 ||
9080 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009081 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009082
9083 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009084 return 1;
9085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9087 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009088 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009089 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 kind_self = PyUnicode_KIND(self);
9092 data_self = PyUnicode_DATA(self);
9093 kind_sub = PyUnicode_KIND(substring);
9094 data_sub = PyUnicode_DATA(substring);
9095 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9096
9097 if (direction > 0)
9098 offset = end;
9099 else
9100 offset = start;
9101
9102 if (PyUnicode_READ(kind_self, data_self, offset) ==
9103 PyUnicode_READ(kind_sub, data_sub, 0) &&
9104 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9105 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9106 /* If both are of the same kind, memcmp is sufficient */
9107 if (kind_self == kind_sub) {
9108 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009109 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 data_sub,
9111 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009112 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113 }
9114 /* otherwise we have to compare each character by first accesing it */
9115 else {
9116 /* We do not need to compare 0 and len(substring)-1 because
9117 the if statement above ensured already that they are equal
9118 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 for (i = 1; i < end_sub; ++i) {
9120 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9121 PyUnicode_READ(kind_sub, data_sub, i))
9122 return 0;
9123 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009124 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009126 }
9127
9128 return 0;
9129}
9130
Alexander Belopolsky40018472011-02-26 01:02:56 +00009131Py_ssize_t
9132PyUnicode_Tailmatch(PyObject *str,
9133 PyObject *substr,
9134 Py_ssize_t start,
9135 Py_ssize_t end,
9136 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009137{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009138 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009139
Guido van Rossumd57fd912000-03-10 22:53:23 +00009140 str = PyUnicode_FromObject(str);
9141 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143 substr = PyUnicode_FromObject(substr);
9144 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 Py_DECREF(str);
9146 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147 }
Tim Petersced69f82003-09-16 20:30:58 +00009148
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009149 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009150 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151 Py_DECREF(str);
9152 Py_DECREF(substr);
9153 return result;
9154}
9155
Guido van Rossumd57fd912000-03-10 22:53:23 +00009156/* Apply fixfct filter to the Unicode object self and return a
9157 reference to the modified object */
9158
Alexander Belopolsky40018472011-02-26 01:02:56 +00009159static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009160fixup(PyObject *self,
9161 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 PyObject *u;
9164 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009165 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009167 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009169 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009170 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009172 /* fix functions return the new maximum character in a string,
9173 if the kind of the resulting unicode object does not change,
9174 everything is fine. Otherwise we need to change the string kind
9175 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009176 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009177
9178 if (maxchar_new == 0) {
9179 /* no changes */;
9180 if (PyUnicode_CheckExact(self)) {
9181 Py_DECREF(u);
9182 Py_INCREF(self);
9183 return self;
9184 }
9185 else
9186 return u;
9187 }
9188
Victor Stinnere6abb482012-05-02 01:15:40 +02009189 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190
Victor Stinnereaab6042011-12-11 22:22:39 +01009191 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009193
9194 /* In case the maximum character changed, we need to
9195 convert the string to the new category. */
9196 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9197 if (v == NULL) {
9198 Py_DECREF(u);
9199 return NULL;
9200 }
9201 if (maxchar_new > maxchar_old) {
9202 /* If the maxchar increased so that the kind changed, not all
9203 characters are representable anymore and we need to fix the
9204 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009205 _PyUnicode_FastCopyCharacters(v, 0,
9206 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009207 maxchar_old = fixfct(v);
9208 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 }
9210 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009211 _PyUnicode_FastCopyCharacters(v, 0,
9212 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009214 Py_DECREF(u);
9215 assert(_PyUnicode_CheckConsistency(v, 1));
9216 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009217}
9218
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009219static PyObject *
9220ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009221{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009222 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9223 char *resdata, *data = PyUnicode_DATA(self);
9224 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009225
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009226 res = PyUnicode_New(len, 127);
9227 if (res == NULL)
9228 return NULL;
9229 resdata = PyUnicode_DATA(res);
9230 if (lower)
9231 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009233 _Py_bytes_upper(resdata, data, len);
9234 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009235}
9236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009238handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009240 Py_ssize_t j;
9241 int final_sigma;
9242 Py_UCS4 c;
9243 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009244
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009245 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9246
9247 where ! is a negation and \p{xxx} is a character with property xxx.
9248 */
9249 for (j = i - 1; j >= 0; j--) {
9250 c = PyUnicode_READ(kind, data, j);
9251 if (!_PyUnicode_IsCaseIgnorable(c))
9252 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009254 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9255 if (final_sigma) {
9256 for (j = i + 1; j < length; j++) {
9257 c = PyUnicode_READ(kind, data, j);
9258 if (!_PyUnicode_IsCaseIgnorable(c))
9259 break;
9260 }
9261 final_sigma = j == length || !_PyUnicode_IsCased(c);
9262 }
9263 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009264}
9265
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009266static int
9267lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9268 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009270 /* Obscure special case. */
9271 if (c == 0x3A3) {
9272 mapped[0] = handle_capital_sigma(kind, data, length, i);
9273 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009274 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009275 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276}
9277
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009278static Py_ssize_t
9279do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009281 Py_ssize_t i, k = 0;
9282 int n_res, j;
9283 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009284
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009285 c = PyUnicode_READ(kind, data, 0);
9286 n_res = _PyUnicode_ToUpperFull(c, mapped);
9287 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009288 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009289 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009291 for (i = 1; i < length; i++) {
9292 c = PyUnicode_READ(kind, data, i);
9293 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9294 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009295 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009296 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009297 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009298 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009299 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300}
9301
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009302static Py_ssize_t
9303do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9304 Py_ssize_t i, k = 0;
9305
9306 for (i = 0; i < length; i++) {
9307 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9308 int n_res, j;
9309 if (Py_UNICODE_ISUPPER(c)) {
9310 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9311 }
9312 else if (Py_UNICODE_ISLOWER(c)) {
9313 n_res = _PyUnicode_ToUpperFull(c, mapped);
9314 }
9315 else {
9316 n_res = 1;
9317 mapped[0] = c;
9318 }
9319 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009320 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009321 res[k++] = mapped[j];
9322 }
9323 }
9324 return k;
9325}
9326
9327static Py_ssize_t
9328do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9329 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009331 Py_ssize_t i, k = 0;
9332
9333 for (i = 0; i < length; i++) {
9334 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9335 int n_res, j;
9336 if (lower)
9337 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9338 else
9339 n_res = _PyUnicode_ToUpperFull(c, mapped);
9340 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009341 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009342 res[k++] = mapped[j];
9343 }
9344 }
9345 return k;
9346}
9347
9348static Py_ssize_t
9349do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9350{
9351 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9352}
9353
9354static Py_ssize_t
9355do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9356{
9357 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9358}
9359
Benjamin Petersone51757f2012-01-12 21:10:29 -05009360static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009361do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9362{
9363 Py_ssize_t i, k = 0;
9364
9365 for (i = 0; i < length; i++) {
9366 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9367 Py_UCS4 mapped[3];
9368 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9369 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009370 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009371 res[k++] = mapped[j];
9372 }
9373 }
9374 return k;
9375}
9376
9377static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009378do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9379{
9380 Py_ssize_t i, k = 0;
9381 int previous_is_cased;
9382
9383 previous_is_cased = 0;
9384 for (i = 0; i < length; i++) {
9385 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9386 Py_UCS4 mapped[3];
9387 int n_res, j;
9388
9389 if (previous_is_cased)
9390 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9391 else
9392 n_res = _PyUnicode_ToTitleFull(c, mapped);
9393
9394 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009395 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009396 res[k++] = mapped[j];
9397 }
9398
9399 previous_is_cased = _PyUnicode_IsCased(c);
9400 }
9401 return k;
9402}
9403
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009404static PyObject *
9405case_operation(PyObject *self,
9406 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9407{
9408 PyObject *res = NULL;
9409 Py_ssize_t length, newlength = 0;
9410 int kind, outkind;
9411 void *data, *outdata;
9412 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9413
Benjamin Petersoneea48462012-01-16 14:28:50 -05009414 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009415
9416 kind = PyUnicode_KIND(self);
9417 data = PyUnicode_DATA(self);
9418 length = PyUnicode_GET_LENGTH(self);
9419 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9420 if (tmp == NULL)
9421 return PyErr_NoMemory();
9422 newlength = perform(kind, data, length, tmp, &maxchar);
9423 res = PyUnicode_New(newlength, maxchar);
9424 if (res == NULL)
9425 goto leave;
9426 tmpend = tmp + newlength;
9427 outdata = PyUnicode_DATA(res);
9428 outkind = PyUnicode_KIND(res);
9429 switch (outkind) {
9430 case PyUnicode_1BYTE_KIND:
9431 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9432 break;
9433 case PyUnicode_2BYTE_KIND:
9434 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9435 break;
9436 case PyUnicode_4BYTE_KIND:
9437 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9438 break;
9439 default:
9440 assert(0);
9441 break;
9442 }
9443 leave:
9444 PyMem_FREE(tmp);
9445 return res;
9446}
9447
Tim Peters8ce9f162004-08-27 01:49:32 +00009448PyObject *
9449PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009452 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009454 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009455 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9456 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009457 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009459 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009461 int use_memcpy;
9462 unsigned char *res_data = NULL, *sep_data = NULL;
9463 PyObject *last_obj;
9464 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009465
Tim Peters05eba1f2004-08-27 21:32:02 +00009466 fseq = PySequence_Fast(seq, "");
9467 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009468 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009469 }
9470
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009471 /* NOTE: the following code can't call back into Python code,
9472 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009473 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009474
Tim Peters05eba1f2004-08-27 21:32:02 +00009475 seqlen = PySequence_Fast_GET_SIZE(fseq);
9476 /* If empty sequence, return u"". */
9477 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009478 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009479 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009480 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009481
Tim Peters05eba1f2004-08-27 21:32:02 +00009482 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009483 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009484 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009485 if (seqlen == 1) {
9486 if (PyUnicode_CheckExact(items[0])) {
9487 res = items[0];
9488 Py_INCREF(res);
9489 Py_DECREF(fseq);
9490 return res;
9491 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009492 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009493 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009494 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009495 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009496 /* Set up sep and seplen */
9497 if (separator == NULL) {
9498 /* fall back to a blank space separator */
9499 sep = PyUnicode_FromOrdinal(' ');
9500 if (!sep)
9501 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009502 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009503 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009504 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009505 else {
9506 if (!PyUnicode_Check(separator)) {
9507 PyErr_Format(PyExc_TypeError,
9508 "separator: expected str instance,"
9509 " %.80s found",
9510 Py_TYPE(separator)->tp_name);
9511 goto onError;
9512 }
9513 if (PyUnicode_READY(separator))
9514 goto onError;
9515 sep = separator;
9516 seplen = PyUnicode_GET_LENGTH(separator);
9517 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9518 /* inc refcount to keep this code path symmetric with the
9519 above case of a blank separator */
9520 Py_INCREF(sep);
9521 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009522 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009523 }
9524
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009525 /* There are at least two things to join, or else we have a subclass
9526 * of str in the sequence.
9527 * Do a pre-pass to figure out the total amount of space we'll
9528 * need (sz), and see whether all argument are strings.
9529 */
9530 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009531#ifdef Py_DEBUG
9532 use_memcpy = 0;
9533#else
9534 use_memcpy = 1;
9535#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009536 for (i = 0; i < seqlen; i++) {
9537 const Py_ssize_t old_sz = sz;
9538 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009539 if (!PyUnicode_Check(item)) {
9540 PyErr_Format(PyExc_TypeError,
9541 "sequence item %zd: expected str instance,"
9542 " %.80s found",
9543 i, Py_TYPE(item)->tp_name);
9544 goto onError;
9545 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 if (PyUnicode_READY(item) == -1)
9547 goto onError;
9548 sz += PyUnicode_GET_LENGTH(item);
9549 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009550 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009551 if (i != 0)
9552 sz += seplen;
9553 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9554 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009555 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009556 goto onError;
9557 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009558 if (use_memcpy && last_obj != NULL) {
9559 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9560 use_memcpy = 0;
9561 }
9562 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009563 }
Tim Petersced69f82003-09-16 20:30:58 +00009564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009566 if (res == NULL)
9567 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009568
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009569 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009570#ifdef Py_DEBUG
9571 use_memcpy = 0;
9572#else
9573 if (use_memcpy) {
9574 res_data = PyUnicode_1BYTE_DATA(res);
9575 kind = PyUnicode_KIND(res);
9576 if (seplen != 0)
9577 sep_data = PyUnicode_1BYTE_DATA(sep);
9578 }
9579#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009580 if (use_memcpy) {
9581 for (i = 0; i < seqlen; ++i) {
9582 Py_ssize_t itemlen;
9583 item = items[i];
9584
9585 /* Copy item, and maybe the separator. */
9586 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009587 Py_MEMCPY(res_data,
9588 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009589 kind * seplen);
9590 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009591 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009592
9593 itemlen = PyUnicode_GET_LENGTH(item);
9594 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009595 Py_MEMCPY(res_data,
9596 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009597 kind * itemlen);
9598 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009599 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009600 }
9601 assert(res_data == PyUnicode_1BYTE_DATA(res)
9602 + kind * PyUnicode_GET_LENGTH(res));
9603 }
9604 else {
9605 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9606 Py_ssize_t itemlen;
9607 item = items[i];
9608
9609 /* Copy item, and maybe the separator. */
9610 if (i && seplen != 0) {
9611 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9612 res_offset += seplen;
9613 }
9614
9615 itemlen = PyUnicode_GET_LENGTH(item);
9616 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009617 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009618 res_offset += itemlen;
9619 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009620 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009621 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009622 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009623
Tim Peters05eba1f2004-08-27 21:32:02 +00009624 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009626 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009628
Benjamin Peterson29060642009-01-31 22:14:21 +00009629 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009630 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009632 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633 return NULL;
9634}
9635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009636#define FILL(kind, data, value, start, length) \
9637 do { \
9638 Py_ssize_t i_ = 0; \
9639 assert(kind != PyUnicode_WCHAR_KIND); \
9640 switch ((kind)) { \
9641 case PyUnicode_1BYTE_KIND: { \
9642 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009643 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 break; \
9645 } \
9646 case PyUnicode_2BYTE_KIND: { \
9647 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9648 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9649 break; \
9650 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009651 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009652 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9653 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9654 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009655 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656 } \
9657 } \
9658 } while (0)
9659
Victor Stinnerd3f08822012-05-29 12:57:52 +02009660void
9661_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9662 Py_UCS4 fill_char)
9663{
9664 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9665 const void *data = PyUnicode_DATA(unicode);
9666 assert(PyUnicode_IS_READY(unicode));
9667 assert(unicode_modifiable(unicode));
9668 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9669 assert(start >= 0);
9670 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9671 FILL(kind, data, fill_char, start, length);
9672}
9673
Victor Stinner3fe55312012-01-04 00:33:50 +01009674Py_ssize_t
9675PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9676 Py_UCS4 fill_char)
9677{
9678 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009679
9680 if (!PyUnicode_Check(unicode)) {
9681 PyErr_BadInternalCall();
9682 return -1;
9683 }
9684 if (PyUnicode_READY(unicode) == -1)
9685 return -1;
9686 if (unicode_check_modifiable(unicode))
9687 return -1;
9688
Victor Stinnerd3f08822012-05-29 12:57:52 +02009689 if (start < 0) {
9690 PyErr_SetString(PyExc_IndexError, "string index out of range");
9691 return -1;
9692 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009693 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9694 PyErr_SetString(PyExc_ValueError,
9695 "fill character is bigger than "
9696 "the string maximum character");
9697 return -1;
9698 }
9699
9700 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9701 length = Py_MIN(maxlen, length);
9702 if (length <= 0)
9703 return 0;
9704
Victor Stinnerd3f08822012-05-29 12:57:52 +02009705 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009706 return length;
9707}
9708
Victor Stinner9310abb2011-10-05 00:59:23 +02009709static PyObject *
9710pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009711 Py_ssize_t left,
9712 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009713 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009714{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009715 PyObject *u;
9716 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009717 int kind;
9718 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009719
9720 if (left < 0)
9721 left = 0;
9722 if (right < 0)
9723 right = 0;
9724
Victor Stinnerc4b49542011-12-11 22:44:26 +01009725 if (left == 0 && right == 0)
9726 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009728 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9729 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009730 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9731 return NULL;
9732 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009734 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009736 if (!u)
9737 return NULL;
9738
9739 kind = PyUnicode_KIND(u);
9740 data = PyUnicode_DATA(u);
9741 if (left)
9742 FILL(kind, data, fill, 0, left);
9743 if (right)
9744 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009745 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009746 assert(_PyUnicode_CheckConsistency(u, 1));
9747 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009748}
9749
Alexander Belopolsky40018472011-02-26 01:02:56 +00009750PyObject *
9751PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009752{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009753 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009754
9755 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009756 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009757 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009758 if (PyUnicode_READY(string) == -1) {
9759 Py_DECREF(string);
9760 return NULL;
9761 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762
Benjamin Petersonead6b532011-12-20 17:23:42 -06009763 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009764 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009765 if (PyUnicode_IS_ASCII(string))
9766 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009767 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009768 PyUnicode_GET_LENGTH(string), keepends);
9769 else
9770 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009771 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009772 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009773 break;
9774 case PyUnicode_2BYTE_KIND:
9775 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009776 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 PyUnicode_GET_LENGTH(string), keepends);
9778 break;
9779 case PyUnicode_4BYTE_KIND:
9780 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009781 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009782 PyUnicode_GET_LENGTH(string), keepends);
9783 break;
9784 default:
9785 assert(0);
9786 list = 0;
9787 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788 Py_DECREF(string);
9789 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790}
9791
Alexander Belopolsky40018472011-02-26 01:02:56 +00009792static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009793split(PyObject *self,
9794 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009795 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 int kind1, kind2, kind;
9798 void *buf1, *buf2;
9799 Py_ssize_t len1, len2;
9800 PyObject* out;
9801
Guido van Rossumd57fd912000-03-10 22:53:23 +00009802 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009803 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009805 if (PyUnicode_READY(self) == -1)
9806 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009808 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009809 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009811 if (PyUnicode_IS_ASCII(self))
9812 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009813 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009814 PyUnicode_GET_LENGTH(self), maxcount
9815 );
9816 else
9817 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009818 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009819 PyUnicode_GET_LENGTH(self), maxcount
9820 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 case PyUnicode_2BYTE_KIND:
9822 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009823 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824 PyUnicode_GET_LENGTH(self), maxcount
9825 );
9826 case PyUnicode_4BYTE_KIND:
9827 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009828 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 PyUnicode_GET_LENGTH(self), maxcount
9830 );
9831 default:
9832 assert(0);
9833 return NULL;
9834 }
9835
9836 if (PyUnicode_READY(substring) == -1)
9837 return NULL;
9838
9839 kind1 = PyUnicode_KIND(self);
9840 kind2 = PyUnicode_KIND(substring);
9841 kind = kind1 > kind2 ? kind1 : kind2;
9842 buf1 = PyUnicode_DATA(self);
9843 buf2 = PyUnicode_DATA(substring);
9844 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009845 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009846 if (!buf1)
9847 return NULL;
9848 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009849 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 if (!buf2) {
9851 if (kind1 != kind) PyMem_Free(buf1);
9852 return NULL;
9853 }
9854 len1 = PyUnicode_GET_LENGTH(self);
9855 len2 = PyUnicode_GET_LENGTH(substring);
9856
Benjamin Petersonead6b532011-12-20 17:23:42 -06009857 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009858 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009859 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9860 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009861 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009862 else
9863 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009864 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 break;
9866 case PyUnicode_2BYTE_KIND:
9867 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009868 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 break;
9870 case PyUnicode_4BYTE_KIND:
9871 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009872 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 break;
9874 default:
9875 out = NULL;
9876 }
9877 if (kind1 != kind)
9878 PyMem_Free(buf1);
9879 if (kind2 != kind)
9880 PyMem_Free(buf2);
9881 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009882}
9883
Alexander Belopolsky40018472011-02-26 01:02:56 +00009884static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009885rsplit(PyObject *self,
9886 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009887 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 int kind1, kind2, kind;
9890 void *buf1, *buf2;
9891 Py_ssize_t len1, len2;
9892 PyObject* out;
9893
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009894 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009895 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 if (PyUnicode_READY(self) == -1)
9898 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009900 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009901 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009903 if (PyUnicode_IS_ASCII(self))
9904 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009905 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009906 PyUnicode_GET_LENGTH(self), maxcount
9907 );
9908 else
9909 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009910 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009911 PyUnicode_GET_LENGTH(self), maxcount
9912 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 case PyUnicode_2BYTE_KIND:
9914 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009915 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 PyUnicode_GET_LENGTH(self), maxcount
9917 );
9918 case PyUnicode_4BYTE_KIND:
9919 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009920 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009921 PyUnicode_GET_LENGTH(self), maxcount
9922 );
9923 default:
9924 assert(0);
9925 return NULL;
9926 }
9927
9928 if (PyUnicode_READY(substring) == -1)
9929 return NULL;
9930
9931 kind1 = PyUnicode_KIND(self);
9932 kind2 = PyUnicode_KIND(substring);
9933 kind = kind1 > kind2 ? kind1 : kind2;
9934 buf1 = PyUnicode_DATA(self);
9935 buf2 = PyUnicode_DATA(substring);
9936 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009937 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009938 if (!buf1)
9939 return NULL;
9940 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009941 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 if (!buf2) {
9943 if (kind1 != kind) PyMem_Free(buf1);
9944 return NULL;
9945 }
9946 len1 = PyUnicode_GET_LENGTH(self);
9947 len2 = PyUnicode_GET_LENGTH(substring);
9948
Benjamin Petersonead6b532011-12-20 17:23:42 -06009949 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009951 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9952 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009953 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009954 else
9955 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009956 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 break;
9958 case PyUnicode_2BYTE_KIND:
9959 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 break;
9962 case PyUnicode_4BYTE_KIND:
9963 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009964 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 break;
9966 default:
9967 out = NULL;
9968 }
9969 if (kind1 != kind)
9970 PyMem_Free(buf1);
9971 if (kind2 != kind)
9972 PyMem_Free(buf2);
9973 return out;
9974}
9975
9976static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9978 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009980 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009982 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9983 return asciilib_find(buf1, len1, buf2, len2, offset);
9984 else
9985 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 case PyUnicode_2BYTE_KIND:
9987 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9988 case PyUnicode_4BYTE_KIND:
9989 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9990 }
9991 assert(0);
9992 return -1;
9993}
9994
9995static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009996anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9997 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009999 switch (kind) {
10000 case PyUnicode_1BYTE_KIND:
10001 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10002 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10003 else
10004 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10005 case PyUnicode_2BYTE_KIND:
10006 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10007 case PyUnicode_4BYTE_KIND:
10008 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10009 }
10010 assert(0);
10011 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010012}
10013
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010014static void
10015replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10016 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10017{
10018 int kind = PyUnicode_KIND(u);
10019 void *data = PyUnicode_DATA(u);
10020 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10021 if (kind == PyUnicode_1BYTE_KIND) {
10022 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10023 (Py_UCS1 *)data + len,
10024 u1, u2, maxcount);
10025 }
10026 else if (kind == PyUnicode_2BYTE_KIND) {
10027 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10028 (Py_UCS2 *)data + len,
10029 u1, u2, maxcount);
10030 }
10031 else {
10032 assert(kind == PyUnicode_4BYTE_KIND);
10033 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10034 (Py_UCS4 *)data + len,
10035 u1, u2, maxcount);
10036 }
10037}
10038
Alexander Belopolsky40018472011-02-26 01:02:56 +000010039static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040replace(PyObject *self, PyObject *str1,
10041 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010042{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 PyObject *u;
10044 char *sbuf = PyUnicode_DATA(self);
10045 char *buf1 = PyUnicode_DATA(str1);
10046 char *buf2 = PyUnicode_DATA(str2);
10047 int srelease = 0, release1 = 0, release2 = 0;
10048 int skind = PyUnicode_KIND(self);
10049 int kind1 = PyUnicode_KIND(str1);
10050 int kind2 = PyUnicode_KIND(str2);
10051 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10052 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10053 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010054 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010055 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056
10057 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010058 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010060 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010061
Victor Stinner59de0ee2011-10-07 10:01:28 +020010062 if (str1 == str2)
10063 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064
Victor Stinner49a0a212011-10-12 23:46:10 +020010065 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010066 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10067 if (maxchar < maxchar_str1)
10068 /* substring too wide to be present */
10069 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010070 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10071 /* Replacing str1 with str2 may cause a maxchar reduction in the
10072 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010073 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010074 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010077 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010079 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010081 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010082 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010083 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010084
Victor Stinner69ed0f42013-04-09 21:48:24 +020010085 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010086 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010087 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010088 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010089 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010091 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010093
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010094 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10095 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010096 }
10097 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 int rkind = skind;
10099 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010100 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (kind1 < rkind) {
10103 /* widen substring */
10104 buf1 = _PyUnicode_AsKind(str1, rkind);
10105 if (!buf1) goto error;
10106 release1 = 1;
10107 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010108 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010109 if (i < 0)
10110 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 if (rkind > kind2) {
10112 /* widen replacement */
10113 buf2 = _PyUnicode_AsKind(str2, rkind);
10114 if (!buf2) goto error;
10115 release2 = 1;
10116 }
10117 else if (rkind < kind2) {
10118 /* widen self and buf1 */
10119 rkind = kind2;
10120 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010121 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 sbuf = _PyUnicode_AsKind(self, rkind);
10123 if (!sbuf) goto error;
10124 srelease = 1;
10125 buf1 = _PyUnicode_AsKind(str1, rkind);
10126 if (!buf1) goto error;
10127 release1 = 1;
10128 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010129 u = PyUnicode_New(slen, maxchar);
10130 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010132 assert(PyUnicode_KIND(u) == rkind);
10133 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010134
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010135 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010136 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010137 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010139 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010141
10142 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010143 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010144 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010145 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010146 if (i == -1)
10147 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010148 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010150 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010152 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010153 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010154 }
10155 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010157 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 int rkind = skind;
10159 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010162 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 buf1 = _PyUnicode_AsKind(str1, rkind);
10164 if (!buf1) goto error;
10165 release1 = 1;
10166 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010167 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010168 if (n == 0)
10169 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010171 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 buf2 = _PyUnicode_AsKind(str2, rkind);
10173 if (!buf2) goto error;
10174 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010177 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 rkind = kind2;
10179 sbuf = _PyUnicode_AsKind(self, rkind);
10180 if (!sbuf) goto error;
10181 srelease = 1;
10182 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010183 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 buf1 = _PyUnicode_AsKind(str1, rkind);
10185 if (!buf1) goto error;
10186 release1 = 1;
10187 }
10188 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10189 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010190 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 PyErr_SetString(PyExc_OverflowError,
10192 "replace string is too long");
10193 goto error;
10194 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010195 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010196 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010197 _Py_INCREF_UNICODE_EMPTY();
10198 if (!unicode_empty)
10199 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010200 u = unicode_empty;
10201 goto done;
10202 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010203 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 PyErr_SetString(PyExc_OverflowError,
10205 "replace string is too long");
10206 goto error;
10207 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010208 u = PyUnicode_New(new_size, maxchar);
10209 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010211 assert(PyUnicode_KIND(u) == rkind);
10212 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 ires = i = 0;
10214 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010215 while (n-- > 0) {
10216 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010217 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010218 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010220 if (j == -1)
10221 break;
10222 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010224 memcpy(res + rkind * ires,
10225 sbuf + rkind * i,
10226 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010228 }
10229 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010231 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010233 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010235 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010239 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010240 memcpy(res + rkind * ires,
10241 sbuf + rkind * i,
10242 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010243 }
10244 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010245 /* interleave */
10246 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010247 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010249 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010251 if (--n <= 0)
10252 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010253 memcpy(res + rkind * ires,
10254 sbuf + rkind * i,
10255 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 ires++;
10257 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010258 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010259 memcpy(res + rkind * ires,
10260 sbuf + rkind * i,
10261 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010262 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010263 }
10264
10265 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010266 unicode_adjust_maxchar(&u);
10267 if (u == NULL)
10268 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010269 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010270
10271 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 if (srelease)
10273 PyMem_FREE(sbuf);
10274 if (release1)
10275 PyMem_FREE(buf1);
10276 if (release2)
10277 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010278 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010280
Benjamin Peterson29060642009-01-31 22:14:21 +000010281 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 if (srelease)
10284 PyMem_FREE(sbuf);
10285 if (release1)
10286 PyMem_FREE(buf1);
10287 if (release2)
10288 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010289 return unicode_result_unchanged(self);
10290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 error:
10292 if (srelease && sbuf)
10293 PyMem_FREE(sbuf);
10294 if (release1 && buf1)
10295 PyMem_FREE(buf1);
10296 if (release2 && buf2)
10297 PyMem_FREE(buf2);
10298 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299}
10300
10301/* --- Unicode Object Methods --------------------------------------------- */
10302
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010303PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010304 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305\n\
10306Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010307characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010308
10309static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010310unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010312 if (PyUnicode_READY(self) == -1)
10313 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010314 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010315}
10316
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010317PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010318 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010319\n\
10320Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010321have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322
10323static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010324unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010326 if (PyUnicode_READY(self) == -1)
10327 return NULL;
10328 if (PyUnicode_GET_LENGTH(self) == 0)
10329 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010330 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010331}
10332
Benjamin Petersond5890c82012-01-14 13:23:30 -050010333PyDoc_STRVAR(casefold__doc__,
10334 "S.casefold() -> str\n\
10335\n\
10336Return a version of S suitable for caseless comparisons.");
10337
10338static PyObject *
10339unicode_casefold(PyObject *self)
10340{
10341 if (PyUnicode_READY(self) == -1)
10342 return NULL;
10343 if (PyUnicode_IS_ASCII(self))
10344 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010345 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010346}
10347
10348
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010349/* Argument converter. Coerces to a single unicode character */
10350
10351static int
10352convert_uc(PyObject *obj, void *addr)
10353{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010355 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010356
Benjamin Peterson14339b62009-01-31 16:36:08 +000010357 uniobj = PyUnicode_FromObject(obj);
10358 if (uniobj == NULL) {
10359 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010360 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010361 return 0;
10362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010364 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010365 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010366 Py_DECREF(uniobj);
10367 return 0;
10368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010370 Py_DECREF(uniobj);
10371 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010372}
10373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010374PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010375 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010377Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010378done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379
10380static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010381unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010383 Py_ssize_t marg, left;
10384 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 Py_UCS4 fillchar = ' ';
10386
Victor Stinnere9a29352011-10-01 02:14:59 +020010387 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389
Benjamin Petersonbac79492012-01-14 13:34:47 -050010390 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391 return NULL;
10392
Victor Stinnerc4b49542011-12-11 22:44:26 +010010393 if (PyUnicode_GET_LENGTH(self) >= width)
10394 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395
Victor Stinnerc4b49542011-12-11 22:44:26 +010010396 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397 left = marg / 2 + (marg & width & 1);
10398
Victor Stinner9310abb2011-10-05 00:59:23 +020010399 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400}
10401
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402/* This function assumes that str1 and str2 are readied by the caller. */
10403
Marc-André Lemburge5034372000-08-08 08:04:29 +000010404static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010405unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010406{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010407#define COMPARE(TYPE1, TYPE2) \
10408 do { \
10409 TYPE1* p1 = (TYPE1 *)data1; \
10410 TYPE2* p2 = (TYPE2 *)data2; \
10411 TYPE1* end = p1 + len; \
10412 Py_UCS4 c1, c2; \
10413 for (; p1 != end; p1++, p2++) { \
10414 c1 = *p1; \
10415 c2 = *p2; \
10416 if (c1 != c2) \
10417 return (c1 < c2) ? -1 : 1; \
10418 } \
10419 } \
10420 while (0)
10421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 int kind1, kind2;
10423 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010424 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010425
Victor Stinner90db9c42012-10-04 21:53:50 +020010426 /* a string is equal to itself */
10427 if (str1 == str2)
10428 return 0;
10429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 kind1 = PyUnicode_KIND(str1);
10431 kind2 = PyUnicode_KIND(str2);
10432 data1 = PyUnicode_DATA(str1);
10433 data2 = PyUnicode_DATA(str2);
10434 len1 = PyUnicode_GET_LENGTH(str1);
10435 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010436 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010437
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010438 switch(kind1) {
10439 case PyUnicode_1BYTE_KIND:
10440 {
10441 switch(kind2) {
10442 case PyUnicode_1BYTE_KIND:
10443 {
10444 int cmp = memcmp(data1, data2, len);
10445 /* normalize result of memcmp() into the range [-1; 1] */
10446 if (cmp < 0)
10447 return -1;
10448 if (cmp > 0)
10449 return 1;
10450 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010451 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010452 case PyUnicode_2BYTE_KIND:
10453 COMPARE(Py_UCS1, Py_UCS2);
10454 break;
10455 case PyUnicode_4BYTE_KIND:
10456 COMPARE(Py_UCS1, Py_UCS4);
10457 break;
10458 default:
10459 assert(0);
10460 }
10461 break;
10462 }
10463 case PyUnicode_2BYTE_KIND:
10464 {
10465 switch(kind2) {
10466 case PyUnicode_1BYTE_KIND:
10467 COMPARE(Py_UCS2, Py_UCS1);
10468 break;
10469 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010470 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010471 COMPARE(Py_UCS2, Py_UCS2);
10472 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010473 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010474 case PyUnicode_4BYTE_KIND:
10475 COMPARE(Py_UCS2, Py_UCS4);
10476 break;
10477 default:
10478 assert(0);
10479 }
10480 break;
10481 }
10482 case PyUnicode_4BYTE_KIND:
10483 {
10484 switch(kind2) {
10485 case PyUnicode_1BYTE_KIND:
10486 COMPARE(Py_UCS4, Py_UCS1);
10487 break;
10488 case PyUnicode_2BYTE_KIND:
10489 COMPARE(Py_UCS4, Py_UCS2);
10490 break;
10491 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010492 {
10493#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10494 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10495 /* normalize result of wmemcmp() into the range [-1; 1] */
10496 if (cmp < 0)
10497 return -1;
10498 if (cmp > 0)
10499 return 1;
10500#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010501 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010502#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010503 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010504 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010505 default:
10506 assert(0);
10507 }
10508 break;
10509 }
10510 default:
10511 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010512 }
10513
Victor Stinner770e19e2012-10-04 22:59:45 +020010514 if (len1 == len2)
10515 return 0;
10516 if (len1 < len2)
10517 return -1;
10518 else
10519 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010520
10521#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010522}
10523
Victor Stinnere5567ad2012-10-23 02:48:49 +020010524static int
10525unicode_compare_eq(PyObject *str1, PyObject *str2)
10526{
10527 int kind;
10528 void *data1, *data2;
10529 Py_ssize_t len;
10530 int cmp;
10531
10532 /* a string is equal to itself */
10533 if (str1 == str2)
10534 return 1;
10535
10536 len = PyUnicode_GET_LENGTH(str1);
10537 if (PyUnicode_GET_LENGTH(str2) != len)
10538 return 0;
10539 kind = PyUnicode_KIND(str1);
10540 if (PyUnicode_KIND(str2) != kind)
10541 return 0;
10542 data1 = PyUnicode_DATA(str1);
10543 data2 = PyUnicode_DATA(str2);
10544
10545 cmp = memcmp(data1, data2, len * kind);
10546 return (cmp == 0);
10547}
10548
10549
Alexander Belopolsky40018472011-02-26 01:02:56 +000010550int
10551PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10554 if (PyUnicode_READY(left) == -1 ||
10555 PyUnicode_READY(right) == -1)
10556 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010557 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010559 PyErr_Format(PyExc_TypeError,
10560 "Can't compare %.100s and %.100s",
10561 left->ob_type->tp_name,
10562 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563 return -1;
10564}
10565
Martin v. Löwis5b222132007-06-10 09:51:05 +000010566int
10567PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10568{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 Py_ssize_t i;
10570 int kind;
10571 void *data;
10572 Py_UCS4 chr;
10573
Victor Stinner910337b2011-10-03 03:20:16 +020010574 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 if (PyUnicode_READY(uni) == -1)
10576 return -1;
10577 kind = PyUnicode_KIND(uni);
10578 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010579 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10581 if (chr != str[i])
10582 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010583 /* This check keeps Python strings that end in '\0' from comparing equal
10584 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010586 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010587 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010588 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010589 return 0;
10590}
10591
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010592
Benjamin Peterson29060642009-01-31 22:14:21 +000010593#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010594 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010595
Alexander Belopolsky40018472011-02-26 01:02:56 +000010596PyObject *
10597PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010598{
10599 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010600 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010601
Victor Stinnere5567ad2012-10-23 02:48:49 +020010602 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10603 Py_RETURN_NOTIMPLEMENTED;
10604
10605 if (PyUnicode_READY(left) == -1 ||
10606 PyUnicode_READY(right) == -1)
10607 return NULL;
10608
10609 if (op == Py_EQ || op == Py_NE) {
10610 result = unicode_compare_eq(left, right);
10611 if (op == Py_EQ)
10612 v = TEST_COND(result);
10613 else
10614 v = TEST_COND(!result);
10615 }
10616 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010617 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010618
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010619 /* Convert the return value to a Boolean */
10620 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010621 case Py_LE:
10622 v = TEST_COND(result <= 0);
10623 break;
10624 case Py_GE:
10625 v = TEST_COND(result >= 0);
10626 break;
10627 case Py_LT:
10628 v = TEST_COND(result == -1);
10629 break;
10630 case Py_GT:
10631 v = TEST_COND(result == 1);
10632 break;
10633 default:
10634 PyErr_BadArgument();
10635 return NULL;
10636 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010637 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010638 Py_INCREF(v);
10639 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010640}
10641
Alexander Belopolsky40018472011-02-26 01:02:56 +000010642int
10643PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010644{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010645 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010646 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 void *buf1, *buf2;
10648 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010649 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010650
10651 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010652 sub = PyUnicode_FromObject(element);
10653 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010654 PyErr_Format(PyExc_TypeError,
10655 "'in <string>' requires string as left operand, not %s",
10656 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010657 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010658 }
10659
Thomas Wouters477c8d52006-05-27 19:21:47 +000010660 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010661 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 Py_DECREF(sub);
10663 return -1;
10664 }
10665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 kind1 = PyUnicode_KIND(str);
10667 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 buf1 = PyUnicode_DATA(str);
10669 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010670 if (kind2 != kind1) {
10671 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010672 Py_DECREF(sub);
10673 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010674 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010675 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010676 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 if (!buf2) {
10679 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010680 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 return -1;
10682 }
10683 len1 = PyUnicode_GET_LENGTH(str);
10684 len2 = PyUnicode_GET_LENGTH(sub);
10685
Victor Stinner77282cb2013-04-14 19:22:47 +020010686 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 case PyUnicode_1BYTE_KIND:
10688 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10689 break;
10690 case PyUnicode_2BYTE_KIND:
10691 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10692 break;
10693 case PyUnicode_4BYTE_KIND:
10694 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10695 break;
10696 default:
10697 result = -1;
10698 assert(0);
10699 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010700
10701 Py_DECREF(str);
10702 Py_DECREF(sub);
10703
Victor Stinner77282cb2013-04-14 19:22:47 +020010704 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705 PyMem_Free(buf2);
10706
Guido van Rossum403d68b2000-03-13 15:55:09 +000010707 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010708}
10709
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710/* Concat to string or Unicode object giving a new Unicode object. */
10711
Alexander Belopolsky40018472011-02-26 01:02:56 +000010712PyObject *
10713PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010715 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010716 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010717 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718
10719 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010722 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010725 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726
10727 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010728 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010729 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010732 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010733 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010734 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735 }
10736
Victor Stinner488fa492011-12-12 00:01:39 +010010737 u_len = PyUnicode_GET_LENGTH(u);
10738 v_len = PyUnicode_GET_LENGTH(v);
10739 if (u_len > PY_SSIZE_T_MAX - v_len) {
10740 PyErr_SetString(PyExc_OverflowError,
10741 "strings are too large to concat");
10742 goto onError;
10743 }
10744 new_len = u_len + v_len;
10745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010746 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010747 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010748 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010749
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010751 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010753 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010754 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10755 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756 Py_DECREF(u);
10757 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010758 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010759 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760
Benjamin Peterson29060642009-01-31 22:14:21 +000010761 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762 Py_XDECREF(u);
10763 Py_XDECREF(v);
10764 return NULL;
10765}
10766
Walter Dörwald1ab83302007-05-18 17:15:44 +000010767void
Victor Stinner23e56682011-10-03 03:54:37 +020010768PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010769{
Victor Stinner23e56682011-10-03 03:54:37 +020010770 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010771 Py_UCS4 maxchar, maxchar2;
10772 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010773
10774 if (p_left == NULL) {
10775 if (!PyErr_Occurred())
10776 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010777 return;
10778 }
Victor Stinner23e56682011-10-03 03:54:37 +020010779 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020010780 if (right == NULL || left == NULL
10781 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010782 if (!PyErr_Occurred())
10783 PyErr_BadInternalCall();
10784 goto error;
10785 }
10786
Benjamin Petersonbac79492012-01-14 13:34:47 -050010787 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010788 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010789 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010790 goto error;
10791
Victor Stinner488fa492011-12-12 00:01:39 +010010792 /* Shortcuts */
10793 if (left == unicode_empty) {
10794 Py_DECREF(left);
10795 Py_INCREF(right);
10796 *p_left = right;
10797 return;
10798 }
10799 if (right == unicode_empty)
10800 return;
10801
10802 left_len = PyUnicode_GET_LENGTH(left);
10803 right_len = PyUnicode_GET_LENGTH(right);
10804 if (left_len > PY_SSIZE_T_MAX - right_len) {
10805 PyErr_SetString(PyExc_OverflowError,
10806 "strings are too large to concat");
10807 goto error;
10808 }
10809 new_len = left_len + right_len;
10810
10811 if (unicode_modifiable(left)
10812 && PyUnicode_CheckExact(right)
10813 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010814 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10815 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010816 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010817 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010818 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10819 {
10820 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010821 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010010822 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020010823
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010824 /* copy 'right' into the newly allocated area of 'left' */
10825 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010826 }
Victor Stinner488fa492011-12-12 00:01:39 +010010827 else {
10828 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10829 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010830 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010831
Victor Stinner488fa492011-12-12 00:01:39 +010010832 /* Concat the two Unicode strings */
10833 res = PyUnicode_New(new_len, maxchar);
10834 if (res == NULL)
10835 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010836 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10837 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010838 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010839 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010010840 }
10841 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010842 return;
10843
10844error:
Victor Stinner488fa492011-12-12 00:01:39 +010010845 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010846}
10847
10848void
10849PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10850{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010851 PyUnicode_Append(pleft, right);
10852 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010853}
10854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010855PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010856 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010858Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010859string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010860interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861
10862static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010863unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010865 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010866 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010867 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010868 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010869 int kind1, kind2, kind;
10870 void *buf1, *buf2;
10871 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872
Jesus Ceaac451502011-04-20 17:09:23 +020010873 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10874 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010875 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010877 kind1 = PyUnicode_KIND(self);
10878 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020010879 if (kind2 > kind1) {
10880 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010881 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020010882 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010883 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010884 buf1 = PyUnicode_DATA(self);
10885 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010886 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010887 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010888 if (!buf2) {
10889 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010890 return NULL;
10891 }
10892 len1 = PyUnicode_GET_LENGTH(self);
10893 len2 = PyUnicode_GET_LENGTH(substring);
10894
10895 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010896 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010897 case PyUnicode_1BYTE_KIND:
10898 iresult = ucs1lib_count(
10899 ((Py_UCS1*)buf1) + start, end - start,
10900 buf2, len2, PY_SSIZE_T_MAX
10901 );
10902 break;
10903 case PyUnicode_2BYTE_KIND:
10904 iresult = ucs2lib_count(
10905 ((Py_UCS2*)buf1) + start, end - start,
10906 buf2, len2, PY_SSIZE_T_MAX
10907 );
10908 break;
10909 case PyUnicode_4BYTE_KIND:
10910 iresult = ucs4lib_count(
10911 ((Py_UCS4*)buf1) + start, end - start,
10912 buf2, len2, PY_SSIZE_T_MAX
10913 );
10914 break;
10915 default:
10916 assert(0); iresult = 0;
10917 }
10918
10919 result = PyLong_FromSsize_t(iresult);
10920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010921 if (kind2 != kind)
10922 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923
10924 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010925
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926 return result;
10927}
10928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010929PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010930 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010932Encode S using the codec registered for encoding. Default encoding\n\
10933is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010934handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010935a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10936'xmlcharrefreplace' as well as any other name registered with\n\
10937codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938
10939static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010940unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010942 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943 char *encoding = NULL;
10944 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010945
Benjamin Peterson308d6372009-09-18 21:42:35 +000010946 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10947 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010949 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010950}
10951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010952PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010953 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954\n\
10955Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010956If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957
10958static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010959unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010961 Py_ssize_t i, j, line_pos, src_len, incr;
10962 Py_UCS4 ch;
10963 PyObject *u;
10964 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010966 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010967 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968
10969 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010970 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010971
Antoine Pitrou22425222011-10-04 19:10:51 +020010972 if (PyUnicode_READY(self) == -1)
10973 return NULL;
10974
Thomas Wouters7e474022000-07-16 12:04:32 +000010975 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010976 src_len = PyUnicode_GET_LENGTH(self);
10977 i = j = line_pos = 0;
10978 kind = PyUnicode_KIND(self);
10979 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010980 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010981 for (; i < src_len; i++) {
10982 ch = PyUnicode_READ(kind, src_data, i);
10983 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010984 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010986 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010987 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010988 goto overflow;
10989 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010990 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010991 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010994 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010995 goto overflow;
10996 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010998 if (ch == '\n' || ch == '\r')
10999 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011001 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011002 if (!found)
11003 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011004
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011006 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 if (!u)
11008 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011009 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010
Antoine Pitroue71d5742011-10-04 15:55:09 +020011011 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012
Antoine Pitroue71d5742011-10-04 15:55:09 +020011013 for (; i < src_len; i++) {
11014 ch = PyUnicode_READ(kind, src_data, i);
11015 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011016 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011017 incr = tabsize - (line_pos % tabsize);
11018 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011019 FILL(kind, dest_data, ' ', j, incr);
11020 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011021 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011022 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011023 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011024 line_pos++;
11025 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011026 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011027 if (ch == '\n' || ch == '\r')
11028 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011030 }
11031 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011032 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011033
Antoine Pitroue71d5742011-10-04 15:55:09 +020011034 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011035 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11036 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037}
11038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011039PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011040 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041\n\
11042Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011043such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044arguments start and end are interpreted as in slice notation.\n\
11045\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011046Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047
11048static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011049unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011051 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011052 Py_ssize_t start;
11053 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011054 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055
Jesus Ceaac451502011-04-20 17:09:23 +020011056 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11057 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059
Christian Heimesd47802e2013-06-29 21:33:36 +020011060 if (PyUnicode_READY(self) == -1) {
11061 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011062 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011063 }
11064 if (PyUnicode_READY(substring) == -1) {
11065 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068
Victor Stinner7931d9a2011-11-04 00:22:48 +010011069 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070
11071 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 if (result == -2)
11074 return NULL;
11075
Christian Heimes217cfd12007-12-02 14:31:20 +000011076 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077}
11078
11079static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011080unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011082 void *data;
11083 enum PyUnicode_Kind kind;
11084 Py_UCS4 ch;
11085 PyObject *res;
11086
11087 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11088 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011090 }
11091 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11092 PyErr_SetString(PyExc_IndexError, "string index out of range");
11093 return NULL;
11094 }
11095 kind = PyUnicode_KIND(self);
11096 data = PyUnicode_DATA(self);
11097 ch = PyUnicode_READ(kind, data, index);
11098 if (ch < 256)
11099 return get_latin1_char(ch);
11100
11101 res = PyUnicode_New(1, ch);
11102 if (res == NULL)
11103 return NULL;
11104 kind = PyUnicode_KIND(res);
11105 data = PyUnicode_DATA(res);
11106 PyUnicode_WRITE(kind, data, 0, ch);
11107 assert(_PyUnicode_CheckConsistency(res, 1));
11108 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109}
11110
Guido van Rossumc2504932007-09-18 19:42:40 +000011111/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011112 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011113static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011114unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115{
Guido van Rossumc2504932007-09-18 19:42:40 +000011116 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011117 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011118
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011119#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011120 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011121#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122 if (_PyUnicode_HASH(self) != -1)
11123 return _PyUnicode_HASH(self);
11124 if (PyUnicode_READY(self) == -1)
11125 return -1;
11126 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011127 /*
11128 We make the hash of the empty string be 0, rather than using
11129 (prefix ^ suffix), since this slightly obfuscates the hash secret
11130 */
11131 if (len == 0) {
11132 _PyUnicode_HASH(self) = 0;
11133 return 0;
11134 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135
11136 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011137#define HASH(P) \
11138 x ^= (Py_uhash_t) *P << 7; \
11139 while (--len >= 0) \
11140 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141
Georg Brandl2fb477c2012-02-21 00:33:36 +010011142 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 switch (PyUnicode_KIND(self)) {
11144 case PyUnicode_1BYTE_KIND: {
11145 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11146 HASH(c);
11147 break;
11148 }
11149 case PyUnicode_2BYTE_KIND: {
11150 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11151 HASH(s);
11152 break;
11153 }
11154 default: {
11155 Py_UCS4 *l;
11156 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11157 "Impossible switch case in unicode_hash");
11158 l = PyUnicode_4BYTE_DATA(self);
11159 HASH(l);
11160 break;
11161 }
11162 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011163 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11164 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165
Guido van Rossumc2504932007-09-18 19:42:40 +000011166 if (x == -1)
11167 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011169 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011173PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011174 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011176Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177
11178static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011181 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011182 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011183 Py_ssize_t start;
11184 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185
Jesus Ceaac451502011-04-20 17:09:23 +020011186 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11187 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189
Christian Heimesd47a0452013-06-29 21:21:37 +020011190 if (PyUnicode_READY(self) == -1) {
11191 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011193 }
11194 if (PyUnicode_READY(substring) == -1) {
11195 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198
Victor Stinner7931d9a2011-11-04 00:22:48 +010011199 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200
11201 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203 if (result == -2)
11204 return NULL;
11205
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 if (result < 0) {
11207 PyErr_SetString(PyExc_ValueError, "substring not found");
11208 return NULL;
11209 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011210
Christian Heimes217cfd12007-12-02 14:31:20 +000011211 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212}
11213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011214PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011215 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011217Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011218at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
11220static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011221unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 Py_ssize_t i, length;
11224 int kind;
11225 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226 int cased;
11227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 if (PyUnicode_READY(self) == -1)
11229 return NULL;
11230 length = PyUnicode_GET_LENGTH(self);
11231 kind = PyUnicode_KIND(self);
11232 data = PyUnicode_DATA(self);
11233
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235 if (length == 1)
11236 return PyBool_FromLong(
11237 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011239 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011242
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011244 for (i = 0; i < length; i++) {
11245 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011246
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11248 return PyBool_FromLong(0);
11249 else if (!cased && Py_UNICODE_ISLOWER(ch))
11250 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011252 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253}
11254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011255PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011256 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011258Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011259at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260
11261static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011262unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 Py_ssize_t i, length;
11265 int kind;
11266 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267 int cased;
11268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 if (PyUnicode_READY(self) == -1)
11270 return NULL;
11271 length = PyUnicode_GET_LENGTH(self);
11272 kind = PyUnicode_KIND(self);
11273 data = PyUnicode_DATA(self);
11274
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 if (length == 1)
11277 return PyBool_FromLong(
11278 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011280 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011281 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011283
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285 for (i = 0; i < length; i++) {
11286 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011287
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11289 return PyBool_FromLong(0);
11290 else if (!cased && Py_UNICODE_ISUPPER(ch))
11291 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011293 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294}
11295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011296PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011297 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011299Return True if S is a titlecased string and there is at least one\n\
11300character in S, i.e. upper- and titlecase characters may only\n\
11301follow uncased characters and lowercase characters only cased ones.\n\
11302Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303
11304static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011305unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 Py_ssize_t i, length;
11308 int kind;
11309 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 int cased, previous_is_cased;
11311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 if (PyUnicode_READY(self) == -1)
11313 return NULL;
11314 length = PyUnicode_GET_LENGTH(self);
11315 kind = PyUnicode_KIND(self);
11316 data = PyUnicode_DATA(self);
11317
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 if (length == 1) {
11320 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11321 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11322 (Py_UNICODE_ISUPPER(ch) != 0));
11323 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011325 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011327 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011328
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329 cased = 0;
11330 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 for (i = 0; i < length; i++) {
11332 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011333
Benjamin Peterson29060642009-01-31 22:14:21 +000011334 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11335 if (previous_is_cased)
11336 return PyBool_FromLong(0);
11337 previous_is_cased = 1;
11338 cased = 1;
11339 }
11340 else if (Py_UNICODE_ISLOWER(ch)) {
11341 if (!previous_is_cased)
11342 return PyBool_FromLong(0);
11343 previous_is_cased = 1;
11344 cased = 1;
11345 }
11346 else
11347 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011349 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350}
11351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011352PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011353 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011355Return True if all characters in S are whitespace\n\
11356and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357
11358static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011359unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 Py_ssize_t i, length;
11362 int kind;
11363 void *data;
11364
11365 if (PyUnicode_READY(self) == -1)
11366 return NULL;
11367 length = PyUnicode_GET_LENGTH(self);
11368 kind = PyUnicode_KIND(self);
11369 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 if (length == 1)
11373 return PyBool_FromLong(
11374 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011376 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 for (i = 0; i < length; i++) {
11381 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011382 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011383 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011385 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386}
11387
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011388PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011389 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011390\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011391Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011392and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011393
11394static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011395unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 Py_ssize_t i, length;
11398 int kind;
11399 void *data;
11400
11401 if (PyUnicode_READY(self) == -1)
11402 return NULL;
11403 length = PyUnicode_GET_LENGTH(self);
11404 kind = PyUnicode_KIND(self);
11405 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011406
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011407 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408 if (length == 1)
11409 return PyBool_FromLong(
11410 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011411
11412 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011413 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 for (i = 0; i < length; i++) {
11417 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011418 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011419 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011420 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011421}
11422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011423PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011424 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011425\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011426Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011427and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011428
11429static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011430unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 int kind;
11433 void *data;
11434 Py_ssize_t len, i;
11435
11436 if (PyUnicode_READY(self) == -1)
11437 return NULL;
11438
11439 kind = PyUnicode_KIND(self);
11440 data = PyUnicode_DATA(self);
11441 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011442
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011443 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (len == 1) {
11445 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11446 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11447 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011448
11449 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011451 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 for (i = 0; i < len; i++) {
11454 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011455 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011457 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011458 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011459}
11460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011464Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011465False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466
11467static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011468unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 Py_ssize_t i, length;
11471 int kind;
11472 void *data;
11473
11474 if (PyUnicode_READY(self) == -1)
11475 return NULL;
11476 length = PyUnicode_GET_LENGTH(self);
11477 kind = PyUnicode_KIND(self);
11478 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 if (length == 1)
11482 return PyBool_FromLong(
11483 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011485 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 for (i = 0; i < length; i++) {
11490 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011491 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011493 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494}
11495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011499Return True if all characters in S are digits\n\
11500and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501
11502static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011503unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 Py_ssize_t i, length;
11506 int kind;
11507 void *data;
11508
11509 if (PyUnicode_READY(self) == -1)
11510 return NULL;
11511 length = PyUnicode_GET_LENGTH(self);
11512 kind = PyUnicode_KIND(self);
11513 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 if (length == 1) {
11517 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11518 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11519 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011521 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011523 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 for (i = 0; i < length; i++) {
11526 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011529 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530}
11531
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011532PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011535Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011536False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537
11538static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011539unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 Py_ssize_t i, length;
11542 int kind;
11543 void *data;
11544
11545 if (PyUnicode_READY(self) == -1)
11546 return NULL;
11547 length = PyUnicode_GET_LENGTH(self);
11548 kind = PyUnicode_KIND(self);
11549 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 if (length == 1)
11553 return PyBool_FromLong(
11554 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011556 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 for (i = 0; i < length; i++) {
11561 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011564 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565}
11566
Martin v. Löwis47383402007-08-15 07:32:56 +000011567int
11568PyUnicode_IsIdentifier(PyObject *self)
11569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 int kind;
11571 void *data;
11572 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011573 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (PyUnicode_READY(self) == -1) {
11576 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 }
11579
11580 /* Special case for empty strings */
11581 if (PyUnicode_GET_LENGTH(self) == 0)
11582 return 0;
11583 kind = PyUnicode_KIND(self);
11584 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011585
11586 /* PEP 3131 says that the first character must be in
11587 XID_Start and subsequent characters in XID_Continue,
11588 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011589 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011590 letters, digits, underscore). However, given the current
11591 definition of XID_Start and XID_Continue, it is sufficient
11592 to check just for these, except that _ must be allowed
11593 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011595 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011596 return 0;
11597
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011598 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011599 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011600 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011601 return 1;
11602}
11603
11604PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011605 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011606\n\
11607Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011608to the language definition.\n\
11609\n\
11610Use keyword.iskeyword() to test for reserved identifiers\n\
11611such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011612
11613static PyObject*
11614unicode_isidentifier(PyObject *self)
11615{
11616 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11617}
11618
Georg Brandl559e5d72008-06-11 18:37:52 +000011619PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011621\n\
11622Return True if all characters in S are considered\n\
11623printable in repr() or S is empty, False otherwise.");
11624
11625static PyObject*
11626unicode_isprintable(PyObject *self)
11627{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 Py_ssize_t i, length;
11629 int kind;
11630 void *data;
11631
11632 if (PyUnicode_READY(self) == -1)
11633 return NULL;
11634 length = PyUnicode_GET_LENGTH(self);
11635 kind = PyUnicode_KIND(self);
11636 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011637
11638 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 if (length == 1)
11640 return PyBool_FromLong(
11641 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 for (i = 0; i < length; i++) {
11644 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011645 Py_RETURN_FALSE;
11646 }
11647 }
11648 Py_RETURN_TRUE;
11649}
11650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011651PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011652 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011653\n\
11654Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011655iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656
11657static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011658unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011660 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661}
11662
Martin v. Löwis18e16552006-02-15 17:27:45 +000011663static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011664unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666 if (PyUnicode_READY(self) == -1)
11667 return -1;
11668 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669}
11670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011671PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011674Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011675done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676
11677static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011678unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011680 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 Py_UCS4 fillchar = ' ';
11682
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011683 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684 return NULL;
11685
Benjamin Petersonbac79492012-01-14 13:34:47 -050011686 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011687 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688
Victor Stinnerc4b49542011-12-11 22:44:26 +010011689 if (PyUnicode_GET_LENGTH(self) >= width)
11690 return unicode_result_unchanged(self);
11691
11692 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693}
11694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011695PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011698Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699
11700static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011701unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011703 if (PyUnicode_READY(self) == -1)
11704 return NULL;
11705 if (PyUnicode_IS_ASCII(self))
11706 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011707 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708}
11709
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710#define LEFTSTRIP 0
11711#define RIGHTSTRIP 1
11712#define BOTHSTRIP 2
11713
11714/* Arrays indexed by above */
11715static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11716
11717#define STRIPNAME(i) (stripformat[i]+3)
11718
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011719/* externally visible for str.strip(unicode) */
11720PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011721_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 void *data;
11724 int kind;
11725 Py_ssize_t i, j, len;
11726 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011727 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11730 return NULL;
11731
11732 kind = PyUnicode_KIND(self);
11733 data = PyUnicode_DATA(self);
11734 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011735 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11737 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011738 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011739
Benjamin Peterson14339b62009-01-31 16:36:08 +000011740 i = 0;
11741 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011742 while (i < len) {
11743 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11744 if (!BLOOM(sepmask, ch))
11745 break;
11746 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11747 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011748 i++;
11749 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011751
Benjamin Peterson14339b62009-01-31 16:36:08 +000011752 j = len;
11753 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011754 j--;
11755 while (j >= i) {
11756 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11757 if (!BLOOM(sepmask, ch))
11758 break;
11759 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11760 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011761 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011762 }
11763
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011765 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766
Victor Stinner7931d9a2011-11-04 00:22:48 +010011767 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768}
11769
11770PyObject*
11771PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11772{
11773 unsigned char *data;
11774 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011775 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776
Victor Stinnerde636f32011-10-01 03:55:54 +020011777 if (PyUnicode_READY(self) == -1)
11778 return NULL;
11779
Victor Stinner684d5fd2012-05-03 02:32:34 +020011780 length = PyUnicode_GET_LENGTH(self);
11781 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011782
Victor Stinner684d5fd2012-05-03 02:32:34 +020011783 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011784 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785
Victor Stinnerde636f32011-10-01 03:55:54 +020011786 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011787 PyErr_SetString(PyExc_IndexError, "string index out of range");
11788 return NULL;
11789 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011790 if (start >= length || end < start)
11791 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011792
Victor Stinner684d5fd2012-05-03 02:32:34 +020011793 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011794 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011795 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011796 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011797 }
11798 else {
11799 kind = PyUnicode_KIND(self);
11800 data = PyUnicode_1BYTE_DATA(self);
11801 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011802 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011803 length);
11804 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806
11807static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011808do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 Py_ssize_t len, i, j;
11811
11812 if (PyUnicode_READY(self) == -1)
11813 return NULL;
11814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011816
Victor Stinnercc7af722013-04-09 22:39:24 +020011817 if (PyUnicode_IS_ASCII(self)) {
11818 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
11819
11820 i = 0;
11821 if (striptype != RIGHTSTRIP) {
11822 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020011823 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020011824 if (!_Py_ascii_whitespace[ch])
11825 break;
11826 i++;
11827 }
11828 }
11829
11830 j = len;
11831 if (striptype != LEFTSTRIP) {
11832 j--;
11833 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020011834 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020011835 if (!_Py_ascii_whitespace[ch])
11836 break;
11837 j--;
11838 }
11839 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011840 }
11841 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011842 else {
11843 int kind = PyUnicode_KIND(self);
11844 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011845
Victor Stinnercc7af722013-04-09 22:39:24 +020011846 i = 0;
11847 if (striptype != RIGHTSTRIP) {
11848 while (i < len) {
11849 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11850 if (!Py_UNICODE_ISSPACE(ch))
11851 break;
11852 i++;
11853 }
Victor Stinner9c79e412013-04-09 22:21:08 +020011854 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011855
11856 j = len;
11857 if (striptype != LEFTSTRIP) {
11858 j--;
11859 while (j >= i) {
11860 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11861 if (!Py_UNICODE_ISSPACE(ch))
11862 break;
11863 j--;
11864 }
11865 j++;
11866 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011867 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011868
Victor Stinner7931d9a2011-11-04 00:22:48 +010011869 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870}
11871
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011872
11873static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011874do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011875{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011876 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011877
Serhiy Storchakac6792272013-10-19 21:03:34 +030011878 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011879 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011880
Benjamin Peterson14339b62009-01-31 16:36:08 +000011881 if (sep != NULL && sep != Py_None) {
11882 if (PyUnicode_Check(sep))
11883 return _PyUnicode_XStrip(self, striptype, sep);
11884 else {
11885 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011886 "%s arg must be None or str",
11887 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011888 return NULL;
11889 }
11890 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011891
Benjamin Peterson14339b62009-01-31 16:36:08 +000011892 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011893}
11894
11895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011896PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011898\n\
11899Return a copy of the string S with leading and trailing\n\
11900whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011901If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011902
11903static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011904unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011905{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011906 if (PyTuple_GET_SIZE(args) == 0)
11907 return do_strip(self, BOTHSTRIP); /* Common case */
11908 else
11909 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011910}
11911
11912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011913PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011915\n\
11916Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011917If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011918
11919static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011920unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011921{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011922 if (PyTuple_GET_SIZE(args) == 0)
11923 return do_strip(self, LEFTSTRIP); /* Common case */
11924 else
11925 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011926}
11927
11928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011929PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011931\n\
11932Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011933If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934
11935static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011936unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011937{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011938 if (PyTuple_GET_SIZE(args) == 0)
11939 return do_strip(self, RIGHTSTRIP); /* Common case */
11940 else
11941 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011942}
11943
11944
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011946unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011948 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950
Serhiy Storchaka05997252013-01-26 12:14:02 +020011951 if (len < 1)
11952 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953
Victor Stinnerc4b49542011-12-11 22:44:26 +010011954 /* no repeat, return original string */
11955 if (len == 1)
11956 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011957
Benjamin Petersonbac79492012-01-14 13:34:47 -050011958 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 return NULL;
11960
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011961 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011962 PyErr_SetString(PyExc_OverflowError,
11963 "repeated string is too long");
11964 return NULL;
11965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011967
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011968 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969 if (!u)
11970 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011971 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 if (PyUnicode_GET_LENGTH(str) == 1) {
11974 const int kind = PyUnicode_KIND(str);
11975 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011976 if (kind == PyUnicode_1BYTE_KIND) {
11977 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011978 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011979 }
11980 else if (kind == PyUnicode_2BYTE_KIND) {
11981 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011982 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011983 ucs2[n] = fill_char;
11984 } else {
11985 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11986 assert(kind == PyUnicode_4BYTE_KIND);
11987 for (n = 0; n < len; ++n)
11988 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 }
11991 else {
11992 /* number of characters copied this far */
11993 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011994 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 char *to = (char *) PyUnicode_DATA(u);
11996 Py_MEMCPY(to, PyUnicode_DATA(str),
11997 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011998 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 n = (done <= nchars-done) ? done : nchars-done;
12000 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012001 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003 }
12004
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012005 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012006 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007}
12008
Alexander Belopolsky40018472011-02-26 01:02:56 +000012009PyObject *
12010PyUnicode_Replace(PyObject *obj,
12011 PyObject *subobj,
12012 PyObject *replobj,
12013 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012014{
12015 PyObject *self;
12016 PyObject *str1;
12017 PyObject *str2;
12018 PyObject *result;
12019
12020 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012021 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012022 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012024 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012025 Py_DECREF(self);
12026 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027 }
12028 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012029 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012030 Py_DECREF(self);
12031 Py_DECREF(str1);
12032 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012034 if (PyUnicode_READY(self) == -1 ||
12035 PyUnicode_READY(str1) == -1 ||
12036 PyUnicode_READY(str2) == -1)
12037 result = NULL;
12038 else
12039 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040 Py_DECREF(self);
12041 Py_DECREF(str1);
12042 Py_DECREF(str2);
12043 return result;
12044}
12045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012046PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012047 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012048\n\
12049Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012050old replaced by new. If the optional argument count is\n\
12051given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052
12053static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056 PyObject *str1;
12057 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012058 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059 PyObject *result;
12060
Martin v. Löwis18e16552006-02-15 17:27:45 +000012061 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012063 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012064 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012065 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012066 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 return NULL;
12068 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012069 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012070 Py_DECREF(str1);
12071 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012072 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012073 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12074 result = NULL;
12075 else
12076 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077
12078 Py_DECREF(str1);
12079 Py_DECREF(str2);
12080 return result;
12081}
12082
Alexander Belopolsky40018472011-02-26 01:02:56 +000012083static PyObject *
12084unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012085{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012086 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 Py_ssize_t isize;
12088 Py_ssize_t osize, squote, dquote, i, o;
12089 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012090 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012094 return NULL;
12095
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 isize = PyUnicode_GET_LENGTH(unicode);
12097 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012098
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 /* Compute length of output, quote characters, and
12100 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012101 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 max = 127;
12103 squote = dquote = 0;
12104 ikind = PyUnicode_KIND(unicode);
12105 for (i = 0; i < isize; i++) {
12106 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12107 switch (ch) {
12108 case '\'': squote++; osize++; break;
12109 case '"': dquote++; osize++; break;
12110 case '\\': case '\t': case '\r': case '\n':
12111 osize += 2; break;
12112 default:
12113 /* Fast-path ASCII */
12114 if (ch < ' ' || ch == 0x7f)
12115 osize += 4; /* \xHH */
12116 else if (ch < 0x7f)
12117 osize++;
12118 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12119 osize++;
12120 max = ch > max ? ch : max;
12121 }
12122 else if (ch < 0x100)
12123 osize += 4; /* \xHH */
12124 else if (ch < 0x10000)
12125 osize += 6; /* \uHHHH */
12126 else
12127 osize += 10; /* \uHHHHHHHH */
12128 }
12129 }
12130
12131 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012132 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012134 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 if (dquote)
12136 /* Both squote and dquote present. Use squote,
12137 and escape them */
12138 osize += squote;
12139 else
12140 quote = '"';
12141 }
Victor Stinner55c08782013-04-14 18:45:39 +020012142 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143
12144 repr = PyUnicode_New(osize, max);
12145 if (repr == NULL)
12146 return NULL;
12147 okind = PyUnicode_KIND(repr);
12148 odata = PyUnicode_DATA(repr);
12149
12150 PyUnicode_WRITE(okind, odata, 0, quote);
12151 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012152 if (unchanged) {
12153 _PyUnicode_FastCopyCharacters(repr, 1,
12154 unicode, 0,
12155 isize);
12156 }
12157 else {
12158 for (i = 0, o = 1; i < isize; i++) {
12159 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160
Victor Stinner55c08782013-04-14 18:45:39 +020012161 /* Escape quotes and backslashes */
12162 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012163 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012165 continue;
12166 }
12167
12168 /* Map special whitespace to '\t', \n', '\r' */
12169 if (ch == '\t') {
12170 PyUnicode_WRITE(okind, odata, o++, '\\');
12171 PyUnicode_WRITE(okind, odata, o++, 't');
12172 }
12173 else if (ch == '\n') {
12174 PyUnicode_WRITE(okind, odata, o++, '\\');
12175 PyUnicode_WRITE(okind, odata, o++, 'n');
12176 }
12177 else if (ch == '\r') {
12178 PyUnicode_WRITE(okind, odata, o++, '\\');
12179 PyUnicode_WRITE(okind, odata, o++, 'r');
12180 }
12181
12182 /* Map non-printable US ASCII to '\xhh' */
12183 else if (ch < ' ' || ch == 0x7F) {
12184 PyUnicode_WRITE(okind, odata, o++, '\\');
12185 PyUnicode_WRITE(okind, odata, o++, 'x');
12186 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12187 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12188 }
12189
12190 /* Copy ASCII characters as-is */
12191 else if (ch < 0x7F) {
12192 PyUnicode_WRITE(okind, odata, o++, ch);
12193 }
12194
12195 /* Non-ASCII characters */
12196 else {
12197 /* Map Unicode whitespace and control characters
12198 (categories Z* and C* except ASCII space)
12199 */
12200 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12201 PyUnicode_WRITE(okind, odata, o++, '\\');
12202 /* Map 8-bit characters to '\xhh' */
12203 if (ch <= 0xff) {
12204 PyUnicode_WRITE(okind, odata, o++, 'x');
12205 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12206 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12207 }
12208 /* Map 16-bit characters to '\uxxxx' */
12209 else if (ch <= 0xffff) {
12210 PyUnicode_WRITE(okind, odata, o++, 'u');
12211 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12212 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12213 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12214 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12215 }
12216 /* Map 21-bit characters to '\U00xxxxxx' */
12217 else {
12218 PyUnicode_WRITE(okind, odata, o++, 'U');
12219 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12220 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12221 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12222 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12223 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12224 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12225 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12226 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12227 }
12228 }
12229 /* Copy characters as-is */
12230 else {
12231 PyUnicode_WRITE(okind, odata, o++, ch);
12232 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012233 }
12234 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012235 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012237 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012238 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239}
12240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012241PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012242 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243\n\
12244Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012245such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246arguments start and end are interpreted as in slice notation.\n\
12247\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012248Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249
12250static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012253 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012254 Py_ssize_t start;
12255 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012256 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
Jesus Ceaac451502011-04-20 17:09:23 +020012258 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12259 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012260 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261
Christian Heimesea71a522013-06-29 21:17:34 +020012262 if (PyUnicode_READY(self) == -1) {
12263 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012265 }
12266 if (PyUnicode_READY(substring) == -1) {
12267 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270
Victor Stinner7931d9a2011-11-04 00:22:48 +010012271 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272
12273 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012275 if (result == -2)
12276 return NULL;
12277
Christian Heimes217cfd12007-12-02 14:31:20 +000012278 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279}
12280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012281PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012284Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285
12286static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012289 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012290 Py_ssize_t start;
12291 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293
Jesus Ceaac451502011-04-20 17:09:23 +020012294 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12295 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012296 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297
Christian Heimesea71a522013-06-29 21:17:34 +020012298 if (PyUnicode_READY(self) == -1) {
12299 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012301 }
12302 if (PyUnicode_READY(substring) == -1) {
12303 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012304 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306
Victor Stinner7931d9a2011-11-04 00:22:48 +010012307 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308
12309 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 if (result == -2)
12312 return NULL;
12313
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314 if (result < 0) {
12315 PyErr_SetString(PyExc_ValueError, "substring not found");
12316 return NULL;
12317 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318
Christian Heimes217cfd12007-12-02 14:31:20 +000012319 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320}
12321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012322PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012323 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012325Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012326done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327
12328static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012329unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012330{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012331 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 Py_UCS4 fillchar = ' ';
12333
Victor Stinnere9a29352011-10-01 02:14:59 +020012334 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012335 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012336
Benjamin Petersonbac79492012-01-14 13:34:47 -050012337 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338 return NULL;
12339
Victor Stinnerc4b49542011-12-11 22:44:26 +010012340 if (PyUnicode_GET_LENGTH(self) >= width)
12341 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012342
Victor Stinnerc4b49542011-12-11 22:44:26 +010012343 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344}
12345
Alexander Belopolsky40018472011-02-26 01:02:56 +000012346PyObject *
12347PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012348{
12349 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012350
Guido van Rossumd57fd912000-03-10 22:53:23 +000012351 s = PyUnicode_FromObject(s);
12352 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012353 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012354 if (sep != NULL) {
12355 sep = PyUnicode_FromObject(sep);
12356 if (sep == NULL) {
12357 Py_DECREF(s);
12358 return NULL;
12359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360 }
12361
Victor Stinner9310abb2011-10-05 00:59:23 +020012362 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363
12364 Py_DECREF(s);
12365 Py_XDECREF(sep);
12366 return result;
12367}
12368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012369PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012370 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371\n\
12372Return a list of the words in S, using sep as the\n\
12373delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012374splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012375whitespace string is a separator and empty strings are\n\
12376removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377
12378static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012379unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012381 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012383 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012384
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012385 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12386 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387 return NULL;
12388
12389 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012390 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012392 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012394 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395}
12396
Thomas Wouters477c8d52006-05-27 19:21:47 +000012397PyObject *
12398PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12399{
12400 PyObject* str_obj;
12401 PyObject* sep_obj;
12402 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 int kind1, kind2, kind;
12404 void *buf1 = NULL, *buf2 = NULL;
12405 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406
12407 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012408 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012409 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012411 if (!sep_obj) {
12412 Py_DECREF(str_obj);
12413 return NULL;
12414 }
12415 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12416 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012417 Py_DECREF(str_obj);
12418 return NULL;
12419 }
12420
Victor Stinner14f8f022011-10-05 20:58:25 +020012421 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012423 kind = Py_MAX(kind1, kind2);
12424 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012426 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 if (!buf1)
12428 goto onError;
12429 buf2 = PyUnicode_DATA(sep_obj);
12430 if (kind2 != kind)
12431 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12432 if (!buf2)
12433 goto onError;
12434 len1 = PyUnicode_GET_LENGTH(str_obj);
12435 len2 = PyUnicode_GET_LENGTH(sep_obj);
12436
Benjamin Petersonead6b532011-12-20 17:23:42 -060012437 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012438 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012439 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12440 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12441 else
12442 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 break;
12444 case PyUnicode_2BYTE_KIND:
12445 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12446 break;
12447 case PyUnicode_4BYTE_KIND:
12448 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12449 break;
12450 default:
12451 assert(0);
12452 out = 0;
12453 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454
12455 Py_DECREF(sep_obj);
12456 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 if (kind1 != kind)
12458 PyMem_Free(buf1);
12459 if (kind2 != kind)
12460 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012461
12462 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012463 onError:
12464 Py_DECREF(sep_obj);
12465 Py_DECREF(str_obj);
12466 if (kind1 != kind && buf1)
12467 PyMem_Free(buf1);
12468 if (kind2 != kind && buf2)
12469 PyMem_Free(buf2);
12470 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012471}
12472
12473
12474PyObject *
12475PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12476{
12477 PyObject* str_obj;
12478 PyObject* sep_obj;
12479 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 int kind1, kind2, kind;
12481 void *buf1 = NULL, *buf2 = NULL;
12482 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012483
12484 str_obj = PyUnicode_FromObject(str_in);
12485 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012486 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012487 sep_obj = PyUnicode_FromObject(sep_in);
12488 if (!sep_obj) {
12489 Py_DECREF(str_obj);
12490 return NULL;
12491 }
12492
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012493 kind1 = PyUnicode_KIND(str_in);
12494 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012495 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496 buf1 = PyUnicode_DATA(str_in);
12497 if (kind1 != kind)
12498 buf1 = _PyUnicode_AsKind(str_in, kind);
12499 if (!buf1)
12500 goto onError;
12501 buf2 = PyUnicode_DATA(sep_obj);
12502 if (kind2 != kind)
12503 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12504 if (!buf2)
12505 goto onError;
12506 len1 = PyUnicode_GET_LENGTH(str_obj);
12507 len2 = PyUnicode_GET_LENGTH(sep_obj);
12508
Benjamin Petersonead6b532011-12-20 17:23:42 -060012509 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012510 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012511 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12512 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12513 else
12514 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 break;
12516 case PyUnicode_2BYTE_KIND:
12517 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12518 break;
12519 case PyUnicode_4BYTE_KIND:
12520 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12521 break;
12522 default:
12523 assert(0);
12524 out = 0;
12525 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526
12527 Py_DECREF(sep_obj);
12528 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 if (kind1 != kind)
12530 PyMem_Free(buf1);
12531 if (kind2 != kind)
12532 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012533
12534 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 onError:
12536 Py_DECREF(sep_obj);
12537 Py_DECREF(str_obj);
12538 if (kind1 != kind && buf1)
12539 PyMem_Free(buf1);
12540 if (kind2 != kind && buf2)
12541 PyMem_Free(buf2);
12542 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012543}
12544
12545PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012546 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012547\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012548Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012550found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012551
12552static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012553unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012554{
Victor Stinner9310abb2011-10-05 00:59:23 +020012555 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556}
12557
12558PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012559 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012560\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012561Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012562the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012563separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012564
12565static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012566unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012567{
Victor Stinner9310abb2011-10-05 00:59:23 +020012568 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012569}
12570
Alexander Belopolsky40018472011-02-26 01:02:56 +000012571PyObject *
12572PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012573{
12574 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012575
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012576 s = PyUnicode_FromObject(s);
12577 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012578 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012579 if (sep != NULL) {
12580 sep = PyUnicode_FromObject(sep);
12581 if (sep == NULL) {
12582 Py_DECREF(s);
12583 return NULL;
12584 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012585 }
12586
Victor Stinner9310abb2011-10-05 00:59:23 +020012587 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012588
12589 Py_DECREF(s);
12590 Py_XDECREF(sep);
12591 return result;
12592}
12593
12594PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012595 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012596\n\
12597Return a list of the words in S, using sep as the\n\
12598delimiter string, starting at the end of the string and\n\
12599working to the front. If maxsplit is given, at most maxsplit\n\
12600splits are done. If sep is not specified, any whitespace string\n\
12601is a separator.");
12602
12603static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012604unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012605{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012606 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012607 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012608 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012609
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012610 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12611 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012612 return NULL;
12613
12614 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012615 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012616 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012617 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012618 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012619 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012620}
12621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012622PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012623 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624\n\
12625Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012626Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012627is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628
12629static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012630unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012632 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012633 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012635 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12636 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637 return NULL;
12638
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012639 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640}
12641
12642static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012643PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012645 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646}
12647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012648PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012649 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650\n\
12651Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012652and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653
12654static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012655unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012657 if (PyUnicode_READY(self) == -1)
12658 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012659 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660}
12661
Larry Hastings31826802013-10-19 00:09:25 -070012662/*[clinic]
12663module str
Georg Brandlceee0772007-11-27 23:48:05 +000012664
Larry Hastings31826802013-10-19 00:09:25 -070012665@staticmethod
12666str.maketrans as unicode_maketrans
12667
12668 x: object
12669
12670 y: unicode=NULL
12671
12672 z: unicode=NULL
12673
12674 /
12675
12676Return a translation table usable for str.translate().
12677
12678If there is only one argument, it must be a dictionary mapping Unicode
12679ordinals (integers) or characters to Unicode ordinals, strings or None.
12680Character keys will be then converted to ordinals.
12681If there are two arguments, they must be strings of equal length, and
12682in the resulting dictionary, each character in x will be mapped to the
12683character at the same position in y. If there is a third argument, it
12684must be a string, whose characters will be mapped to None in the result.
12685[clinic]*/
12686
12687PyDoc_STRVAR(unicode_maketrans__doc__,
12688"Return a translation table usable for str.translate().\n"
12689"\n"
12690"str.maketrans(x, y=None, z=None)\n"
12691"\n"
12692"If there is only one argument, it must be a dictionary mapping Unicode\n"
12693"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12694"Character keys will be then converted to ordinals.\n"
12695"If there are two arguments, they must be strings of equal length, and\n"
12696"in the resulting dictionary, each character in x will be mapped to the\n"
12697"character at the same position in y. If there is a third argument, it\n"
12698"must be a string, whose characters will be mapped to None in the result.");
12699
12700#define UNICODE_MAKETRANS_METHODDEF \
12701 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12702
12703static PyObject *
12704unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
12705
12706static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012707unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012708{
Larry Hastings31826802013-10-19 00:09:25 -070012709 PyObject *return_value = NULL;
12710 PyObject *x;
12711 PyObject *y = NULL;
12712 PyObject *z = NULL;
12713
12714 if (!PyArg_ParseTuple(args,
12715 "O|UU:maketrans",
12716 &x, &y, &z))
12717 goto exit;
12718 return_value = unicode_maketrans_impl(x, y, z);
12719
12720exit:
12721 return return_value;
12722}
12723
12724static PyObject *
12725unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
12726/*[clinic checksum: 137db9c3199e7906b7967009f511c24fa3235b5f]*/
12727{
Georg Brandlceee0772007-11-27 23:48:05 +000012728 PyObject *new = NULL, *key, *value;
12729 Py_ssize_t i = 0;
12730 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012731
Georg Brandlceee0772007-11-27 23:48:05 +000012732 new = PyDict_New();
12733 if (!new)
12734 return NULL;
12735 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 int x_kind, y_kind, z_kind;
12737 void *x_data, *y_data, *z_data;
12738
Georg Brandlceee0772007-11-27 23:48:05 +000012739 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012740 if (!PyUnicode_Check(x)) {
12741 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12742 "be a string if there is a second argument");
12743 goto err;
12744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012746 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12747 "arguments must have equal length");
12748 goto err;
12749 }
12750 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012751 x_kind = PyUnicode_KIND(x);
12752 y_kind = PyUnicode_KIND(y);
12753 x_data = PyUnicode_DATA(x);
12754 y_data = PyUnicode_DATA(y);
12755 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12756 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012757 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012758 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012759 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012760 if (!value) {
12761 Py_DECREF(key);
12762 goto err;
12763 }
Georg Brandlceee0772007-11-27 23:48:05 +000012764 res = PyDict_SetItem(new, key, value);
12765 Py_DECREF(key);
12766 Py_DECREF(value);
12767 if (res < 0)
12768 goto err;
12769 }
12770 /* create entries for deleting chars in z */
12771 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772 z_kind = PyUnicode_KIND(z);
12773 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012774 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012775 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012776 if (!key)
12777 goto err;
12778 res = PyDict_SetItem(new, key, Py_None);
12779 Py_DECREF(key);
12780 if (res < 0)
12781 goto err;
12782 }
12783 }
12784 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012785 int kind;
12786 void *data;
12787
Georg Brandlceee0772007-11-27 23:48:05 +000012788 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012789 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012790 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12791 "to maketrans it must be a dict");
12792 goto err;
12793 }
12794 /* copy entries into the new dict, converting string keys to int keys */
12795 while (PyDict_Next(x, &i, &key, &value)) {
12796 if (PyUnicode_Check(key)) {
12797 /* convert string keys to integer keys */
12798 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012799 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012800 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12801 "table must be of length 1");
12802 goto err;
12803 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012804 kind = PyUnicode_KIND(key);
12805 data = PyUnicode_DATA(key);
12806 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012807 if (!newkey)
12808 goto err;
12809 res = PyDict_SetItem(new, newkey, value);
12810 Py_DECREF(newkey);
12811 if (res < 0)
12812 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012813 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012814 /* just keep integer keys */
12815 if (PyDict_SetItem(new, key, value) < 0)
12816 goto err;
12817 } else {
12818 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12819 "be strings or integers");
12820 goto err;
12821 }
12822 }
12823 }
12824 return new;
12825 err:
12826 Py_DECREF(new);
12827 return NULL;
12828}
12829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012830PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012831 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832\n\
12833Return a copy of the string S, where all characters have been mapped\n\
12834through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012835Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012836Unmapped characters are left untouched. Characters mapped to None\n\
12837are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838
12839static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012840unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843}
12844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012845PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012846 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012848Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849
12850static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012851unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012853 if (PyUnicode_READY(self) == -1)
12854 return NULL;
12855 if (PyUnicode_IS_ASCII(self))
12856 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012857 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012858}
12859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012860PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012863Pad a numeric string S with zeros on the left, to fill a field\n\
12864of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865
12866static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012867unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012868{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012869 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012870 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012871 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012872 int kind;
12873 void *data;
12874 Py_UCS4 chr;
12875
Martin v. Löwis18e16552006-02-15 17:27:45 +000012876 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877 return NULL;
12878
Benjamin Petersonbac79492012-01-14 13:34:47 -050012879 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012880 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881
Victor Stinnerc4b49542011-12-11 22:44:26 +010012882 if (PyUnicode_GET_LENGTH(self) >= width)
12883 return unicode_result_unchanged(self);
12884
12885 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886
12887 u = pad(self, fill, 0, '0');
12888
Walter Dörwald068325e2002-04-15 13:36:47 +000012889 if (u == NULL)
12890 return NULL;
12891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012892 kind = PyUnicode_KIND(u);
12893 data = PyUnicode_DATA(u);
12894 chr = PyUnicode_READ(kind, data, fill);
12895
12896 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 PyUnicode_WRITE(kind, data, 0, chr);
12899 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900 }
12901
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012902 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012903 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012904}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905
12906#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012907static PyObject *
12908unicode__decimal2ascii(PyObject *self)
12909{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012910 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012911}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012912#endif
12913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012914PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012916\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012917Return True if S starts with the specified prefix, False otherwise.\n\
12918With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012919With optional end, stop comparing S at that position.\n\
12920prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012921
12922static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012923unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012924 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012925{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012926 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012927 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012928 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012929 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012930 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012931
Jesus Ceaac451502011-04-20 17:09:23 +020012932 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012933 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012934 if (PyTuple_Check(subobj)) {
12935 Py_ssize_t i;
12936 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012937 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012938 if (substring == NULL)
12939 return NULL;
12940 result = tailmatch(self, substring, start, end, -1);
12941 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012942 if (result == -1)
12943 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012944 if (result) {
12945 Py_RETURN_TRUE;
12946 }
12947 }
12948 /* nothing matched */
12949 Py_RETURN_FALSE;
12950 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012951 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012952 if (substring == NULL) {
12953 if (PyErr_ExceptionMatches(PyExc_TypeError))
12954 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12955 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012956 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012957 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012958 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012959 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012960 if (result == -1)
12961 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012962 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012963}
12964
12965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012966PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012967 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012968\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012969Return True if S ends with the specified suffix, False otherwise.\n\
12970With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012971With optional end, stop comparing S at that position.\n\
12972suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012973
12974static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012975unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012976 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012977{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012978 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012979 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012980 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012981 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012982 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012983
Jesus Ceaac451502011-04-20 17:09:23 +020012984 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012985 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012986 if (PyTuple_Check(subobj)) {
12987 Py_ssize_t i;
12988 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012989 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012990 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012991 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012992 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012993 result = tailmatch(self, substring, start, end, +1);
12994 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012995 if (result == -1)
12996 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012997 if (result) {
12998 Py_RETURN_TRUE;
12999 }
13000 }
13001 Py_RETURN_FALSE;
13002 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013003 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013004 if (substring == NULL) {
13005 if (PyErr_ExceptionMatches(PyExc_TypeError))
13006 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13007 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013008 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013009 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013010 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013011 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013012 if (result == -1)
13013 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013014 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015}
13016
Victor Stinner202fdca2012-05-07 12:47:02 +020013017Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013018_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013019{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013020 if (!writer->readonly)
13021 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13022 else {
13023 /* Copy-on-write mode: set buffer size to 0 so
13024 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13025 * next write. */
13026 writer->size = 0;
13027 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013028 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13029 writer->data = PyUnicode_DATA(writer->buffer);
13030 writer->kind = PyUnicode_KIND(writer->buffer);
13031}
13032
Victor Stinnerd3f08822012-05-29 12:57:52 +020013033void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013034_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013035{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013036 memset(writer, 0, sizeof(*writer));
13037#ifdef Py_DEBUG
13038 writer->kind = 5; /* invalid kind */
13039#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013040 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013041}
13042
Victor Stinnerd3f08822012-05-29 12:57:52 +020013043int
13044_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13045 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013046{
13047 Py_ssize_t newlen;
13048 PyObject *newbuffer;
13049
Victor Stinnerd3f08822012-05-29 12:57:52 +020013050 assert(length > 0);
13051
Victor Stinner202fdca2012-05-07 12:47:02 +020013052 if (length > PY_SSIZE_T_MAX - writer->pos) {
13053 PyErr_NoMemory();
13054 return -1;
13055 }
13056 newlen = writer->pos + length;
13057
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013058 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013059
Victor Stinnerd3f08822012-05-29 12:57:52 +020013060 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013061 assert(!writer->readonly);
13062 if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / 4)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013063 /* overallocate 25% to limit the number of resize */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013064 newlen += newlen / 4;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013065 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013066 if (newlen < writer->min_length)
13067 newlen = writer->min_length;
13068
Victor Stinnerd3f08822012-05-29 12:57:52 +020013069 writer->buffer = PyUnicode_New(newlen, maxchar);
13070 if (writer->buffer == NULL)
13071 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013072 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013073 else if (newlen > writer->size) {
13074 if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / 4)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013075 /* overallocate 25% to limit the number of resize */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013076 newlen += newlen / 4;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013077 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013078 if (newlen < writer->min_length)
13079 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013080
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013081 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013082 /* resize + widen */
13083 newbuffer = PyUnicode_New(newlen, maxchar);
13084 if (newbuffer == NULL)
13085 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013086 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13087 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013088 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013089 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013090 }
13091 else {
13092 newbuffer = resize_compact(writer->buffer, newlen);
13093 if (newbuffer == NULL)
13094 return -1;
13095 }
13096 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013097 }
13098 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013099 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013100 newbuffer = PyUnicode_New(writer->size, maxchar);
13101 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013102 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013103 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13104 writer->buffer, 0, writer->pos);
13105 Py_DECREF(writer->buffer);
13106 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013107 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013108 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013109 return 0;
13110}
13111
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013112Py_LOCAL_INLINE(int)
13113_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013114{
13115 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13116 return -1;
13117 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13118 writer->pos++;
13119 return 0;
13120}
13121
13122int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013123_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13124{
13125 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13126}
13127
13128int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013129_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13130{
13131 Py_UCS4 maxchar;
13132 Py_ssize_t len;
13133
13134 if (PyUnicode_READY(str) == -1)
13135 return -1;
13136 len = PyUnicode_GET_LENGTH(str);
13137 if (len == 0)
13138 return 0;
13139 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13140 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013141 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013142 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013143 Py_INCREF(str);
13144 writer->buffer = str;
13145 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013146 writer->pos += len;
13147 return 0;
13148 }
13149 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13150 return -1;
13151 }
13152 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13153 str, 0, len);
13154 writer->pos += len;
13155 return 0;
13156}
13157
Victor Stinnere215d962012-10-06 23:03:36 +020013158int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013159_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13160 Py_ssize_t start, Py_ssize_t end)
13161{
13162 Py_UCS4 maxchar;
13163 Py_ssize_t len;
13164
13165 if (PyUnicode_READY(str) == -1)
13166 return -1;
13167
13168 assert(0 <= start);
13169 assert(end <= PyUnicode_GET_LENGTH(str));
13170 assert(start <= end);
13171
13172 if (end == 0)
13173 return 0;
13174
13175 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13176 return _PyUnicodeWriter_WriteStr(writer, str);
13177
13178 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13179 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13180 else
13181 maxchar = writer->maxchar;
13182 len = end - start;
13183
13184 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13185 return -1;
13186
13187 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13188 str, start, len);
13189 writer->pos += len;
13190 return 0;
13191}
13192
13193int
Victor Stinnere215d962012-10-06 23:03:36 +020013194_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
13195{
13196 Py_UCS4 maxchar;
13197
13198 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13199 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13200 return -1;
13201 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13202 writer->pos += len;
13203 return 0;
13204}
13205
Victor Stinnerd3f08822012-05-29 12:57:52 +020013206PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013207_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013208{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013209 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013210 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013211 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013212 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013213 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013214 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013215 str = writer->buffer;
13216 writer->buffer = NULL;
13217 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13218 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013219 }
13220 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13221 PyObject *newbuffer;
13222 newbuffer = resize_compact(writer->buffer, writer->pos);
13223 if (newbuffer == NULL) {
13224 Py_DECREF(writer->buffer);
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013225 writer->buffer = NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013226 return NULL;
13227 }
13228 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013229 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013230 str = writer->buffer;
13231 writer->buffer = NULL;
13232 assert(_PyUnicode_CheckConsistency(str, 1));
13233 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013234}
13235
Victor Stinnerd3f08822012-05-29 12:57:52 +020013236void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013237_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013238{
13239 Py_CLEAR(writer->buffer);
13240}
13241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013243
13244PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013246\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013247Return a formatted version of S, using substitutions from args and kwargs.\n\
13248The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013249
Eric Smith27bbca62010-11-04 17:06:58 +000013250PyDoc_STRVAR(format_map__doc__,
13251 "S.format_map(mapping) -> str\n\
13252\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013253Return a formatted version of S, using substitutions from mapping.\n\
13254The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013255
Eric Smith4a7d76d2008-05-30 18:10:19 +000013256static PyObject *
13257unicode__format__(PyObject* self, PyObject* args)
13258{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013259 PyObject *format_spec;
13260 _PyUnicodeWriter writer;
13261 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013262
13263 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13264 return NULL;
13265
Victor Stinnerd3f08822012-05-29 12:57:52 +020013266 if (PyUnicode_READY(self) == -1)
13267 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013268 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013269 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13270 self, format_spec, 0,
13271 PyUnicode_GET_LENGTH(format_spec));
13272 if (ret == -1) {
13273 _PyUnicodeWriter_Dealloc(&writer);
13274 return NULL;
13275 }
13276 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013277}
13278
Eric Smith8c663262007-08-25 02:26:07 +000013279PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013280 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013281\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013282Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013283
13284static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013285unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 Py_ssize_t size;
13288
13289 /* If it's a compact object, account for base structure +
13290 character data. */
13291 if (PyUnicode_IS_COMPACT_ASCII(v))
13292 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13293 else if (PyUnicode_IS_COMPACT(v))
13294 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013295 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013296 else {
13297 /* If it is a two-block object, account for base object, and
13298 for character block if present. */
13299 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013300 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013301 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013302 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013303 }
13304 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013305 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013306 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013307 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013308 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013309 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013310
13311 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013312}
13313
13314PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013315 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013316
13317static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013318unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013319{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013320 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013321 if (!copy)
13322 return NULL;
13323 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013324}
13325
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013327 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013328 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013329 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13330 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013331 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13332 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013333 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013334 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13335 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13336 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13337 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13338 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013339 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013340 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13341 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13342 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013343 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013344 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13345 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13346 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013347 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013348 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013349 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013350 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013351 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13352 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13353 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13354 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13355 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13356 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13357 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13358 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13359 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13360 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13361 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13362 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13363 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13364 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013365 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013366 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013367 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013368 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013369 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013370 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013371 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013372 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013373#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013374 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013375 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013376#endif
13377
Benjamin Peterson14339b62009-01-31 16:36:08 +000013378 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013379 {NULL, NULL}
13380};
13381
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013382static PyObject *
13383unicode_mod(PyObject *v, PyObject *w)
13384{
Brian Curtindfc80e32011-08-10 20:28:54 -050013385 if (!PyUnicode_Check(v))
13386 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013387 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013388}
13389
13390static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013391 0, /*nb_add*/
13392 0, /*nb_subtract*/
13393 0, /*nb_multiply*/
13394 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013395};
13396
Guido van Rossumd57fd912000-03-10 22:53:23 +000013397static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013398 (lenfunc) unicode_length, /* sq_length */
13399 PyUnicode_Concat, /* sq_concat */
13400 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13401 (ssizeargfunc) unicode_getitem, /* sq_item */
13402 0, /* sq_slice */
13403 0, /* sq_ass_item */
13404 0, /* sq_ass_slice */
13405 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013406};
13407
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013408static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013409unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013411 if (PyUnicode_READY(self) == -1)
13412 return NULL;
13413
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013414 if (PyIndex_Check(item)) {
13415 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013416 if (i == -1 && PyErr_Occurred())
13417 return NULL;
13418 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013419 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013420 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013421 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013422 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013423 PyObject *result;
13424 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013425 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013426 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013428 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013429 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013430 return NULL;
13431 }
13432
13433 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013434 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013435 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013436 slicelength == PyUnicode_GET_LENGTH(self)) {
13437 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013438 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013439 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013440 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013441 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013442 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013443 src_kind = PyUnicode_KIND(self);
13444 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013445 if (!PyUnicode_IS_ASCII(self)) {
13446 kind_limit = kind_maxchar_limit(src_kind);
13447 max_char = 0;
13448 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13449 ch = PyUnicode_READ(src_kind, src_data, cur);
13450 if (ch > max_char) {
13451 max_char = ch;
13452 if (max_char >= kind_limit)
13453 break;
13454 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013455 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013456 }
Victor Stinner55c99112011-10-13 01:17:06 +020013457 else
13458 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013459 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013460 if (result == NULL)
13461 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013462 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013463 dest_data = PyUnicode_DATA(result);
13464
13465 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013466 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13467 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013468 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013469 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013470 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013471 } else {
13472 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13473 return NULL;
13474 }
13475}
13476
13477static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013478 (lenfunc)unicode_length, /* mp_length */
13479 (binaryfunc)unicode_subscript, /* mp_subscript */
13480 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013481};
13482
Guido van Rossumd57fd912000-03-10 22:53:23 +000013483
Guido van Rossumd57fd912000-03-10 22:53:23 +000013484/* Helpers for PyUnicode_Format() */
13485
Victor Stinnera47082312012-10-04 02:19:54 +020013486struct unicode_formatter_t {
13487 PyObject *args;
13488 int args_owned;
13489 Py_ssize_t arglen, argidx;
13490 PyObject *dict;
13491
13492 enum PyUnicode_Kind fmtkind;
13493 Py_ssize_t fmtcnt, fmtpos;
13494 void *fmtdata;
13495 PyObject *fmtstr;
13496
13497 _PyUnicodeWriter writer;
13498};
13499
13500struct unicode_format_arg_t {
13501 Py_UCS4 ch;
13502 int flags;
13503 Py_ssize_t width;
13504 int prec;
13505 int sign;
13506};
13507
Guido van Rossumd57fd912000-03-10 22:53:23 +000013508static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013509unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013510{
Victor Stinnera47082312012-10-04 02:19:54 +020013511 Py_ssize_t argidx = ctx->argidx;
13512
13513 if (argidx < ctx->arglen) {
13514 ctx->argidx++;
13515 if (ctx->arglen < 0)
13516 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013517 else
Victor Stinnera47082312012-10-04 02:19:54 +020013518 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013519 }
13520 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013522 return NULL;
13523}
13524
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013525/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013526
Victor Stinnera47082312012-10-04 02:19:54 +020013527/* Format a float into the writer if the writer is not NULL, or into *p_output
13528 otherwise.
13529
13530 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013531static int
Victor Stinnera47082312012-10-04 02:19:54 +020013532formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13533 PyObject **p_output,
13534 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013535{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013536 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013537 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013538 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013539 int prec;
13540 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013541
Guido van Rossumd57fd912000-03-10 22:53:23 +000013542 x = PyFloat_AsDouble(v);
13543 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013545
Victor Stinnera47082312012-10-04 02:19:54 +020013546 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013547 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013549
Victor Stinnera47082312012-10-04 02:19:54 +020013550 if (arg->flags & F_ALT)
13551 dtoa_flags = Py_DTSF_ALT;
13552 else
13553 dtoa_flags = 0;
13554 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013555 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013556 return -1;
13557 len = strlen(p);
13558 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013559 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13560 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013561 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013562 }
Victor Stinner184252a2012-06-16 02:57:41 +020013563 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013564 writer->pos += len;
13565 }
13566 else
13567 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013568 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013569 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013570}
13571
Victor Stinnerd0880d52012-04-27 23:40:13 +020013572/* formatlong() emulates the format codes d, u, o, x and X, and
13573 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13574 * Python's regular ints.
13575 * Return value: a new PyUnicodeObject*, or NULL if error.
13576 * The output string is of the form
13577 * "-"? ("0x" | "0X")? digit+
13578 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13579 * set in flags. The case of hex digits will be correct,
13580 * There will be at least prec digits, zero-filled on the left if
13581 * necessary to get that many.
13582 * val object to be converted
13583 * flags bitmask of format flags; only F_ALT is looked at
13584 * prec minimum number of digits; 0-fill on left if needed
13585 * type a character in [duoxX]; u acts the same as d
13586 *
13587 * CAUTION: o, x and X conversions on regular ints can never
13588 * produce a '-' sign, but can for Python's unbounded ints.
13589 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013590static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013591formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013592{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013593 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013594 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013595 Py_ssize_t i;
13596 int sign; /* 1 if '-', else 0 */
13597 int len; /* number of characters */
13598 Py_ssize_t llen;
13599 int numdigits; /* len == numnondigits + numdigits */
13600 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013601 int prec = arg->prec;
13602 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013603
Victor Stinnerd0880d52012-04-27 23:40:13 +020013604 /* Avoid exceeding SSIZE_T_MAX */
13605 if (prec > INT_MAX-3) {
13606 PyErr_SetString(PyExc_OverflowError,
13607 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013608 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013609 }
13610
13611 assert(PyLong_Check(val));
13612
13613 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013614 default:
13615 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013616 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013617 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013618 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013619 /* int and int subclasses should print numerically when a numeric */
13620 /* format code is used (see issue18780) */
13621 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013622 break;
13623 case 'o':
13624 numnondigits = 2;
13625 result = PyNumber_ToBase(val, 8);
13626 break;
13627 case 'x':
13628 case 'X':
13629 numnondigits = 2;
13630 result = PyNumber_ToBase(val, 16);
13631 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013632 }
13633 if (!result)
13634 return NULL;
13635
13636 assert(unicode_modifiable(result));
13637 assert(PyUnicode_IS_READY(result));
13638 assert(PyUnicode_IS_ASCII(result));
13639
13640 /* To modify the string in-place, there can only be one reference. */
13641 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013642 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013643 PyErr_BadInternalCall();
13644 return NULL;
13645 }
13646 buf = PyUnicode_DATA(result);
13647 llen = PyUnicode_GET_LENGTH(result);
13648 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013649 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013650 PyErr_SetString(PyExc_ValueError,
13651 "string too large in _PyBytes_FormatLong");
13652 return NULL;
13653 }
13654 len = (int)llen;
13655 sign = buf[0] == '-';
13656 numnondigits += sign;
13657 numdigits = len - numnondigits;
13658 assert(numdigits > 0);
13659
13660 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013661 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013662 (type == 'o' || type == 'x' || type == 'X'))) {
13663 assert(buf[sign] == '0');
13664 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13665 buf[sign+1] == 'o');
13666 numnondigits -= 2;
13667 buf += 2;
13668 len -= 2;
13669 if (sign)
13670 buf[0] = '-';
13671 assert(len == numnondigits + numdigits);
13672 assert(numdigits > 0);
13673 }
13674
13675 /* Fill with leading zeroes to meet minimum width. */
13676 if (prec > numdigits) {
13677 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13678 numnondigits + prec);
13679 char *b1;
13680 if (!r1) {
13681 Py_DECREF(result);
13682 return NULL;
13683 }
13684 b1 = PyBytes_AS_STRING(r1);
13685 for (i = 0; i < numnondigits; ++i)
13686 *b1++ = *buf++;
13687 for (i = 0; i < prec - numdigits; i++)
13688 *b1++ = '0';
13689 for (i = 0; i < numdigits; i++)
13690 *b1++ = *buf++;
13691 *b1 = '\0';
13692 Py_DECREF(result);
13693 result = r1;
13694 buf = PyBytes_AS_STRING(result);
13695 len = numnondigits + prec;
13696 }
13697
13698 /* Fix up case for hex conversions. */
13699 if (type == 'X') {
13700 /* Need to convert all lower case letters to upper case.
13701 and need to convert 0x to 0X (and -0x to -0X). */
13702 for (i = 0; i < len; i++)
13703 if (buf[i] >= 'a' && buf[i] <= 'x')
13704 buf[i] -= 'a'-'A';
13705 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013706 if (!PyUnicode_Check(result)
13707 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013708 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013709 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013710 Py_DECREF(result);
13711 result = unicode;
13712 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013713 else if (len != PyUnicode_GET_LENGTH(result)) {
13714 if (PyUnicode_Resize(&result, len) < 0)
13715 Py_CLEAR(result);
13716 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013717 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013718}
13719
Victor Stinner621ef3d2012-10-02 00:33:47 +020013720/* Format an integer.
13721 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013722 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013723 * -1 and raise an exception on error */
13724static int
Victor Stinnera47082312012-10-04 02:19:54 +020013725mainformatlong(PyObject *v,
13726 struct unicode_format_arg_t *arg,
13727 PyObject **p_output,
13728 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013729{
13730 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013731 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013732
13733 if (!PyNumber_Check(v))
13734 goto wrongtype;
13735
13736 if (!PyLong_Check(v)) {
13737 iobj = PyNumber_Long(v);
13738 if (iobj == NULL) {
13739 if (PyErr_ExceptionMatches(PyExc_TypeError))
13740 goto wrongtype;
13741 return -1;
13742 }
13743 assert(PyLong_Check(iobj));
13744 }
13745 else {
13746 iobj = v;
13747 Py_INCREF(iobj);
13748 }
13749
13750 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013751 && arg->width == -1 && arg->prec == -1
13752 && !(arg->flags & (F_SIGN | F_BLANK))
13753 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013754 {
13755 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013756 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013757 int base;
13758
Victor Stinnera47082312012-10-04 02:19:54 +020013759 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013760 {
13761 default:
13762 assert(0 && "'type' not in [diuoxX]");
13763 case 'd':
13764 case 'i':
13765 case 'u':
13766 base = 10;
13767 break;
13768 case 'o':
13769 base = 8;
13770 break;
13771 case 'x':
13772 case 'X':
13773 base = 16;
13774 break;
13775 }
13776
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013777 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13778 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013779 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013780 }
13781 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013782 return 1;
13783 }
13784
Victor Stinnera47082312012-10-04 02:19:54 +020013785 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013786 Py_DECREF(iobj);
13787 if (res == NULL)
13788 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013789 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013790 return 0;
13791
13792wrongtype:
13793 PyErr_Format(PyExc_TypeError,
13794 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013795 "not %.200s",
13796 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013797 return -1;
13798}
13799
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013800static Py_UCS4
13801formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013802{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013803 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013804 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013805 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013806 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013807 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 goto onError;
13809 }
13810 else {
13811 /* Integer input truncated to a character */
13812 long x;
13813 x = PyLong_AsLong(v);
13814 if (x == -1 && PyErr_Occurred())
13815 goto onError;
13816
Victor Stinner8faf8212011-12-08 22:14:11 +010013817 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013818 PyErr_SetString(PyExc_OverflowError,
13819 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013820 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013821 }
13822
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013823 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013824 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013825
Benjamin Peterson29060642009-01-31 22:14:21 +000013826 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013827 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013829 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830}
13831
Victor Stinnera47082312012-10-04 02:19:54 +020013832/* Parse options of an argument: flags, width, precision.
13833 Handle also "%(name)" syntax.
13834
13835 Return 0 if the argument has been formatted into arg->str.
13836 Return 1 if the argument has been written into ctx->writer,
13837 Raise an exception and return -1 on error. */
13838static int
13839unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13840 struct unicode_format_arg_t *arg)
13841{
13842#define FORMAT_READ(ctx) \
13843 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13844
13845 PyObject *v;
13846
Victor Stinnera47082312012-10-04 02:19:54 +020013847 if (arg->ch == '(') {
13848 /* Get argument value from a dictionary. Example: "%(name)s". */
13849 Py_ssize_t keystart;
13850 Py_ssize_t keylen;
13851 PyObject *key;
13852 int pcount = 1;
13853
13854 if (ctx->dict == NULL) {
13855 PyErr_SetString(PyExc_TypeError,
13856 "format requires a mapping");
13857 return -1;
13858 }
13859 ++ctx->fmtpos;
13860 --ctx->fmtcnt;
13861 keystart = ctx->fmtpos;
13862 /* Skip over balanced parentheses */
13863 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13864 arg->ch = FORMAT_READ(ctx);
13865 if (arg->ch == ')')
13866 --pcount;
13867 else if (arg->ch == '(')
13868 ++pcount;
13869 ctx->fmtpos++;
13870 }
13871 keylen = ctx->fmtpos - keystart - 1;
13872 if (ctx->fmtcnt < 0 || pcount > 0) {
13873 PyErr_SetString(PyExc_ValueError,
13874 "incomplete format key");
13875 return -1;
13876 }
13877 key = PyUnicode_Substring(ctx->fmtstr,
13878 keystart, keystart + keylen);
13879 if (key == NULL)
13880 return -1;
13881 if (ctx->args_owned) {
13882 Py_DECREF(ctx->args);
13883 ctx->args_owned = 0;
13884 }
13885 ctx->args = PyObject_GetItem(ctx->dict, key);
13886 Py_DECREF(key);
13887 if (ctx->args == NULL)
13888 return -1;
13889 ctx->args_owned = 1;
13890 ctx->arglen = -1;
13891 ctx->argidx = -2;
13892 }
13893
13894 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020013895 while (--ctx->fmtcnt >= 0) {
13896 arg->ch = FORMAT_READ(ctx);
13897 ctx->fmtpos++;
13898 switch (arg->ch) {
13899 case '-': arg->flags |= F_LJUST; continue;
13900 case '+': arg->flags |= F_SIGN; continue;
13901 case ' ': arg->flags |= F_BLANK; continue;
13902 case '#': arg->flags |= F_ALT; continue;
13903 case '0': arg->flags |= F_ZERO; continue;
13904 }
13905 break;
13906 }
13907
13908 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020013909 if (arg->ch == '*') {
13910 v = unicode_format_getnextarg(ctx);
13911 if (v == NULL)
13912 return -1;
13913 if (!PyLong_Check(v)) {
13914 PyErr_SetString(PyExc_TypeError,
13915 "* wants int");
13916 return -1;
13917 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013918 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013919 if (arg->width == -1 && PyErr_Occurred())
13920 return -1;
13921 if (arg->width < 0) {
13922 arg->flags |= F_LJUST;
13923 arg->width = -arg->width;
13924 }
13925 if (--ctx->fmtcnt >= 0) {
13926 arg->ch = FORMAT_READ(ctx);
13927 ctx->fmtpos++;
13928 }
13929 }
13930 else if (arg->ch >= '0' && arg->ch <= '9') {
13931 arg->width = arg->ch - '0';
13932 while (--ctx->fmtcnt >= 0) {
13933 arg->ch = FORMAT_READ(ctx);
13934 ctx->fmtpos++;
13935 if (arg->ch < '0' || arg->ch > '9')
13936 break;
13937 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13938 mixing signed and unsigned comparison. Since arg->ch is between
13939 '0' and '9', casting to int is safe. */
13940 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13941 PyErr_SetString(PyExc_ValueError,
13942 "width too big");
13943 return -1;
13944 }
13945 arg->width = arg->width*10 + (arg->ch - '0');
13946 }
13947 }
13948
13949 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020013950 if (arg->ch == '.') {
13951 arg->prec = 0;
13952 if (--ctx->fmtcnt >= 0) {
13953 arg->ch = FORMAT_READ(ctx);
13954 ctx->fmtpos++;
13955 }
13956 if (arg->ch == '*') {
13957 v = unicode_format_getnextarg(ctx);
13958 if (v == NULL)
13959 return -1;
13960 if (!PyLong_Check(v)) {
13961 PyErr_SetString(PyExc_TypeError,
13962 "* wants int");
13963 return -1;
13964 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013965 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013966 if (arg->prec == -1 && PyErr_Occurred())
13967 return -1;
13968 if (arg->prec < 0)
13969 arg->prec = 0;
13970 if (--ctx->fmtcnt >= 0) {
13971 arg->ch = FORMAT_READ(ctx);
13972 ctx->fmtpos++;
13973 }
13974 }
13975 else if (arg->ch >= '0' && arg->ch <= '9') {
13976 arg->prec = arg->ch - '0';
13977 while (--ctx->fmtcnt >= 0) {
13978 arg->ch = FORMAT_READ(ctx);
13979 ctx->fmtpos++;
13980 if (arg->ch < '0' || arg->ch > '9')
13981 break;
13982 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13983 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013984 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013985 return -1;
13986 }
13987 arg->prec = arg->prec*10 + (arg->ch - '0');
13988 }
13989 }
13990 }
13991
13992 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13993 if (ctx->fmtcnt >= 0) {
13994 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13995 if (--ctx->fmtcnt >= 0) {
13996 arg->ch = FORMAT_READ(ctx);
13997 ctx->fmtpos++;
13998 }
13999 }
14000 }
14001 if (ctx->fmtcnt < 0) {
14002 PyErr_SetString(PyExc_ValueError,
14003 "incomplete format");
14004 return -1;
14005 }
14006 return 0;
14007
14008#undef FORMAT_READ
14009}
14010
14011/* Format one argument. Supported conversion specifiers:
14012
14013 - "s", "r", "a": any type
14014 - "i", "d", "u", "o", "x", "X": int
14015 - "e", "E", "f", "F", "g", "G": float
14016 - "c": int or str (1 character)
14017
Victor Stinner8dbd4212012-12-04 09:30:24 +010014018 When possible, the output is written directly into the Unicode writer
14019 (ctx->writer). A string is created when padding is required.
14020
Victor Stinnera47082312012-10-04 02:19:54 +020014021 Return 0 if the argument has been formatted into *p_str,
14022 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014023 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014024static int
14025unicode_format_arg_format(struct unicode_formatter_t *ctx,
14026 struct unicode_format_arg_t *arg,
14027 PyObject **p_str)
14028{
14029 PyObject *v;
14030 _PyUnicodeWriter *writer = &ctx->writer;
14031
14032 if (ctx->fmtcnt == 0)
14033 ctx->writer.overallocate = 0;
14034
14035 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014036 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014037 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014038 return 1;
14039 }
14040
14041 v = unicode_format_getnextarg(ctx);
14042 if (v == NULL)
14043 return -1;
14044
Victor Stinnera47082312012-10-04 02:19:54 +020014045
14046 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014047 case 's':
14048 case 'r':
14049 case 'a':
14050 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14051 /* Fast path */
14052 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14053 return -1;
14054 return 1;
14055 }
14056
14057 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14058 *p_str = v;
14059 Py_INCREF(*p_str);
14060 }
14061 else {
14062 if (arg->ch == 's')
14063 *p_str = PyObject_Str(v);
14064 else if (arg->ch == 'r')
14065 *p_str = PyObject_Repr(v);
14066 else
14067 *p_str = PyObject_ASCII(v);
14068 }
14069 break;
14070
14071 case 'i':
14072 case 'd':
14073 case 'u':
14074 case 'o':
14075 case 'x':
14076 case 'X':
14077 {
14078 int ret = mainformatlong(v, arg, p_str, writer);
14079 if (ret != 0)
14080 return ret;
14081 arg->sign = 1;
14082 break;
14083 }
14084
14085 case 'e':
14086 case 'E':
14087 case 'f':
14088 case 'F':
14089 case 'g':
14090 case 'G':
14091 if (arg->width == -1 && arg->prec == -1
14092 && !(arg->flags & (F_SIGN | F_BLANK)))
14093 {
14094 /* Fast path */
14095 if (formatfloat(v, arg, NULL, writer) == -1)
14096 return -1;
14097 return 1;
14098 }
14099
14100 arg->sign = 1;
14101 if (formatfloat(v, arg, p_str, NULL) == -1)
14102 return -1;
14103 break;
14104
14105 case 'c':
14106 {
14107 Py_UCS4 ch = formatchar(v);
14108 if (ch == (Py_UCS4) -1)
14109 return -1;
14110 if (arg->width == -1 && arg->prec == -1) {
14111 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014112 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014113 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014114 return 1;
14115 }
14116 *p_str = PyUnicode_FromOrdinal(ch);
14117 break;
14118 }
14119
14120 default:
14121 PyErr_Format(PyExc_ValueError,
14122 "unsupported format character '%c' (0x%x) "
14123 "at index %zd",
14124 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14125 (int)arg->ch,
14126 ctx->fmtpos - 1);
14127 return -1;
14128 }
14129 if (*p_str == NULL)
14130 return -1;
14131 assert (PyUnicode_Check(*p_str));
14132 return 0;
14133}
14134
14135static int
14136unicode_format_arg_output(struct unicode_formatter_t *ctx,
14137 struct unicode_format_arg_t *arg,
14138 PyObject *str)
14139{
14140 Py_ssize_t len;
14141 enum PyUnicode_Kind kind;
14142 void *pbuf;
14143 Py_ssize_t pindex;
14144 Py_UCS4 signchar;
14145 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014146 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014147 Py_ssize_t sublen;
14148 _PyUnicodeWriter *writer = &ctx->writer;
14149 Py_UCS4 fill;
14150
14151 fill = ' ';
14152 if (arg->sign && arg->flags & F_ZERO)
14153 fill = '0';
14154
14155 if (PyUnicode_READY(str) == -1)
14156 return -1;
14157
14158 len = PyUnicode_GET_LENGTH(str);
14159 if ((arg->width == -1 || arg->width <= len)
14160 && (arg->prec == -1 || arg->prec >= len)
14161 && !(arg->flags & (F_SIGN | F_BLANK)))
14162 {
14163 /* Fast path */
14164 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14165 return -1;
14166 return 0;
14167 }
14168
14169 /* Truncate the string for "s", "r" and "a" formats
14170 if the precision is set */
14171 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14172 if (arg->prec >= 0 && len > arg->prec)
14173 len = arg->prec;
14174 }
14175
14176 /* Adjust sign and width */
14177 kind = PyUnicode_KIND(str);
14178 pbuf = PyUnicode_DATA(str);
14179 pindex = 0;
14180 signchar = '\0';
14181 if (arg->sign) {
14182 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14183 if (ch == '-' || ch == '+') {
14184 signchar = ch;
14185 len--;
14186 pindex++;
14187 }
14188 else if (arg->flags & F_SIGN)
14189 signchar = '+';
14190 else if (arg->flags & F_BLANK)
14191 signchar = ' ';
14192 else
14193 arg->sign = 0;
14194 }
14195 if (arg->width < len)
14196 arg->width = len;
14197
14198 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014199 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014200 if (!(arg->flags & F_LJUST)) {
14201 if (arg->sign) {
14202 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014203 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014204 }
14205 else {
14206 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014207 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014208 }
14209 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014210 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14211 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014212 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014213 }
14214
Victor Stinnera47082312012-10-04 02:19:54 +020014215 buflen = arg->width;
14216 if (arg->sign && len == arg->width)
14217 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014218 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014219 return -1;
14220
14221 /* Write the sign if needed */
14222 if (arg->sign) {
14223 if (fill != ' ') {
14224 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14225 writer->pos += 1;
14226 }
14227 if (arg->width > len)
14228 arg->width--;
14229 }
14230
14231 /* Write the numeric prefix for "x", "X" and "o" formats
14232 if the alternate form is used.
14233 For example, write "0x" for the "%#x" format. */
14234 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14235 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14236 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14237 if (fill != ' ') {
14238 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14239 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14240 writer->pos += 2;
14241 pindex += 2;
14242 }
14243 arg->width -= 2;
14244 if (arg->width < 0)
14245 arg->width = 0;
14246 len -= 2;
14247 }
14248
14249 /* Pad left with the fill character if needed */
14250 if (arg->width > len && !(arg->flags & F_LJUST)) {
14251 sublen = arg->width - len;
14252 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14253 writer->pos += sublen;
14254 arg->width = len;
14255 }
14256
14257 /* If padding with spaces: write sign if needed and/or numeric prefix if
14258 the alternate form is used */
14259 if (fill == ' ') {
14260 if (arg->sign) {
14261 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14262 writer->pos += 1;
14263 }
14264 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14265 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14266 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14267 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14268 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14269 writer->pos += 2;
14270 pindex += 2;
14271 }
14272 }
14273
14274 /* Write characters */
14275 if (len) {
14276 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14277 str, pindex, len);
14278 writer->pos += len;
14279 }
14280
14281 /* Pad right with the fill character if needed */
14282 if (arg->width > len) {
14283 sublen = arg->width - len;
14284 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14285 writer->pos += sublen;
14286 }
14287 return 0;
14288}
14289
14290/* Helper of PyUnicode_Format(): format one arg.
14291 Return 0 on success, raise an exception and return -1 on error. */
14292static int
14293unicode_format_arg(struct unicode_formatter_t *ctx)
14294{
14295 struct unicode_format_arg_t arg;
14296 PyObject *str;
14297 int ret;
14298
Victor Stinner8dbd4212012-12-04 09:30:24 +010014299 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14300 arg.flags = 0;
14301 arg.width = -1;
14302 arg.prec = -1;
14303 arg.sign = 0;
14304 str = NULL;
14305
Victor Stinnera47082312012-10-04 02:19:54 +020014306 ret = unicode_format_arg_parse(ctx, &arg);
14307 if (ret == -1)
14308 return -1;
14309
14310 ret = unicode_format_arg_format(ctx, &arg, &str);
14311 if (ret == -1)
14312 return -1;
14313
14314 if (ret != 1) {
14315 ret = unicode_format_arg_output(ctx, &arg, str);
14316 Py_DECREF(str);
14317 if (ret == -1)
14318 return -1;
14319 }
14320
14321 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14322 PyErr_SetString(PyExc_TypeError,
14323 "not all arguments converted during string formatting");
14324 return -1;
14325 }
14326 return 0;
14327}
14328
Alexander Belopolsky40018472011-02-26 01:02:56 +000014329PyObject *
14330PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014331{
Victor Stinnera47082312012-10-04 02:19:54 +020014332 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014333
Guido van Rossumd57fd912000-03-10 22:53:23 +000014334 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014335 PyErr_BadInternalCall();
14336 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014337 }
Victor Stinnera47082312012-10-04 02:19:54 +020014338
14339 ctx.fmtstr = PyUnicode_FromObject(format);
14340 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014341 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014342 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14343 Py_DECREF(ctx.fmtstr);
14344 return NULL;
14345 }
14346 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14347 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14348 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14349 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014350
Victor Stinner8f674cc2013-04-17 23:02:17 +020014351 _PyUnicodeWriter_Init(&ctx.writer);
14352 ctx.writer.min_length = ctx.fmtcnt + 100;
14353 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014354
Guido van Rossumd57fd912000-03-10 22:53:23 +000014355 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014356 ctx.arglen = PyTuple_Size(args);
14357 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014358 }
14359 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014360 ctx.arglen = -1;
14361 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014362 }
Victor Stinnera47082312012-10-04 02:19:54 +020014363 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014364 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014365 ctx.dict = args;
14366 else
14367 ctx.dict = NULL;
14368 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014369
Victor Stinnera47082312012-10-04 02:19:54 +020014370 while (--ctx.fmtcnt >= 0) {
14371 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014372 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014373
14374 nonfmtpos = ctx.fmtpos++;
14375 while (ctx.fmtcnt >= 0 &&
14376 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14377 ctx.fmtpos++;
14378 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014379 }
Victor Stinnera47082312012-10-04 02:19:54 +020014380 if (ctx.fmtcnt < 0) {
14381 ctx.fmtpos--;
14382 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014383 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014384
Victor Stinnercfc4c132013-04-03 01:48:39 +020014385 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14386 nonfmtpos, ctx.fmtpos) < 0)
14387 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014388 }
14389 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014390 ctx.fmtpos++;
14391 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014392 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014393 }
14394 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014395
Victor Stinnera47082312012-10-04 02:19:54 +020014396 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014397 PyErr_SetString(PyExc_TypeError,
14398 "not all arguments converted during string formatting");
14399 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014400 }
14401
Victor Stinnera47082312012-10-04 02:19:54 +020014402 if (ctx.args_owned) {
14403 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014404 }
Victor Stinnera47082312012-10-04 02:19:54 +020014405 Py_DECREF(ctx.fmtstr);
14406 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014407
Benjamin Peterson29060642009-01-31 22:14:21 +000014408 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014409 Py_DECREF(ctx.fmtstr);
14410 _PyUnicodeWriter_Dealloc(&ctx.writer);
14411 if (ctx.args_owned) {
14412 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014413 }
14414 return NULL;
14415}
14416
Jeremy Hylton938ace62002-07-17 16:30:39 +000014417static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014418unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14419
Tim Peters6d6c1a32001-08-02 04:15:00 +000014420static PyObject *
14421unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14422{
Benjamin Peterson29060642009-01-31 22:14:21 +000014423 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014424 static char *kwlist[] = {"object", "encoding", "errors", 0};
14425 char *encoding = NULL;
14426 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014427
Benjamin Peterson14339b62009-01-31 16:36:08 +000014428 if (type != &PyUnicode_Type)
14429 return unicode_subtype_new(type, args, kwds);
14430 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014431 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014432 return NULL;
14433 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014434 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014435 if (encoding == NULL && errors == NULL)
14436 return PyObject_Str(x);
14437 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014438 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014439}
14440
Guido van Rossume023fe02001-08-30 03:12:59 +000014441static PyObject *
14442unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14443{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014444 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014445 Py_ssize_t length, char_size;
14446 int share_wstr, share_utf8;
14447 unsigned int kind;
14448 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014449
Benjamin Peterson14339b62009-01-31 16:36:08 +000014450 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014451
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014452 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014453 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014454 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014455 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014456 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014457 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014458 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014459 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014460
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014461 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014462 if (self == NULL) {
14463 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014464 return NULL;
14465 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014466 kind = PyUnicode_KIND(unicode);
14467 length = PyUnicode_GET_LENGTH(unicode);
14468
14469 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014470#ifdef Py_DEBUG
14471 _PyUnicode_HASH(self) = -1;
14472#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014473 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014474#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014475 _PyUnicode_STATE(self).interned = 0;
14476 _PyUnicode_STATE(self).kind = kind;
14477 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014478 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014479 _PyUnicode_STATE(self).ready = 1;
14480 _PyUnicode_WSTR(self) = NULL;
14481 _PyUnicode_UTF8_LENGTH(self) = 0;
14482 _PyUnicode_UTF8(self) = NULL;
14483 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014484 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014485
14486 share_utf8 = 0;
14487 share_wstr = 0;
14488 if (kind == PyUnicode_1BYTE_KIND) {
14489 char_size = 1;
14490 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14491 share_utf8 = 1;
14492 }
14493 else if (kind == PyUnicode_2BYTE_KIND) {
14494 char_size = 2;
14495 if (sizeof(wchar_t) == 2)
14496 share_wstr = 1;
14497 }
14498 else {
14499 assert(kind == PyUnicode_4BYTE_KIND);
14500 char_size = 4;
14501 if (sizeof(wchar_t) == 4)
14502 share_wstr = 1;
14503 }
14504
14505 /* Ensure we won't overflow the length. */
14506 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14507 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014508 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014509 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014510 data = PyObject_MALLOC((length + 1) * char_size);
14511 if (data == NULL) {
14512 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014513 goto onError;
14514 }
14515
Victor Stinnerc3c74152011-10-02 20:39:55 +020014516 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014517 if (share_utf8) {
14518 _PyUnicode_UTF8_LENGTH(self) = length;
14519 _PyUnicode_UTF8(self) = data;
14520 }
14521 if (share_wstr) {
14522 _PyUnicode_WSTR_LENGTH(self) = length;
14523 _PyUnicode_WSTR(self) = (wchar_t *)data;
14524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014525
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014526 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014527 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014528 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014529#ifdef Py_DEBUG
14530 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14531#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014532 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014533 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014534
14535onError:
14536 Py_DECREF(unicode);
14537 Py_DECREF(self);
14538 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014539}
14540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014541PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014542"str(object='') -> str\n\
14543str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014544\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014545Create a new string object from the given object. If encoding or\n\
14546errors is specified, then the object must expose a data buffer\n\
14547that will be decoded using the given encoding and error handler.\n\
14548Otherwise, returns the result of object.__str__() (if defined)\n\
14549or repr(object).\n\
14550encoding defaults to sys.getdefaultencoding().\n\
14551errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014552
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014553static PyObject *unicode_iter(PyObject *seq);
14554
Guido van Rossumd57fd912000-03-10 22:53:23 +000014555PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014556 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014557 "str", /* tp_name */
14558 sizeof(PyUnicodeObject), /* tp_size */
14559 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014560 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014561 (destructor)unicode_dealloc, /* tp_dealloc */
14562 0, /* tp_print */
14563 0, /* tp_getattr */
14564 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014565 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014566 unicode_repr, /* tp_repr */
14567 &unicode_as_number, /* tp_as_number */
14568 &unicode_as_sequence, /* tp_as_sequence */
14569 &unicode_as_mapping, /* tp_as_mapping */
14570 (hashfunc) unicode_hash, /* tp_hash*/
14571 0, /* tp_call*/
14572 (reprfunc) unicode_str, /* tp_str */
14573 PyObject_GenericGetAttr, /* tp_getattro */
14574 0, /* tp_setattro */
14575 0, /* tp_as_buffer */
14576 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014577 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014578 unicode_doc, /* tp_doc */
14579 0, /* tp_traverse */
14580 0, /* tp_clear */
14581 PyUnicode_RichCompare, /* tp_richcompare */
14582 0, /* tp_weaklistoffset */
14583 unicode_iter, /* tp_iter */
14584 0, /* tp_iternext */
14585 unicode_methods, /* tp_methods */
14586 0, /* tp_members */
14587 0, /* tp_getset */
14588 &PyBaseObject_Type, /* tp_base */
14589 0, /* tp_dict */
14590 0, /* tp_descr_get */
14591 0, /* tp_descr_set */
14592 0, /* tp_dictoffset */
14593 0, /* tp_init */
14594 0, /* tp_alloc */
14595 unicode_new, /* tp_new */
14596 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014597};
14598
14599/* Initialize the Unicode implementation */
14600
Victor Stinner3a50e702011-10-18 21:21:00 +020014601int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014602{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014603 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014604 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014605 0x000A, /* LINE FEED */
14606 0x000D, /* CARRIAGE RETURN */
14607 0x001C, /* FILE SEPARATOR */
14608 0x001D, /* GROUP SEPARATOR */
14609 0x001E, /* RECORD SEPARATOR */
14610 0x0085, /* NEXT LINE */
14611 0x2028, /* LINE SEPARATOR */
14612 0x2029, /* PARAGRAPH SEPARATOR */
14613 };
14614
Fred Drakee4315f52000-05-09 19:53:39 +000014615 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014616 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014617 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014618 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014619 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014620
Guido van Rossumcacfc072002-05-24 19:01:59 +000014621 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014622 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014623
14624 /* initialize the linebreak bloom filter */
14625 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014626 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014627 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014628
Christian Heimes26532f72013-07-20 14:57:16 +020014629 if (PyType_Ready(&EncodingMapType) < 0)
14630 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014631
Benjamin Petersonc4311282012-10-30 23:21:10 -040014632 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14633 Py_FatalError("Can't initialize field name iterator type");
14634
14635 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14636 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014637
Victor Stinner3a50e702011-10-18 21:21:00 +020014638#ifdef HAVE_MBCS
14639 winver.dwOSVersionInfoSize = sizeof(winver);
14640 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14641 PyErr_SetFromWindowsErr(0);
14642 return -1;
14643 }
14644#endif
14645 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014646}
14647
14648/* Finalize the Unicode implementation */
14649
Christian Heimesa156e092008-02-16 07:38:31 +000014650int
14651PyUnicode_ClearFreeList(void)
14652{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014653 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014654}
14655
Guido van Rossumd57fd912000-03-10 22:53:23 +000014656void
Thomas Wouters78890102000-07-22 19:25:51 +000014657_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014658{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014659 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014660
Serhiy Storchaka05997252013-01-26 12:14:02 +020014661 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014662
Serhiy Storchaka05997252013-01-26 12:14:02 +020014663 for (i = 0; i < 256; i++)
14664 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014665 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014666 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014667}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014668
Walter Dörwald16807132007-05-25 13:52:07 +000014669void
14670PyUnicode_InternInPlace(PyObject **p)
14671{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014672 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014673 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014674#ifdef Py_DEBUG
14675 assert(s != NULL);
14676 assert(_PyUnicode_CHECK(s));
14677#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014678 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014679 return;
14680#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014681 /* If it's a subclass, we don't really know what putting
14682 it in the interned dict might do. */
14683 if (!PyUnicode_CheckExact(s))
14684 return;
14685 if (PyUnicode_CHECK_INTERNED(s))
14686 return;
14687 if (interned == NULL) {
14688 interned = PyDict_New();
14689 if (interned == NULL) {
14690 PyErr_Clear(); /* Don't leave an exception */
14691 return;
14692 }
14693 }
14694 /* It might be that the GetItem call fails even
14695 though the key is present in the dictionary,
14696 namely when this happens during a stack overflow. */
14697 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014698 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014699 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014700
Victor Stinnerf0335102013-04-14 19:13:03 +020014701 if (t) {
14702 Py_INCREF(t);
14703 Py_DECREF(*p);
14704 *p = t;
14705 return;
14706 }
Walter Dörwald16807132007-05-25 13:52:07 +000014707
Benjamin Peterson14339b62009-01-31 16:36:08 +000014708 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014709 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014710 PyErr_Clear();
14711 PyThreadState_GET()->recursion_critical = 0;
14712 return;
14713 }
14714 PyThreadState_GET()->recursion_critical = 0;
14715 /* The two references in interned are not counted by refcnt.
14716 The deallocator will take care of this */
14717 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014718 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014719}
14720
14721void
14722PyUnicode_InternImmortal(PyObject **p)
14723{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014724 PyUnicode_InternInPlace(p);
14725 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014726 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014727 Py_INCREF(*p);
14728 }
Walter Dörwald16807132007-05-25 13:52:07 +000014729}
14730
14731PyObject *
14732PyUnicode_InternFromString(const char *cp)
14733{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014734 PyObject *s = PyUnicode_FromString(cp);
14735 if (s == NULL)
14736 return NULL;
14737 PyUnicode_InternInPlace(&s);
14738 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014739}
14740
Alexander Belopolsky40018472011-02-26 01:02:56 +000014741void
14742_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014743{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014744 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014745 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014746 Py_ssize_t i, n;
14747 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014748
Benjamin Peterson14339b62009-01-31 16:36:08 +000014749 if (interned == NULL || !PyDict_Check(interned))
14750 return;
14751 keys = PyDict_Keys(interned);
14752 if (keys == NULL || !PyList_Check(keys)) {
14753 PyErr_Clear();
14754 return;
14755 }
Walter Dörwald16807132007-05-25 13:52:07 +000014756
Benjamin Peterson14339b62009-01-31 16:36:08 +000014757 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14758 detector, interned unicode strings are not forcibly deallocated;
14759 rather, we give them their stolen references back, and then clear
14760 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014761
Benjamin Peterson14339b62009-01-31 16:36:08 +000014762 n = PyList_GET_SIZE(keys);
14763 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014764 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014765 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014766 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014767 if (PyUnicode_READY(s) == -1) {
14768 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014769 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014771 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014772 case SSTATE_NOT_INTERNED:
14773 /* XXX Shouldn't happen */
14774 break;
14775 case SSTATE_INTERNED_IMMORTAL:
14776 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014777 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014778 break;
14779 case SSTATE_INTERNED_MORTAL:
14780 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014781 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014782 break;
14783 default:
14784 Py_FatalError("Inconsistent interned string state.");
14785 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014786 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014787 }
14788 fprintf(stderr, "total size of all interned strings: "
14789 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14790 "mortal/immortal\n", mortal_size, immortal_size);
14791 Py_DECREF(keys);
14792 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014793 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014794}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014795
14796
14797/********************* Unicode Iterator **************************/
14798
14799typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014800 PyObject_HEAD
14801 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014802 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014803} unicodeiterobject;
14804
14805static void
14806unicodeiter_dealloc(unicodeiterobject *it)
14807{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014808 _PyObject_GC_UNTRACK(it);
14809 Py_XDECREF(it->it_seq);
14810 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014811}
14812
14813static int
14814unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14815{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014816 Py_VISIT(it->it_seq);
14817 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014818}
14819
14820static PyObject *
14821unicodeiter_next(unicodeiterobject *it)
14822{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014823 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014824
Benjamin Peterson14339b62009-01-31 16:36:08 +000014825 assert(it != NULL);
14826 seq = it->it_seq;
14827 if (seq == NULL)
14828 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014829 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014831 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14832 int kind = PyUnicode_KIND(seq);
14833 void *data = PyUnicode_DATA(seq);
14834 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14835 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014836 if (item != NULL)
14837 ++it->it_index;
14838 return item;
14839 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014840
Benjamin Peterson14339b62009-01-31 16:36:08 +000014841 Py_DECREF(seq);
14842 it->it_seq = NULL;
14843 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014844}
14845
14846static PyObject *
14847unicodeiter_len(unicodeiterobject *it)
14848{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014849 Py_ssize_t len = 0;
14850 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014851 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014852 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014853}
14854
14855PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14856
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014857static PyObject *
14858unicodeiter_reduce(unicodeiterobject *it)
14859{
14860 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014861 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014862 it->it_seq, it->it_index);
14863 } else {
14864 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14865 if (u == NULL)
14866 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014867 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014868 }
14869}
14870
14871PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14872
14873static PyObject *
14874unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14875{
14876 Py_ssize_t index = PyLong_AsSsize_t(state);
14877 if (index == -1 && PyErr_Occurred())
14878 return NULL;
14879 if (index < 0)
14880 index = 0;
14881 it->it_index = index;
14882 Py_RETURN_NONE;
14883}
14884
14885PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14886
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014887static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014888 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014889 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014890 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14891 reduce_doc},
14892 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14893 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014894 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014895};
14896
14897PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014898 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14899 "str_iterator", /* tp_name */
14900 sizeof(unicodeiterobject), /* tp_basicsize */
14901 0, /* tp_itemsize */
14902 /* methods */
14903 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14904 0, /* tp_print */
14905 0, /* tp_getattr */
14906 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014907 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014908 0, /* tp_repr */
14909 0, /* tp_as_number */
14910 0, /* tp_as_sequence */
14911 0, /* tp_as_mapping */
14912 0, /* tp_hash */
14913 0, /* tp_call */
14914 0, /* tp_str */
14915 PyObject_GenericGetAttr, /* tp_getattro */
14916 0, /* tp_setattro */
14917 0, /* tp_as_buffer */
14918 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14919 0, /* tp_doc */
14920 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14921 0, /* tp_clear */
14922 0, /* tp_richcompare */
14923 0, /* tp_weaklistoffset */
14924 PyObject_SelfIter, /* tp_iter */
14925 (iternextfunc)unicodeiter_next, /* tp_iternext */
14926 unicodeiter_methods, /* tp_methods */
14927 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014928};
14929
14930static PyObject *
14931unicode_iter(PyObject *seq)
14932{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014933 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014934
Benjamin Peterson14339b62009-01-31 16:36:08 +000014935 if (!PyUnicode_Check(seq)) {
14936 PyErr_BadInternalCall();
14937 return NULL;
14938 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014939 if (PyUnicode_READY(seq) == -1)
14940 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14942 if (it == NULL)
14943 return NULL;
14944 it->it_index = 0;
14945 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014946 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014947 _PyObject_GC_TRACK(it);
14948 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014949}
14950
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014951
14952size_t
14953Py_UNICODE_strlen(const Py_UNICODE *u)
14954{
14955 int res = 0;
14956 while(*u++)
14957 res++;
14958 return res;
14959}
14960
14961Py_UNICODE*
14962Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14963{
14964 Py_UNICODE *u = s1;
14965 while ((*u++ = *s2++));
14966 return s1;
14967}
14968
14969Py_UNICODE*
14970Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14971{
14972 Py_UNICODE *u = s1;
14973 while ((*u++ = *s2++))
14974 if (n-- == 0)
14975 break;
14976 return s1;
14977}
14978
14979Py_UNICODE*
14980Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14981{
14982 Py_UNICODE *u1 = s1;
14983 u1 += Py_UNICODE_strlen(u1);
14984 Py_UNICODE_strcpy(u1, s2);
14985 return s1;
14986}
14987
14988int
14989Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14990{
14991 while (*s1 && *s2 && *s1 == *s2)
14992 s1++, s2++;
14993 if (*s1 && *s2)
14994 return (*s1 < *s2) ? -1 : +1;
14995 if (*s1)
14996 return 1;
14997 if (*s2)
14998 return -1;
14999 return 0;
15000}
15001
15002int
15003Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15004{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015005 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015006 for (; n != 0; n--) {
15007 u1 = *s1;
15008 u2 = *s2;
15009 if (u1 != u2)
15010 return (u1 < u2) ? -1 : +1;
15011 if (u1 == '\0')
15012 return 0;
15013 s1++;
15014 s2++;
15015 }
15016 return 0;
15017}
15018
15019Py_UNICODE*
15020Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15021{
15022 const Py_UNICODE *p;
15023 for (p = s; *p; p++)
15024 if (*p == c)
15025 return (Py_UNICODE*)p;
15026 return NULL;
15027}
15028
15029Py_UNICODE*
15030Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15031{
15032 const Py_UNICODE *p;
15033 p = s + Py_UNICODE_strlen(s);
15034 while (p != s) {
15035 p--;
15036 if (*p == c)
15037 return (Py_UNICODE*)p;
15038 }
15039 return NULL;
15040}
Victor Stinner331ea922010-08-10 16:37:20 +000015041
Victor Stinner71133ff2010-09-01 23:43:53 +000015042Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015043PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015044{
Victor Stinner577db2c2011-10-11 22:12:48 +020015045 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015046 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015048 if (!PyUnicode_Check(unicode)) {
15049 PyErr_BadArgument();
15050 return NULL;
15051 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015052 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015053 if (u == NULL)
15054 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015055 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015056 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015057 PyErr_NoMemory();
15058 return NULL;
15059 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015060 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015061 size *= sizeof(Py_UNICODE);
15062 copy = PyMem_Malloc(size);
15063 if (copy == NULL) {
15064 PyErr_NoMemory();
15065 return NULL;
15066 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015067 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015068 return copy;
15069}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015070
Georg Brandl66c221e2010-10-14 07:04:07 +000015071/* A _string module, to export formatter_parser and formatter_field_name_split
15072 to the string.Formatter class implemented in Python. */
15073
15074static PyMethodDef _string_methods[] = {
15075 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15076 METH_O, PyDoc_STR("split the argument as a field name")},
15077 {"formatter_parser", (PyCFunction) formatter_parser,
15078 METH_O, PyDoc_STR("parse the argument as a format string")},
15079 {NULL, NULL}
15080};
15081
15082static struct PyModuleDef _string_module = {
15083 PyModuleDef_HEAD_INIT,
15084 "_string",
15085 PyDoc_STR("string helper module"),
15086 0,
15087 _string_methods,
15088 NULL,
15089 NULL,
15090 NULL,
15091 NULL
15092};
15093
15094PyMODINIT_FUNC
15095PyInit__string(void)
15096{
15097 return PyModule_Create(&_string_module);
15098}
15099
15100
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015101#ifdef __cplusplus
15102}
15103#endif