blob: 880889e8a29cf9513cd8ff308486feb9659a5c1e [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 { \
Victor Stinner4a587072013-11-19 12:54:53 +0100143 to_type *_to = (to_type *)(to); \
144 const from_type *_iter = (from_type *)(begin); \
145 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200146 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);
Victor Stinner68b674c2013-10-29 19:31:43 +0100899
900 _PyUnicode_WSTR_LENGTH(unicode) = length;
901 _PyUnicode_HASH(unicode) = -1;
902 _PyUnicode_STATE(unicode).interned = 0;
903 _PyUnicode_STATE(unicode).kind = 0;
904 _PyUnicode_STATE(unicode).compact = 0;
905 _PyUnicode_STATE(unicode).ready = 0;
906 _PyUnicode_STATE(unicode).ascii = 0;
907 _PyUnicode_DATA_ANY(unicode) = NULL;
908 _PyUnicode_LENGTH(unicode) = 0;
909 _PyUnicode_UTF8(unicode) = NULL;
910 _PyUnicode_UTF8_LENGTH(unicode) = 0;
911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
913 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100914 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000915 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100916 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000917 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200918
Jeremy Hyltond8082792003-09-16 19:41:39 +0000919 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000920 * the caller fails before initializing str -- unicode_resize()
921 * reads str[0], and the Keep-Alive optimization can keep memory
922 * allocated for str alive across a call to unicode_dealloc(unicode).
923 * We don't want unicode_resize to read uninitialized memory in
924 * that case.
925 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200926 _PyUnicode_WSTR(unicode)[0] = 0;
927 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100928
Victor Stinner7931d9a2011-11-04 00:22:48 +0100929 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000930 return unicode;
931}
932
Victor Stinnerf42dc442011-10-02 23:33:16 +0200933static const char*
934unicode_kind_name(PyObject *unicode)
935{
Victor Stinner42dfd712011-10-03 14:41:45 +0200936 /* don't check consistency: unicode_kind_name() is called from
937 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200938 if (!PyUnicode_IS_COMPACT(unicode))
939 {
940 if (!PyUnicode_IS_READY(unicode))
941 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600942 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 {
944 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200945 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200946 return "legacy ascii";
947 else
948 return "legacy latin1";
949 case PyUnicode_2BYTE_KIND:
950 return "legacy UCS2";
951 case PyUnicode_4BYTE_KIND:
952 return "legacy UCS4";
953 default:
954 return "<legacy invalid kind>";
955 }
956 }
957 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600958 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200959 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200960 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200961 return "ascii";
962 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200963 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200965 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200966 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200967 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200968 default:
969 return "<invalid compact kind>";
970 }
971}
972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200973#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974/* Functions wrapping macros for use in debugger */
975char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200976 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977}
978
979void *_PyUnicode_compact_data(void *unicode) {
980 return _PyUnicode_COMPACT_DATA(unicode);
981}
982void *_PyUnicode_data(void *unicode){
983 printf("obj %p\n", unicode);
984 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
985 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
986 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
987 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
988 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
989 return PyUnicode_DATA(unicode);
990}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200991
992void
993_PyUnicode_Dump(PyObject *op)
994{
995 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200996 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
997 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
998 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200999
Victor Stinnera849a4b2011-10-03 12:12:11 +02001000 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001001 {
1002 if (ascii->state.ascii)
1003 data = (ascii + 1);
1004 else
1005 data = (compact + 1);
1006 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001007 else
1008 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +02001009 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
1010
Victor Stinnera849a4b2011-10-03 12:12:11 +02001011 if (ascii->wstr == data)
1012 printf("shared ");
1013 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001014
Victor Stinnera3b334d2011-10-03 13:53:37 +02001015 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +02001016 printf(" (%zu), ", compact->wstr_length);
1017 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1018 printf("shared ");
1019 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001020 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001021 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001022}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001023#endif
1024
1025PyObject *
1026PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1027{
1028 PyObject *obj;
1029 PyCompactUnicodeObject *unicode;
1030 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001031 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001032 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033 Py_ssize_t char_size;
1034 Py_ssize_t struct_size;
1035
1036 /* Optimization for empty strings */
1037 if (size == 0 && unicode_empty != NULL) {
1038 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001039 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 }
1041
Victor Stinner9e9d6892011-10-04 01:02:02 +02001042 is_ascii = 0;
1043 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 struct_size = sizeof(PyCompactUnicodeObject);
1045 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001046 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 char_size = 1;
1048 is_ascii = 1;
1049 struct_size = sizeof(PyASCIIObject);
1050 }
1051 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001052 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001053 char_size = 1;
1054 }
1055 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001056 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057 char_size = 2;
1058 if (sizeof(wchar_t) == 2)
1059 is_sharing = 1;
1060 }
1061 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001062 if (maxchar > MAX_UNICODE) {
1063 PyErr_SetString(PyExc_SystemError,
1064 "invalid maximum character passed to PyUnicode_New");
1065 return NULL;
1066 }
Victor Stinner8f825062012-04-27 13:55:39 +02001067 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 char_size = 4;
1069 if (sizeof(wchar_t) == 4)
1070 is_sharing = 1;
1071 }
1072
1073 /* Ensure we won't overflow the size. */
1074 if (size < 0) {
1075 PyErr_SetString(PyExc_SystemError,
1076 "Negative size passed to PyUnicode_New");
1077 return NULL;
1078 }
1079 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1080 return PyErr_NoMemory();
1081
1082 /* Duplicated allocation code from _PyObject_New() instead of a call to
1083 * PyObject_New() so we are able to allocate space for the object and
1084 * it's data buffer.
1085 */
1086 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1087 if (obj == NULL)
1088 return PyErr_NoMemory();
1089 obj = PyObject_INIT(obj, &PyUnicode_Type);
1090 if (obj == NULL)
1091 return NULL;
1092
1093 unicode = (PyCompactUnicodeObject *)obj;
1094 if (is_ascii)
1095 data = ((PyASCIIObject*)obj) + 1;
1096 else
1097 data = unicode + 1;
1098 _PyUnicode_LENGTH(unicode) = size;
1099 _PyUnicode_HASH(unicode) = -1;
1100 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001101 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001102 _PyUnicode_STATE(unicode).compact = 1;
1103 _PyUnicode_STATE(unicode).ready = 1;
1104 _PyUnicode_STATE(unicode).ascii = is_ascii;
1105 if (is_ascii) {
1106 ((char*)data)[size] = 0;
1107 _PyUnicode_WSTR(unicode) = NULL;
1108 }
Victor Stinner8f825062012-04-27 13:55:39 +02001109 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110 ((char*)data)[size] = 0;
1111 _PyUnicode_WSTR(unicode) = NULL;
1112 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001113 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001114 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001115 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 else {
1117 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001118 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001119 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001121 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001122 ((Py_UCS4*)data)[size] = 0;
1123 if (is_sharing) {
1124 _PyUnicode_WSTR_LENGTH(unicode) = size;
1125 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1126 }
1127 else {
1128 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1129 _PyUnicode_WSTR(unicode) = NULL;
1130 }
1131 }
Victor Stinner8f825062012-04-27 13:55:39 +02001132#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001133 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001134#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001135 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001136 return obj;
1137}
1138
1139#if SIZEOF_WCHAR_T == 2
1140/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1141 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001142 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143
1144 This function assumes that unicode can hold one more code point than wstr
1145 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001146static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001148 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149{
1150 const wchar_t *iter;
1151 Py_UCS4 *ucs4_out;
1152
Victor Stinner910337b2011-10-03 03:20:16 +02001153 assert(unicode != NULL);
1154 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001155 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1156 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1157
1158 for (iter = begin; iter < end; ) {
1159 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1160 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001161 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1162 && (iter+1) < end
1163 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001164 {
Victor Stinner551ac952011-11-29 22:58:13 +01001165 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166 iter += 2;
1167 }
1168 else {
1169 *ucs4_out++ = *iter;
1170 iter++;
1171 }
1172 }
1173 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1174 _PyUnicode_GET_LENGTH(unicode)));
1175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176}
1177#endif
1178
Victor Stinnercd9950f2011-10-02 00:34:53 +02001179static int
Victor Stinner488fa492011-12-12 00:01:39 +01001180unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001181{
Victor Stinner488fa492011-12-12 00:01:39 +01001182 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001183 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001184 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001185 return -1;
1186 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001187 return 0;
1188}
1189
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001190static int
1191_copy_characters(PyObject *to, Py_ssize_t to_start,
1192 PyObject *from, Py_ssize_t from_start,
1193 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001194{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001195 unsigned int from_kind, to_kind;
1196 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001197
Victor Stinneree4544c2012-05-09 22:24:08 +02001198 assert(0 <= how_many);
1199 assert(0 <= from_start);
1200 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001201 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001202 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001203 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204
Victor Stinnerd3f08822012-05-29 12:57:52 +02001205 assert(PyUnicode_Check(to));
1206 assert(PyUnicode_IS_READY(to));
1207 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1208
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001209 if (how_many == 0)
1210 return 0;
1211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001212 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001213 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001214 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001215 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216
Victor Stinnerf1852262012-06-16 16:38:26 +02001217#ifdef Py_DEBUG
1218 if (!check_maxchar
1219 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1220 {
1221 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1222 Py_UCS4 ch;
1223 Py_ssize_t i;
1224 for (i=0; i < how_many; i++) {
1225 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1226 assert(ch <= to_maxchar);
1227 }
1228 }
1229#endif
1230
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001231 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001232 if (check_maxchar
1233 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1234 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001235 /* Writing Latin-1 characters into an ASCII string requires to
1236 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001237 Py_UCS4 max_char;
1238 max_char = ucs1lib_find_max_char(from_data,
1239 (Py_UCS1*)from_data + how_many);
1240 if (max_char >= 128)
1241 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001242 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001243 Py_MEMCPY((char*)to_data + to_kind * to_start,
1244 (char*)from_data + from_kind * from_start,
1245 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001246 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001247 else if (from_kind == PyUnicode_1BYTE_KIND
1248 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001249 {
1250 _PyUnicode_CONVERT_BYTES(
1251 Py_UCS1, Py_UCS2,
1252 PyUnicode_1BYTE_DATA(from) + from_start,
1253 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1254 PyUnicode_2BYTE_DATA(to) + to_start
1255 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001256 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001257 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001258 && to_kind == PyUnicode_4BYTE_KIND)
1259 {
1260 _PyUnicode_CONVERT_BYTES(
1261 Py_UCS1, Py_UCS4,
1262 PyUnicode_1BYTE_DATA(from) + from_start,
1263 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1264 PyUnicode_4BYTE_DATA(to) + to_start
1265 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001266 }
1267 else if (from_kind == PyUnicode_2BYTE_KIND
1268 && to_kind == PyUnicode_4BYTE_KIND)
1269 {
1270 _PyUnicode_CONVERT_BYTES(
1271 Py_UCS2, Py_UCS4,
1272 PyUnicode_2BYTE_DATA(from) + from_start,
1273 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1274 PyUnicode_4BYTE_DATA(to) + to_start
1275 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001276 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001277 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001278 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1279
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001280 if (!check_maxchar) {
1281 if (from_kind == PyUnicode_2BYTE_KIND
1282 && to_kind == PyUnicode_1BYTE_KIND)
1283 {
1284 _PyUnicode_CONVERT_BYTES(
1285 Py_UCS2, Py_UCS1,
1286 PyUnicode_2BYTE_DATA(from) + from_start,
1287 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1288 PyUnicode_1BYTE_DATA(to) + to_start
1289 );
1290 }
1291 else if (from_kind == PyUnicode_4BYTE_KIND
1292 && to_kind == PyUnicode_1BYTE_KIND)
1293 {
1294 _PyUnicode_CONVERT_BYTES(
1295 Py_UCS4, Py_UCS1,
1296 PyUnicode_4BYTE_DATA(from) + from_start,
1297 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1298 PyUnicode_1BYTE_DATA(to) + to_start
1299 );
1300 }
1301 else if (from_kind == PyUnicode_4BYTE_KIND
1302 && to_kind == PyUnicode_2BYTE_KIND)
1303 {
1304 _PyUnicode_CONVERT_BYTES(
1305 Py_UCS4, Py_UCS2,
1306 PyUnicode_4BYTE_DATA(from) + from_start,
1307 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1308 PyUnicode_2BYTE_DATA(to) + to_start
1309 );
1310 }
1311 else {
1312 assert(0);
1313 return -1;
1314 }
1315 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001316 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001317 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001318 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001319 Py_ssize_t i;
1320
Victor Stinnera0702ab2011-09-29 14:14:38 +02001321 for (i=0; i < how_many; i++) {
1322 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001323 if (ch > to_maxchar)
1324 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001325 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1326 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001327 }
1328 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001329 return 0;
1330}
1331
Victor Stinnerd3f08822012-05-29 12:57:52 +02001332void
1333_PyUnicode_FastCopyCharacters(
1334 PyObject *to, Py_ssize_t to_start,
1335 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001336{
1337 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1338}
1339
1340Py_ssize_t
1341PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1342 PyObject *from, Py_ssize_t from_start,
1343 Py_ssize_t how_many)
1344{
1345 int err;
1346
1347 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1348 PyErr_BadInternalCall();
1349 return -1;
1350 }
1351
Benjamin Petersonbac79492012-01-14 13:34:47 -05001352 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001353 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001354 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001355 return -1;
1356
Victor Stinnerd3f08822012-05-29 12:57:52 +02001357 if (from_start < 0) {
1358 PyErr_SetString(PyExc_IndexError, "string index out of range");
1359 return -1;
1360 }
1361 if (to_start < 0) {
1362 PyErr_SetString(PyExc_IndexError, "string index out of range");
1363 return -1;
1364 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001365 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1366 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1367 PyErr_Format(PyExc_SystemError,
1368 "Cannot write %zi characters at %zi "
1369 "in a string of %zi characters",
1370 how_many, to_start, PyUnicode_GET_LENGTH(to));
1371 return -1;
1372 }
1373
1374 if (how_many == 0)
1375 return 0;
1376
Victor Stinner488fa492011-12-12 00:01:39 +01001377 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001378 return -1;
1379
1380 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1381 if (err) {
1382 PyErr_Format(PyExc_SystemError,
1383 "Cannot copy %s characters "
1384 "into a string of %s characters",
1385 unicode_kind_name(from),
1386 unicode_kind_name(to));
1387 return -1;
1388 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001389 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390}
1391
Victor Stinner17222162011-09-28 22:15:37 +02001392/* Find the maximum code point and count the number of surrogate pairs so a
1393 correct string length can be computed before converting a string to UCS4.
1394 This function counts single surrogates as a character and not as a pair.
1395
1396 Return 0 on success, or -1 on error. */
1397static int
1398find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1399 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400{
1401 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001402 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403
Victor Stinnerc53be962011-10-02 21:33:54 +02001404 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 *num_surrogates = 0;
1406 *maxchar = 0;
1407
1408 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001410 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1411 && (iter+1) < end
1412 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1413 {
1414 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1415 ++(*num_surrogates);
1416 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001417 }
1418 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001420 {
1421 ch = *iter;
1422 iter++;
1423 }
1424 if (ch > *maxchar) {
1425 *maxchar = ch;
1426 if (*maxchar > MAX_UNICODE) {
1427 PyErr_Format(PyExc_ValueError,
1428 "character U+%x is not in range [U+0000; U+10ffff]",
1429 ch);
1430 return -1;
1431 }
1432 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 }
1434 return 0;
1435}
1436
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001437int
1438_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439{
1440 wchar_t *end;
1441 Py_UCS4 maxchar = 0;
1442 Py_ssize_t num_surrogates;
1443#if SIZEOF_WCHAR_T == 2
1444 Py_ssize_t length_wo_surrogates;
1445#endif
1446
Georg Brandl7597add2011-10-05 16:36:47 +02001447 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001448 strings were created using _PyObject_New() and where no canonical
1449 representation (the str field) has been set yet aka strings
1450 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001451 assert(_PyUnicode_CHECK(unicode));
1452 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001454 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001455 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001456 /* Actually, it should neither be interned nor be anything else: */
1457 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001460 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001461 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463
1464 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001465 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1466 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 PyErr_NoMemory();
1468 return -1;
1469 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001470 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001471 _PyUnicode_WSTR(unicode), end,
1472 PyUnicode_1BYTE_DATA(unicode));
1473 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1474 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1475 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1476 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001477 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001478 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001479 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001480 }
1481 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001482 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001483 _PyUnicode_UTF8(unicode) = NULL;
1484 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001485 }
1486 PyObject_FREE(_PyUnicode_WSTR(unicode));
1487 _PyUnicode_WSTR(unicode) = NULL;
1488 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1489 }
1490 /* In this case we might have to convert down from 4-byte native
1491 wchar_t to 2-byte unicode. */
1492 else if (maxchar < 65536) {
1493 assert(num_surrogates == 0 &&
1494 "FindMaxCharAndNumSurrogatePairs() messed up");
1495
Victor Stinner506f5922011-09-28 22:34:18 +02001496#if SIZEOF_WCHAR_T == 2
1497 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001498 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001499 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1500 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1501 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001502 _PyUnicode_UTF8(unicode) = NULL;
1503 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001504#else
1505 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001506 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001507 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001508 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001509 PyErr_NoMemory();
1510 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001511 }
Victor Stinner506f5922011-09-28 22:34:18 +02001512 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1513 _PyUnicode_WSTR(unicode), end,
1514 PyUnicode_2BYTE_DATA(unicode));
1515 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1516 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1517 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001518 _PyUnicode_UTF8(unicode) = NULL;
1519 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001520 PyObject_FREE(_PyUnicode_WSTR(unicode));
1521 _PyUnicode_WSTR(unicode) = NULL;
1522 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1523#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001524 }
1525 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1526 else {
1527#if SIZEOF_WCHAR_T == 2
1528 /* in case the native representation is 2-bytes, we need to allocate a
1529 new normalized 4-byte version. */
1530 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001531 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1532 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001533 PyErr_NoMemory();
1534 return -1;
1535 }
1536 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1537 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001538 _PyUnicode_UTF8(unicode) = NULL;
1539 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001540 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1541 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001542 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 PyObject_FREE(_PyUnicode_WSTR(unicode));
1544 _PyUnicode_WSTR(unicode) = NULL;
1545 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1546#else
1547 assert(num_surrogates == 0);
1548
Victor Stinnerc3c74152011-10-02 20:39:55 +02001549 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001551 _PyUnicode_UTF8(unicode) = NULL;
1552 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001553 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1554#endif
1555 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1556 }
1557 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001558 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001559 return 0;
1560}
1561
Alexander Belopolsky40018472011-02-26 01:02:56 +00001562static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001563unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001564{
Walter Dörwald16807132007-05-25 13:52:07 +00001565 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001566 case SSTATE_NOT_INTERNED:
1567 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001568
Benjamin Peterson29060642009-01-31 22:14:21 +00001569 case SSTATE_INTERNED_MORTAL:
1570 /* revive dead object temporarily for DelItem */
1571 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001572 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 Py_FatalError(
1574 "deletion of interned string failed");
1575 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001576
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 case SSTATE_INTERNED_IMMORTAL:
1578 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001579
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 default:
1581 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001582 }
1583
Victor Stinner03490912011-10-03 23:45:12 +02001584 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001586 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001587 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001588 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1589 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001590
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001591 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001592}
1593
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001594#ifdef Py_DEBUG
1595static int
1596unicode_is_singleton(PyObject *unicode)
1597{
1598 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1599 if (unicode == unicode_empty)
1600 return 1;
1601 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1602 {
1603 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1604 if (ch < 256 && unicode_latin1[ch] == unicode)
1605 return 1;
1606 }
1607 return 0;
1608}
1609#endif
1610
Alexander Belopolsky40018472011-02-26 01:02:56 +00001611static int
Victor Stinner488fa492011-12-12 00:01:39 +01001612unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001613{
Victor Stinner488fa492011-12-12 00:01:39 +01001614 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001615 if (Py_REFCNT(unicode) != 1)
1616 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001617 if (_PyUnicode_HASH(unicode) != -1)
1618 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001619 if (PyUnicode_CHECK_INTERNED(unicode))
1620 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001621 if (!PyUnicode_CheckExact(unicode))
1622 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001623#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001624 /* singleton refcount is greater than 1 */
1625 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001626#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001627 return 1;
1628}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001629
Victor Stinnerfe226c02011-10-03 03:52:20 +02001630static int
1631unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1632{
1633 PyObject *unicode;
1634 Py_ssize_t old_length;
1635
1636 assert(p_unicode != NULL);
1637 unicode = *p_unicode;
1638
1639 assert(unicode != NULL);
1640 assert(PyUnicode_Check(unicode));
1641 assert(0 <= length);
1642
Victor Stinner910337b2011-10-03 03:20:16 +02001643 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001644 old_length = PyUnicode_WSTR_LENGTH(unicode);
1645 else
1646 old_length = PyUnicode_GET_LENGTH(unicode);
1647 if (old_length == length)
1648 return 0;
1649
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001650 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001651 _Py_INCREF_UNICODE_EMPTY();
1652 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001653 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001654 Py_DECREF(*p_unicode);
1655 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001656 return 0;
1657 }
1658
Victor Stinner488fa492011-12-12 00:01:39 +01001659 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001660 PyObject *copy = resize_copy(unicode, length);
1661 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001662 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001663 Py_DECREF(*p_unicode);
1664 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001665 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001666 }
1667
Victor Stinnerfe226c02011-10-03 03:52:20 +02001668 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001669 PyObject *new_unicode = resize_compact(unicode, length);
1670 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001671 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001672 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001673 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001674 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001675 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001676}
1677
Alexander Belopolsky40018472011-02-26 01:02:56 +00001678int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001679PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001680{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001681 PyObject *unicode;
1682 if (p_unicode == NULL) {
1683 PyErr_BadInternalCall();
1684 return -1;
1685 }
1686 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001687 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001688 {
1689 PyErr_BadInternalCall();
1690 return -1;
1691 }
1692 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001693}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001694
Victor Stinnerc5166102012-02-22 13:55:02 +01001695/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001696
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001697 WARNING: The function doesn't copy the terminating null character and
1698 doesn't check the maximum character (may write a latin1 character in an
1699 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001700static void
1701unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1702 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001703{
1704 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1705 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001706 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001707
1708 switch (kind) {
1709 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001710 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001711#ifdef Py_DEBUG
1712 if (PyUnicode_IS_ASCII(unicode)) {
1713 Py_UCS4 maxchar = ucs1lib_find_max_char(
1714 (const Py_UCS1*)str,
1715 (const Py_UCS1*)str + len);
1716 assert(maxchar < 128);
1717 }
1718#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001719 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001720 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001721 }
1722 case PyUnicode_2BYTE_KIND: {
1723 Py_UCS2 *start = (Py_UCS2 *)data + index;
1724 Py_UCS2 *ucs2 = start;
1725 assert(index <= PyUnicode_GET_LENGTH(unicode));
1726
Victor Stinner184252a2012-06-16 02:57:41 +02001727 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 *ucs2 = (Py_UCS2)*str;
1729
1730 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001731 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001732 }
1733 default: {
1734 Py_UCS4 *start = (Py_UCS4 *)data + index;
1735 Py_UCS4 *ucs4 = start;
1736 assert(kind == PyUnicode_4BYTE_KIND);
1737 assert(index <= PyUnicode_GET_LENGTH(unicode));
1738
Victor Stinner184252a2012-06-16 02:57:41 +02001739 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001740 *ucs4 = (Py_UCS4)*str;
1741
1742 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001743 }
1744 }
1745}
1746
1747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748static PyObject*
1749get_latin1_char(unsigned char ch)
1750{
Victor Stinnera464fc12011-10-02 20:39:30 +02001751 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001753 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754 if (!unicode)
1755 return NULL;
1756 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001757 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 unicode_latin1[ch] = unicode;
1759 }
1760 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001761 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762}
1763
Alexander Belopolsky40018472011-02-26 01:02:56 +00001764PyObject *
1765PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001767 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768 Py_UCS4 maxchar = 0;
1769 Py_ssize_t num_surrogates;
1770
1771 if (u == NULL)
1772 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001773
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001774 /* If the Unicode data is known at construction time, we can apply
1775 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001777 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001778 if (size == 0)
1779 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001781 /* Single character Unicode objects in the Latin-1 range are
1782 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001783 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001784 return get_latin1_char((unsigned char)*u);
1785
1786 /* If not empty and not single character, copy the Unicode data
1787 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001788 if (find_maxchar_surrogates(u, u + size,
1789 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001790 return NULL;
1791
Victor Stinner8faf8212011-12-08 22:14:11 +01001792 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001793 if (!unicode)
1794 return NULL;
1795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 switch (PyUnicode_KIND(unicode)) {
1797 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001798 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001799 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1800 break;
1801 case PyUnicode_2BYTE_KIND:
1802#if Py_UNICODE_SIZE == 2
1803 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1804#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001805 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1807#endif
1808 break;
1809 case PyUnicode_4BYTE_KIND:
1810#if SIZEOF_WCHAR_T == 2
1811 /* This is the only case which has to process surrogates, thus
1812 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001813 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814#else
1815 assert(num_surrogates == 0);
1816 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1817#endif
1818 break;
1819 default:
1820 assert(0 && "Impossible state");
1821 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001822
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001823 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001824}
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826PyObject *
1827PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001828{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001829 if (size < 0) {
1830 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001831 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001832 return NULL;
1833 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001834 if (u != NULL)
1835 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1836 else
1837 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001838}
1839
Alexander Belopolsky40018472011-02-26 01:02:56 +00001840PyObject *
1841PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001842{
1843 size_t size = strlen(u);
1844 if (size > PY_SSIZE_T_MAX) {
1845 PyErr_SetString(PyExc_OverflowError, "input too long");
1846 return NULL;
1847 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001848 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001849}
1850
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001851PyObject *
1852_PyUnicode_FromId(_Py_Identifier *id)
1853{
1854 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001855 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1856 strlen(id->string),
1857 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001858 if (!id->object)
1859 return NULL;
1860 PyUnicode_InternInPlace(&id->object);
1861 assert(!id->next);
1862 id->next = static_strings;
1863 static_strings = id;
1864 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001865 return id->object;
1866}
1867
1868void
1869_PyUnicode_ClearStaticStrings()
1870{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001871 _Py_Identifier *tmp, *s = static_strings;
1872 while (s) {
1873 Py_DECREF(s->object);
1874 s->object = NULL;
1875 tmp = s->next;
1876 s->next = NULL;
1877 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001878 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001879 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001880}
1881
Benjamin Peterson0df54292012-03-26 14:50:32 -04001882/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001883
Victor Stinnerd3f08822012-05-29 12:57:52 +02001884PyObject*
1885_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001886{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001887 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001888 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001889 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001890#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001891 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001892#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001893 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001894 }
Victor Stinner785938e2011-12-11 20:09:03 +01001895 unicode = PyUnicode_New(size, 127);
1896 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001897 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001898 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1899 assert(_PyUnicode_CheckConsistency(unicode, 1));
1900 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001901}
1902
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001903static Py_UCS4
1904kind_maxchar_limit(unsigned int kind)
1905{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001906 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001907 case PyUnicode_1BYTE_KIND:
1908 return 0x80;
1909 case PyUnicode_2BYTE_KIND:
1910 return 0x100;
1911 case PyUnicode_4BYTE_KIND:
1912 return 0x10000;
1913 default:
1914 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001915 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001916 }
1917}
1918
Victor Stinnere6abb482012-05-02 01:15:40 +02001919Py_LOCAL_INLINE(Py_UCS4)
1920align_maxchar(Py_UCS4 maxchar)
1921{
1922 if (maxchar <= 127)
1923 return 127;
1924 else if (maxchar <= 255)
1925 return 255;
1926 else if (maxchar <= 65535)
1927 return 65535;
1928 else
1929 return MAX_UNICODE;
1930}
1931
Victor Stinner702c7342011-10-05 13:50:52 +02001932static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001933_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001934{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001935 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001936 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001937
Serhiy Storchaka678db842013-01-26 12:16:36 +02001938 if (size == 0)
1939 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001940 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001941 if (size == 1)
1942 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001943
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001944 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001945 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946 if (!res)
1947 return NULL;
1948 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001949 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001951}
1952
Victor Stinnere57b1c02011-09-28 22:20:48 +02001953static PyObject*
1954_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001955{
1956 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001957 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001958
Serhiy Storchaka678db842013-01-26 12:16:36 +02001959 if (size == 0)
1960 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001961 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001962 if (size == 1) {
1963 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001964 int kind;
1965 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001966 if (ch < 256)
1967 return get_latin1_char((unsigned char)ch);
1968
1969 res = PyUnicode_New(1, ch);
1970 if (res == NULL)
1971 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001972 kind = PyUnicode_KIND(res);
1973 data = PyUnicode_DATA(res);
1974 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001975 assert(_PyUnicode_CheckConsistency(res, 1));
1976 return res;
1977 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001978
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001979 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001980 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001981 if (!res)
1982 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001983 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001985 else {
1986 _PyUnicode_CONVERT_BYTES(
1987 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1988 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001989 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990 return res;
1991}
1992
Victor Stinnere57b1c02011-09-28 22:20:48 +02001993static PyObject*
1994_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995{
1996 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001998
Serhiy Storchaka678db842013-01-26 12:16:36 +02001999 if (size == 0)
2000 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002001 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002002 if (size == 1) {
2003 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002004 int kind;
2005 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002006 if (ch < 256)
2007 return get_latin1_char((unsigned char)ch);
2008
2009 res = PyUnicode_New(1, ch);
2010 if (res == NULL)
2011 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002012 kind = PyUnicode_KIND(res);
2013 data = PyUnicode_DATA(res);
2014 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002015 assert(_PyUnicode_CheckConsistency(res, 1));
2016 return res;
2017 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002018
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002019 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002020 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021 if (!res)
2022 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002023 if (max_char < 256)
2024 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2025 PyUnicode_1BYTE_DATA(res));
2026 else if (max_char < 0x10000)
2027 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2028 PyUnicode_2BYTE_DATA(res));
2029 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002031 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032 return res;
2033}
2034
2035PyObject*
2036PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2037{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002038 if (size < 0) {
2039 PyErr_SetString(PyExc_ValueError, "size must be positive");
2040 return NULL;
2041 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002042 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002044 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002045 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002046 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002048 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002049 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002050 PyErr_SetString(PyExc_SystemError, "invalid kind");
2051 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053}
2054
Victor Stinnerece58de2012-04-23 23:36:38 +02002055Py_UCS4
2056_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2057{
2058 enum PyUnicode_Kind kind;
2059 void *startptr, *endptr;
2060
2061 assert(PyUnicode_IS_READY(unicode));
2062 assert(0 <= start);
2063 assert(end <= PyUnicode_GET_LENGTH(unicode));
2064 assert(start <= end);
2065
2066 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2067 return PyUnicode_MAX_CHAR_VALUE(unicode);
2068
2069 if (start == end)
2070 return 127;
2071
Victor Stinner94d558b2012-04-27 22:26:58 +02002072 if (PyUnicode_IS_ASCII(unicode))
2073 return 127;
2074
Victor Stinnerece58de2012-04-23 23:36:38 +02002075 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002076 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002077 endptr = (char *)startptr + end * kind;
2078 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002079 switch(kind) {
2080 case PyUnicode_1BYTE_KIND:
2081 return ucs1lib_find_max_char(startptr, endptr);
2082 case PyUnicode_2BYTE_KIND:
2083 return ucs2lib_find_max_char(startptr, endptr);
2084 case PyUnicode_4BYTE_KIND:
2085 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002086 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002087 assert(0);
2088 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002089 }
2090}
2091
Victor Stinner25a4b292011-10-06 12:31:55 +02002092/* Ensure that a string uses the most efficient storage, if it is not the
2093 case: create a new string with of the right kind. Write NULL into *p_unicode
2094 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002095static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002096unicode_adjust_maxchar(PyObject **p_unicode)
2097{
2098 PyObject *unicode, *copy;
2099 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002100 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002101 unsigned int kind;
2102
2103 assert(p_unicode != NULL);
2104 unicode = *p_unicode;
2105 assert(PyUnicode_IS_READY(unicode));
2106 if (PyUnicode_IS_ASCII(unicode))
2107 return;
2108
2109 len = PyUnicode_GET_LENGTH(unicode);
2110 kind = PyUnicode_KIND(unicode);
2111 if (kind == PyUnicode_1BYTE_KIND) {
2112 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002113 max_char = ucs1lib_find_max_char(u, u + len);
2114 if (max_char >= 128)
2115 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002116 }
2117 else if (kind == PyUnicode_2BYTE_KIND) {
2118 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002119 max_char = ucs2lib_find_max_char(u, u + len);
2120 if (max_char >= 256)
2121 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002122 }
2123 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002124 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002125 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002126 max_char = ucs4lib_find_max_char(u, u + len);
2127 if (max_char >= 0x10000)
2128 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002129 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002131 if (copy != NULL)
2132 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002133 Py_DECREF(unicode);
2134 *p_unicode = copy;
2135}
2136
Victor Stinner034f6cf2011-09-30 02:26:44 +02002137PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002138_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002139{
Victor Stinner87af4f22011-11-21 23:03:47 +01002140 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002141 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002142
Victor Stinner034f6cf2011-09-30 02:26:44 +02002143 if (!PyUnicode_Check(unicode)) {
2144 PyErr_BadInternalCall();
2145 return NULL;
2146 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002147 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002149
Victor Stinner87af4f22011-11-21 23:03:47 +01002150 length = PyUnicode_GET_LENGTH(unicode);
2151 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002152 if (!copy)
2153 return NULL;
2154 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2155
Victor Stinner87af4f22011-11-21 23:03:47 +01002156 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2157 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002158 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002159 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002160}
2161
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162
Victor Stinnerbc603d12011-10-02 01:00:40 +02002163/* Widen Unicode objects to larger buffers. Don't write terminating null
2164 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002165
2166void*
2167_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2168{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002169 Py_ssize_t len;
2170 void *result;
2171 unsigned int skind;
2172
Benjamin Petersonbac79492012-01-14 13:34:47 -05002173 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 return NULL;
2175
2176 len = PyUnicode_GET_LENGTH(s);
2177 skind = PyUnicode_KIND(s);
2178 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002179 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180 return NULL;
2181 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002182 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002183 case PyUnicode_2BYTE_KIND:
2184 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2185 if (!result)
2186 return PyErr_NoMemory();
2187 assert(skind == PyUnicode_1BYTE_KIND);
2188 _PyUnicode_CONVERT_BYTES(
2189 Py_UCS1, Py_UCS2,
2190 PyUnicode_1BYTE_DATA(s),
2191 PyUnicode_1BYTE_DATA(s) + len,
2192 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002194 case PyUnicode_4BYTE_KIND:
2195 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2196 if (!result)
2197 return PyErr_NoMemory();
2198 if (skind == PyUnicode_2BYTE_KIND) {
2199 _PyUnicode_CONVERT_BYTES(
2200 Py_UCS2, Py_UCS4,
2201 PyUnicode_2BYTE_DATA(s),
2202 PyUnicode_2BYTE_DATA(s) + len,
2203 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002205 else {
2206 assert(skind == PyUnicode_1BYTE_KIND);
2207 _PyUnicode_CONVERT_BYTES(
2208 Py_UCS1, Py_UCS4,
2209 PyUnicode_1BYTE_DATA(s),
2210 PyUnicode_1BYTE_DATA(s) + len,
2211 result);
2212 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002213 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002214 default:
2215 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 }
Victor Stinner01698042011-10-04 00:04:26 +02002217 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return NULL;
2219}
2220
2221static Py_UCS4*
2222as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2223 int copy_null)
2224{
2225 int kind;
2226 void *data;
2227 Py_ssize_t len, targetlen;
2228 if (PyUnicode_READY(string) == -1)
2229 return NULL;
2230 kind = PyUnicode_KIND(string);
2231 data = PyUnicode_DATA(string);
2232 len = PyUnicode_GET_LENGTH(string);
2233 targetlen = len;
2234 if (copy_null)
2235 targetlen++;
2236 if (!target) {
2237 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2238 PyErr_NoMemory();
2239 return NULL;
2240 }
2241 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2242 if (!target) {
2243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246 }
2247 else {
2248 if (targetsize < targetlen) {
2249 PyErr_Format(PyExc_SystemError,
2250 "string is longer than the buffer");
2251 if (copy_null && 0 < targetsize)
2252 target[0] = 0;
2253 return NULL;
2254 }
2255 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002256 if (kind == PyUnicode_1BYTE_KIND) {
2257 Py_UCS1 *start = (Py_UCS1 *) data;
2258 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002260 else if (kind == PyUnicode_2BYTE_KIND) {
2261 Py_UCS2 *start = (Py_UCS2 *) data;
2262 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2263 }
2264 else {
2265 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268 if (copy_null)
2269 target[len] = 0;
2270 return target;
2271}
2272
2273Py_UCS4*
2274PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2275 int copy_null)
2276{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002277 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 PyErr_BadInternalCall();
2279 return NULL;
2280 }
2281 return as_ucs4(string, target, targetsize, copy_null);
2282}
2283
2284Py_UCS4*
2285PyUnicode_AsUCS4Copy(PyObject *string)
2286{
2287 return as_ucs4(string, NULL, 0, 1);
2288}
2289
2290#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002291
Alexander Belopolsky40018472011-02-26 01:02:56 +00002292PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002293PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002294{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002295 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002296 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002297 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002298 PyErr_BadInternalCall();
2299 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 }
2301
Martin v. Löwis790465f2008-04-05 20:41:37 +00002302 if (size == -1) {
2303 size = wcslen(w);
2304 }
2305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002306 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002307}
2308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002309#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002310
Walter Dörwald346737f2007-05-31 10:44:43 +00002311static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002312makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002313 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002314{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002315 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002316 if (longflag)
2317 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002318 else if (longlongflag) {
2319 /* longlongflag should only ever be nonzero on machines with
2320 HAVE_LONG_LONG defined */
2321#ifdef HAVE_LONG_LONG
2322 char *f = PY_FORMAT_LONG_LONG;
2323 while (*f)
2324 *fmt++ = *f++;
2325#else
2326 /* we shouldn't ever get here */
2327 assert(0);
2328 *fmt++ = 'l';
2329#endif
2330 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002331 else if (size_tflag) {
2332 char *f = PY_FORMAT_SIZE_T;
2333 while (*f)
2334 *fmt++ = *f++;
2335 }
2336 *fmt++ = c;
2337 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002338}
2339
Victor Stinner15a11362012-10-06 23:48:20 +02002340/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002341 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2342 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2343#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002344
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002345static int
2346unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2347 Py_ssize_t width, Py_ssize_t precision)
2348{
2349 Py_ssize_t length, fill, arglen;
2350 Py_UCS4 maxchar;
2351
2352 if (PyUnicode_READY(str) == -1)
2353 return -1;
2354
2355 length = PyUnicode_GET_LENGTH(str);
2356 if ((precision == -1 || precision >= length)
2357 && width <= length)
2358 return _PyUnicodeWriter_WriteStr(writer, str);
2359
2360 if (precision != -1)
2361 length = Py_MIN(precision, length);
2362
2363 arglen = Py_MAX(length, width);
2364 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2365 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2366 else
2367 maxchar = writer->maxchar;
2368
2369 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2370 return -1;
2371
2372 if (width > length) {
2373 fill = width - length;
2374 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2375 return -1;
2376 writer->pos += fill;
2377 }
2378
2379 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2380 str, 0, length);
2381 writer->pos += length;
2382 return 0;
2383}
2384
2385static int
2386unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2387 Py_ssize_t width, Py_ssize_t precision)
2388{
2389 /* UTF-8 */
2390 Py_ssize_t length;
2391 PyObject *unicode;
2392 int res;
2393
2394 length = strlen(str);
2395 if (precision != -1)
2396 length = Py_MIN(length, precision);
2397 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2398 if (unicode == NULL)
2399 return -1;
2400
2401 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2402 Py_DECREF(unicode);
2403 return res;
2404}
2405
Victor Stinner96865452011-03-01 23:44:09 +00002406static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002407unicode_fromformat_arg(_PyUnicodeWriter *writer,
2408 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002409{
Victor Stinnere215d962012-10-06 23:03:36 +02002410 const char *p;
2411 Py_ssize_t len;
2412 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002413 Py_ssize_t width;
2414 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002415 int longflag;
2416 int longlongflag;
2417 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002418 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002419
2420 p = f;
2421 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002422 zeropad = 0;
2423 if (*f == '0') {
2424 zeropad = 1;
2425 f++;
2426 }
Victor Stinner96865452011-03-01 23:44:09 +00002427
2428 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002429 width = -1;
2430 if (Py_ISDIGIT((unsigned)*f)) {
2431 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002432 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002433 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002434 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002435 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002436 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002437 return NULL;
2438 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002440 f++;
2441 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002442 }
2443 precision = -1;
2444 if (*f == '.') {
2445 f++;
2446 if (Py_ISDIGIT((unsigned)*f)) {
2447 precision = (*f - '0');
2448 f++;
2449 while (Py_ISDIGIT((unsigned)*f)) {
2450 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2451 PyErr_SetString(PyExc_ValueError,
2452 "precision too big");
2453 return NULL;
2454 }
2455 precision = (precision * 10) + (*f - '0');
2456 f++;
2457 }
2458 }
Victor Stinner96865452011-03-01 23:44:09 +00002459 if (*f == '%') {
2460 /* "%.3%s" => f points to "3" */
2461 f--;
2462 }
2463 }
2464 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002465 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002466 f--;
2467 }
Victor Stinner96865452011-03-01 23:44:09 +00002468
2469 /* Handle %ld, %lu, %lld and %llu. */
2470 longflag = 0;
2471 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002472 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002473 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002474 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002475 longflag = 1;
2476 ++f;
2477 }
2478#ifdef HAVE_LONG_LONG
2479 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002480 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002481 longlongflag = 1;
2482 f += 2;
2483 }
2484#endif
2485 }
2486 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002487 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002488 size_tflag = 1;
2489 ++f;
2490 }
Victor Stinnere215d962012-10-06 23:03:36 +02002491
2492 if (f[1] == '\0')
2493 writer->overallocate = 0;
2494
2495 switch (*f) {
2496 case 'c':
2497 {
2498 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002499 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002500 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002501 "character argument not in range(0x110000)");
2502 return NULL;
2503 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002504 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002505 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002506 break;
2507 }
2508
2509 case 'i':
2510 case 'd':
2511 case 'u':
2512 case 'x':
2513 {
2514 /* used by sprintf */
2515 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002516 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002517 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002518
2519 if (*f == 'u') {
2520 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2521
2522 if (longflag)
2523 len = sprintf(buffer, fmt,
2524 va_arg(*vargs, unsigned long));
2525#ifdef HAVE_LONG_LONG
2526 else if (longlongflag)
2527 len = sprintf(buffer, fmt,
2528 va_arg(*vargs, unsigned PY_LONG_LONG));
2529#endif
2530 else if (size_tflag)
2531 len = sprintf(buffer, fmt,
2532 va_arg(*vargs, size_t));
2533 else
2534 len = sprintf(buffer, fmt,
2535 va_arg(*vargs, unsigned int));
2536 }
2537 else if (*f == 'x') {
2538 makefmt(fmt, 0, 0, 0, 'x');
2539 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2540 }
2541 else {
2542 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2543
2544 if (longflag)
2545 len = sprintf(buffer, fmt,
2546 va_arg(*vargs, long));
2547#ifdef HAVE_LONG_LONG
2548 else if (longlongflag)
2549 len = sprintf(buffer, fmt,
2550 va_arg(*vargs, PY_LONG_LONG));
2551#endif
2552 else if (size_tflag)
2553 len = sprintf(buffer, fmt,
2554 va_arg(*vargs, Py_ssize_t));
2555 else
2556 len = sprintf(buffer, fmt,
2557 va_arg(*vargs, int));
2558 }
2559 assert(len >= 0);
2560
Victor Stinnere215d962012-10-06 23:03:36 +02002561 if (precision < len)
2562 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002563
2564 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002565 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2566 return NULL;
2567
Victor Stinnere215d962012-10-06 23:03:36 +02002568 if (width > precision) {
2569 Py_UCS4 fillchar;
2570 fill = width - precision;
2571 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002572 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2573 return NULL;
2574 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002575 }
Victor Stinner15a11362012-10-06 23:48:20 +02002576 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002577 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002578 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2579 return NULL;
2580 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002581 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002582
Victor Stinner4a587072013-11-19 12:54:53 +01002583 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2584 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002585 break;
2586 }
2587
2588 case 'p':
2589 {
2590 char number[MAX_LONG_LONG_CHARS];
2591
2592 len = sprintf(number, "%p", va_arg(*vargs, void*));
2593 assert(len >= 0);
2594
2595 /* %p is ill-defined: ensure leading 0x. */
2596 if (number[1] == 'X')
2597 number[1] = 'x';
2598 else if (number[1] != 'x') {
2599 memmove(number + 2, number,
2600 strlen(number) + 1);
2601 number[0] = '0';
2602 number[1] = 'x';
2603 len += 2;
2604 }
2605
Victor Stinner4a587072013-11-19 12:54:53 +01002606 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002607 return NULL;
2608 break;
2609 }
2610
2611 case 's':
2612 {
2613 /* UTF-8 */
2614 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002615 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002616 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002617 break;
2618 }
2619
2620 case 'U':
2621 {
2622 PyObject *obj = va_arg(*vargs, PyObject *);
2623 assert(obj && _PyUnicode_CHECK(obj));
2624
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002625 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002626 return NULL;
2627 break;
2628 }
2629
2630 case 'V':
2631 {
2632 PyObject *obj = va_arg(*vargs, PyObject *);
2633 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002634 if (obj) {
2635 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002636 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002637 return NULL;
2638 }
2639 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002640 assert(str != NULL);
2641 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002642 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002643 }
2644 break;
2645 }
2646
2647 case 'S':
2648 {
2649 PyObject *obj = va_arg(*vargs, PyObject *);
2650 PyObject *str;
2651 assert(obj);
2652 str = PyObject_Str(obj);
2653 if (!str)
2654 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002655 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002656 Py_DECREF(str);
2657 return NULL;
2658 }
2659 Py_DECREF(str);
2660 break;
2661 }
2662
2663 case 'R':
2664 {
2665 PyObject *obj = va_arg(*vargs, PyObject *);
2666 PyObject *repr;
2667 assert(obj);
2668 repr = PyObject_Repr(obj);
2669 if (!repr)
2670 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002671 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002672 Py_DECREF(repr);
2673 return NULL;
2674 }
2675 Py_DECREF(repr);
2676 break;
2677 }
2678
2679 case 'A':
2680 {
2681 PyObject *obj = va_arg(*vargs, PyObject *);
2682 PyObject *ascii;
2683 assert(obj);
2684 ascii = PyObject_ASCII(obj);
2685 if (!ascii)
2686 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002687 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002688 Py_DECREF(ascii);
2689 return NULL;
2690 }
2691 Py_DECREF(ascii);
2692 break;
2693 }
2694
2695 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002696 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002697 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002698 break;
2699
2700 default:
2701 /* if we stumble upon an unknown formatting code, copy the rest
2702 of the format string to the output string. (we cannot just
2703 skip the code, since there's no way to know what's in the
2704 argument list) */
2705 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002706 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002707 return NULL;
2708 f = p+len;
2709 return f;
2710 }
2711
2712 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002713 return f;
2714}
2715
Walter Dörwaldd2034312007-05-18 16:29:38 +00002716PyObject *
2717PyUnicode_FromFormatV(const char *format, va_list vargs)
2718{
Victor Stinnere215d962012-10-06 23:03:36 +02002719 va_list vargs2;
2720 const char *f;
2721 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002722
Victor Stinner8f674cc2013-04-17 23:02:17 +02002723 _PyUnicodeWriter_Init(&writer);
2724 writer.min_length = strlen(format) + 100;
2725 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002726
2727 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2728 Copy it to be able to pass a reference to a subfunction. */
2729 Py_VA_COPY(vargs2, vargs);
2730
2731 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002732 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002733 f = unicode_fromformat_arg(&writer, f, &vargs2);
2734 if (f == NULL)
2735 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002738 const char *p;
2739 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002740
Victor Stinnere215d962012-10-06 23:03:36 +02002741 p = f;
2742 do
2743 {
2744 if ((unsigned char)*p > 127) {
2745 PyErr_Format(PyExc_ValueError,
2746 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2747 "string, got a non-ASCII byte: 0x%02x",
2748 (unsigned char)*p);
2749 return NULL;
2750 }
2751 p++;
2752 }
2753 while (*p != '\0' && *p != '%');
2754 len = p - f;
2755
2756 if (*p == '\0')
2757 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002758
2759 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002760 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002761
2762 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002764 }
Victor Stinnere215d962012-10-06 23:03:36 +02002765 return _PyUnicodeWriter_Finish(&writer);
2766
2767 fail:
2768 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002770}
2771
Walter Dörwaldd2034312007-05-18 16:29:38 +00002772PyObject *
2773PyUnicode_FromFormat(const char *format, ...)
2774{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002775 PyObject* ret;
2776 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002777
2778#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002779 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002780#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002781 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002783 ret = PyUnicode_FromFormatV(format, vargs);
2784 va_end(vargs);
2785 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002786}
2787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002788#ifdef HAVE_WCHAR_H
2789
Victor Stinner5593d8a2010-10-02 11:11:27 +00002790/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2791 convert a Unicode object to a wide character string.
2792
Victor Stinnerd88d9832011-09-06 02:00:05 +02002793 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 character) required to convert the unicode object. Ignore size argument.
2795
Victor Stinnerd88d9832011-09-06 02:00:05 +02002796 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002797 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002798 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002800unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002801 wchar_t *w,
2802 Py_ssize_t size)
2803{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002804 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805 const wchar_t *wstr;
2806
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002807 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002808 if (wstr == NULL)
2809 return -1;
2810
Victor Stinner5593d8a2010-10-02 11:11:27 +00002811 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002812 if (size > res)
2813 size = res + 1;
2814 else
2815 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002816 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002817 return res;
2818 }
2819 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002821}
2822
2823Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002824PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002825 wchar_t *w,
2826 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002827{
2828 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002829 PyErr_BadInternalCall();
2830 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002831 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002832 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002833}
2834
Victor Stinner137c34c2010-09-29 10:25:54 +00002835wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002836PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 Py_ssize_t *size)
2838{
2839 wchar_t* buffer;
2840 Py_ssize_t buflen;
2841
2842 if (unicode == NULL) {
2843 PyErr_BadInternalCall();
2844 return NULL;
2845 }
2846
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002847 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002848 if (buflen == -1)
2849 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002850 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002851 PyErr_NoMemory();
2852 return NULL;
2853 }
2854
Victor Stinner137c34c2010-09-29 10:25:54 +00002855 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2856 if (buffer == NULL) {
2857 PyErr_NoMemory();
2858 return NULL;
2859 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002860 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002861 if (buflen == -1) {
2862 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002863 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002864 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002865 if (size != NULL)
2866 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002867 return buffer;
2868}
2869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002871
Alexander Belopolsky40018472011-02-26 01:02:56 +00002872PyObject *
2873PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002874{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002875 PyObject *v;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002876 void *data;
2877 int kind;
2878
Victor Stinner8faf8212011-12-08 22:14:11 +01002879 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002880 PyErr_SetString(PyExc_ValueError,
2881 "chr() arg not in range(0x110000)");
2882 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002883 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002884
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002885 if ((Py_UCS4)ordinal < 256)
2886 return get_latin1_char((unsigned char)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002888 v = PyUnicode_New(1, ordinal);
2889 if (v == NULL)
2890 return NULL;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002891 kind = PyUnicode_KIND(v);
2892 data = PyUnicode_DATA(v);
2893 PyUnicode_WRITE(kind, data, 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002894 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002895 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002896}
2897
Alexander Belopolsky40018472011-02-26 01:02:56 +00002898PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002899PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002900{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002901 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002902 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002903 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002904 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002905 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 Py_INCREF(obj);
2907 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002908 }
2909 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002910 /* For a Unicode subtype that's not a Unicode object,
2911 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002912 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002913 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002914 PyErr_Format(PyExc_TypeError,
2915 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002916 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002917 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002918}
2919
Alexander Belopolsky40018472011-02-26 01:02:56 +00002920PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002921PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002922 const char *encoding,
2923 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002924{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002925 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002926 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002927
Guido van Rossumd57fd912000-03-10 22:53:23 +00002928 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002929 PyErr_BadInternalCall();
2930 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002931 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002932
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002933 /* Decoding bytes objects is the most common case and should be fast */
2934 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002935 if (PyBytes_GET_SIZE(obj) == 0)
2936 _Py_RETURN_UNICODE_EMPTY();
2937 v = PyUnicode_Decode(
2938 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2939 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002940 return v;
2941 }
2942
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002943 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002944 PyErr_SetString(PyExc_TypeError,
2945 "decoding str is not supported");
2946 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002947 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002948
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002949 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2950 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2951 PyErr_Format(PyExc_TypeError,
2952 "coercing to str: need bytes, bytearray "
2953 "or buffer-like object, %.80s found",
2954 Py_TYPE(obj)->tp_name);
2955 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002956 }
Tim Petersced69f82003-09-16 20:30:58 +00002957
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002958 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002959 PyBuffer_Release(&buffer);
2960 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002961 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002962
Serhiy Storchaka05997252013-01-26 12:14:02 +02002963 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002964 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002965 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966}
2967
Victor Stinner600d3be2010-06-10 12:00:55 +00002968/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002969 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2970 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002971int
2972_Py_normalize_encoding(const char *encoding,
2973 char *lower,
2974 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002975{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002976 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002977 char *l;
2978 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002979
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002980 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002981 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002982 if (lower_len < 6)
2983 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002984 strcpy(lower, "utf-8");
2985 return 1;
2986 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002987 e = encoding;
2988 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002989 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002990 while (*e) {
2991 if (l == l_end)
2992 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002993 if (Py_ISUPPER(*e)) {
2994 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002995 }
2996 else if (*e == '_') {
2997 *l++ = '-';
2998 e++;
2999 }
3000 else {
3001 *l++ = *e++;
3002 }
3003 }
3004 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003005 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003006}
3007
Alexander Belopolsky40018472011-02-26 01:02:56 +00003008PyObject *
3009PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003010 Py_ssize_t size,
3011 const char *encoding,
3012 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003013{
3014 PyObject *buffer = NULL, *unicode;
3015 Py_buffer info;
3016 char lower[11]; /* Enough for any encoding shortcut */
3017
Fred Drakee4315f52000-05-09 19:53:39 +00003018 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003019 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003020 if ((strcmp(lower, "utf-8") == 0) ||
3021 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003022 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003023 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003024 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003025 (strcmp(lower, "iso-8859-1") == 0) ||
3026 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003027 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003028#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003029 else if (strcmp(lower, "mbcs") == 0)
3030 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003031#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003032 else if (strcmp(lower, "ascii") == 0)
3033 return PyUnicode_DecodeASCII(s, size, errors);
3034 else if (strcmp(lower, "utf-16") == 0)
3035 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3036 else if (strcmp(lower, "utf-32") == 0)
3037 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3038 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003039
3040 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003041 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003042 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003043 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003044 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003045 if (buffer == NULL)
3046 goto onError;
3047 unicode = PyCodec_Decode(buffer, encoding, errors);
3048 if (unicode == NULL)
3049 goto onError;
3050 if (!PyUnicode_Check(unicode)) {
3051 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003052 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3053 "use codecs.decode() to decode to arbitrary types",
3054 encoding,
3055 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003056 Py_DECREF(unicode);
3057 goto onError;
3058 }
3059 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003060 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003061
Benjamin Peterson29060642009-01-31 22:14:21 +00003062 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003063 Py_XDECREF(buffer);
3064 return NULL;
3065}
3066
Alexander Belopolsky40018472011-02-26 01:02:56 +00003067PyObject *
3068PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003069 const char *encoding,
3070 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003071{
3072 PyObject *v;
3073
3074 if (!PyUnicode_Check(unicode)) {
3075 PyErr_BadArgument();
3076 goto onError;
3077 }
3078
3079 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003080 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003081
3082 /* Decode via the codec registry */
3083 v = PyCodec_Decode(unicode, encoding, errors);
3084 if (v == NULL)
3085 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003086 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003087
Benjamin Peterson29060642009-01-31 22:14:21 +00003088 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003089 return NULL;
3090}
3091
Alexander Belopolsky40018472011-02-26 01:02:56 +00003092PyObject *
3093PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003094 const char *encoding,
3095 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003096{
3097 PyObject *v;
3098
3099 if (!PyUnicode_Check(unicode)) {
3100 PyErr_BadArgument();
3101 goto onError;
3102 }
3103
3104 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003105 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003106
3107 /* Decode via the codec registry */
3108 v = PyCodec_Decode(unicode, encoding, errors);
3109 if (v == NULL)
3110 goto onError;
3111 if (!PyUnicode_Check(v)) {
3112 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003113 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3114 "use codecs.decode() to decode to arbitrary types",
3115 encoding,
3116 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003117 Py_DECREF(v);
3118 goto onError;
3119 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003120 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003121
Benjamin Peterson29060642009-01-31 22:14:21 +00003122 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003123 return NULL;
3124}
3125
Alexander Belopolsky40018472011-02-26 01:02:56 +00003126PyObject *
3127PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003128 Py_ssize_t size,
3129 const char *encoding,
3130 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003131{
3132 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003133
Guido van Rossumd57fd912000-03-10 22:53:23 +00003134 unicode = PyUnicode_FromUnicode(s, size);
3135 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003137 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3138 Py_DECREF(unicode);
3139 return v;
3140}
3141
Alexander Belopolsky40018472011-02-26 01:02:56 +00003142PyObject *
3143PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003144 const char *encoding,
3145 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003146{
3147 PyObject *v;
3148
3149 if (!PyUnicode_Check(unicode)) {
3150 PyErr_BadArgument();
3151 goto onError;
3152 }
3153
3154 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003155 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003156
3157 /* Encode via the codec registry */
3158 v = PyCodec_Encode(unicode, encoding, errors);
3159 if (v == NULL)
3160 goto onError;
3161 return v;
3162
Benjamin Peterson29060642009-01-31 22:14:21 +00003163 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003164 return NULL;
3165}
3166
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003167static size_t
3168wcstombs_errorpos(const wchar_t *wstr)
3169{
3170 size_t len;
3171#if SIZEOF_WCHAR_T == 2
3172 wchar_t buf[3];
3173#else
3174 wchar_t buf[2];
3175#endif
3176 char outbuf[MB_LEN_MAX];
3177 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003178
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003179#if SIZEOF_WCHAR_T == 2
3180 buf[2] = 0;
3181#else
3182 buf[1] = 0;
3183#endif
3184 start = wstr;
3185 while (*wstr != L'\0')
3186 {
3187 previous = wstr;
3188#if SIZEOF_WCHAR_T == 2
3189 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3190 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3191 {
3192 buf[0] = wstr[0];
3193 buf[1] = wstr[1];
3194 wstr += 2;
3195 }
3196 else {
3197 buf[0] = *wstr;
3198 buf[1] = 0;
3199 wstr++;
3200 }
3201#else
3202 buf[0] = *wstr;
3203 wstr++;
3204#endif
3205 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003206 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003207 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003208 }
3209
3210 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003211 return 0;
3212}
3213
Victor Stinner1b579672011-12-17 05:47:23 +01003214static int
3215locale_error_handler(const char *errors, int *surrogateescape)
3216{
3217 if (errors == NULL) {
3218 *surrogateescape = 0;
3219 return 0;
3220 }
3221
3222 if (strcmp(errors, "strict") == 0) {
3223 *surrogateescape = 0;
3224 return 0;
3225 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003226 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003227 *surrogateescape = 1;
3228 return 0;
3229 }
3230 PyErr_Format(PyExc_ValueError,
3231 "only 'strict' and 'surrogateescape' error handlers "
3232 "are supported, not '%s'",
3233 errors);
3234 return -1;
3235}
3236
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003237PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003238PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003239{
3240 Py_ssize_t wlen, wlen2;
3241 wchar_t *wstr;
3242 PyObject *bytes = NULL;
3243 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003244 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003245 PyObject *exc;
3246 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003247 int surrogateescape;
3248
3249 if (locale_error_handler(errors, &surrogateescape) < 0)
3250 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003251
3252 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3253 if (wstr == NULL)
3254 return NULL;
3255
3256 wlen2 = wcslen(wstr);
3257 if (wlen2 != wlen) {
3258 PyMem_Free(wstr);
3259 PyErr_SetString(PyExc_TypeError, "embedded null character");
3260 return NULL;
3261 }
3262
3263 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003264 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003265 char *str;
3266
3267 str = _Py_wchar2char(wstr, &error_pos);
3268 if (str == NULL) {
3269 if (error_pos == (size_t)-1) {
3270 PyErr_NoMemory();
3271 PyMem_Free(wstr);
3272 return NULL;
3273 }
3274 else {
3275 goto encode_error;
3276 }
3277 }
3278 PyMem_Free(wstr);
3279
3280 bytes = PyBytes_FromString(str);
3281 PyMem_Free(str);
3282 }
3283 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003284 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003285 size_t len, len2;
3286
3287 len = wcstombs(NULL, wstr, 0);
3288 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003289 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 goto encode_error;
3291 }
3292
3293 bytes = PyBytes_FromStringAndSize(NULL, len);
3294 if (bytes == NULL) {
3295 PyMem_Free(wstr);
3296 return NULL;
3297 }
3298
3299 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3300 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003301 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003302 goto encode_error;
3303 }
3304 PyMem_Free(wstr);
3305 }
3306 return bytes;
3307
3308encode_error:
3309 errmsg = strerror(errno);
3310 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003311
3312 if (error_pos == (size_t)-1)
3313 error_pos = wcstombs_errorpos(wstr);
3314
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003315 PyMem_Free(wstr);
3316 Py_XDECREF(bytes);
3317
Victor Stinner2f197072011-12-17 07:08:30 +01003318 if (errmsg != NULL) {
3319 size_t errlen;
3320 wstr = _Py_char2wchar(errmsg, &errlen);
3321 if (wstr != NULL) {
3322 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003323 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003324 } else
3325 errmsg = NULL;
3326 }
3327 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003328 reason = PyUnicode_FromString(
3329 "wcstombs() encountered an unencodable "
3330 "wide character");
3331 if (reason == NULL)
3332 return NULL;
3333
3334 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3335 "locale", unicode,
3336 (Py_ssize_t)error_pos,
3337 (Py_ssize_t)(error_pos+1),
3338 reason);
3339 Py_DECREF(reason);
3340 if (exc != NULL) {
3341 PyCodec_StrictErrors(exc);
3342 Py_XDECREF(exc);
3343 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003344 return NULL;
3345}
3346
Victor Stinnerad158722010-10-27 00:25:46 +00003347PyObject *
3348PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003349{
Victor Stinner99b95382011-07-04 14:23:54 +02003350#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003351 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003352#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003353 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003354#else
Victor Stinner793b5312011-04-27 00:24:21 +02003355 PyInterpreterState *interp = PyThreadState_GET()->interp;
3356 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3357 cannot use it to encode and decode filenames before it is loaded. Load
3358 the Python codec requires to encode at least its own filename. Use the C
3359 version of the locale codec until the codec registry is initialized and
3360 the Python codec is loaded.
3361
3362 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3363 cannot only rely on it: check also interp->fscodec_initialized for
3364 subinterpreters. */
3365 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003366 return PyUnicode_AsEncodedString(unicode,
3367 Py_FileSystemDefaultEncoding,
3368 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003369 }
3370 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003371 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003372 }
Victor Stinnerad158722010-10-27 00:25:46 +00003373#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003374}
3375
Alexander Belopolsky40018472011-02-26 01:02:56 +00003376PyObject *
3377PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003378 const char *encoding,
3379 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003380{
3381 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003382 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003383
Guido van Rossumd57fd912000-03-10 22:53:23 +00003384 if (!PyUnicode_Check(unicode)) {
3385 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003387 }
Fred Drakee4315f52000-05-09 19:53:39 +00003388
Fred Drakee4315f52000-05-09 19:53:39 +00003389 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003390 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003391 if ((strcmp(lower, "utf-8") == 0) ||
3392 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003393 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003394 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003395 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003396 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003397 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003398 }
Victor Stinner37296e82010-06-10 13:36:23 +00003399 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003400 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003401 (strcmp(lower, "iso-8859-1") == 0) ||
3402 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003403 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003404#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003405 else if (strcmp(lower, "mbcs") == 0)
3406 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003407#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003408 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003409 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003410 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003411
3412 /* Encode via the codec registry */
3413 v = PyCodec_Encode(unicode, encoding, errors);
3414 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003415 return NULL;
3416
3417 /* The normal path */
3418 if (PyBytes_Check(v))
3419 return v;
3420
3421 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003422 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003423 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003424 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003425
3426 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003427 "encoder %s returned bytearray instead of bytes; "
3428 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003429 encoding);
3430 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003431 Py_DECREF(v);
3432 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003433 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003434
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003435 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3436 Py_DECREF(v);
3437 return b;
3438 }
3439
3440 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003441 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3442 "use codecs.encode() to encode to arbitrary types",
3443 encoding,
3444 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003445 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003446 return NULL;
3447}
3448
Alexander Belopolsky40018472011-02-26 01:02:56 +00003449PyObject *
3450PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003451 const char *encoding,
3452 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003453{
3454 PyObject *v;
3455
3456 if (!PyUnicode_Check(unicode)) {
3457 PyErr_BadArgument();
3458 goto onError;
3459 }
3460
3461 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003462 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003463
3464 /* Encode via the codec registry */
3465 v = PyCodec_Encode(unicode, encoding, errors);
3466 if (v == NULL)
3467 goto onError;
3468 if (!PyUnicode_Check(v)) {
3469 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003470 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3471 "use codecs.encode() to encode to arbitrary types",
3472 encoding,
3473 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003474 Py_DECREF(v);
3475 goto onError;
3476 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003477 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003478
Benjamin Peterson29060642009-01-31 22:14:21 +00003479 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003480 return NULL;
3481}
3482
Victor Stinner2f197072011-12-17 07:08:30 +01003483static size_t
3484mbstowcs_errorpos(const char *str, size_t len)
3485{
3486#ifdef HAVE_MBRTOWC
3487 const char *start = str;
3488 mbstate_t mbs;
3489 size_t converted;
3490 wchar_t ch;
3491
3492 memset(&mbs, 0, sizeof mbs);
3493 while (len)
3494 {
3495 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3496 if (converted == 0)
3497 /* Reached end of string */
3498 break;
3499 if (converted == (size_t)-1 || converted == (size_t)-2) {
3500 /* Conversion error or incomplete character */
3501 return str - start;
3502 }
3503 else {
3504 str += converted;
3505 len -= converted;
3506 }
3507 }
3508 /* failed to find the undecodable byte sequence */
3509 return 0;
3510#endif
3511 return 0;
3512}
3513
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003514PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003515PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003516 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003517{
3518 wchar_t smallbuf[256];
3519 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3520 wchar_t *wstr;
3521 size_t wlen, wlen2;
3522 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003523 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003524 size_t error_pos;
3525 char *errmsg;
3526 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003527
3528 if (locale_error_handler(errors, &surrogateescape) < 0)
3529 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003530
3531 if (str[len] != '\0' || len != strlen(str)) {
3532 PyErr_SetString(PyExc_TypeError, "embedded null character");
3533 return NULL;
3534 }
3535
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003536 if (surrogateescape) {
3537 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003538 wstr = _Py_char2wchar(str, &wlen);
3539 if (wstr == NULL) {
3540 if (wlen == (size_t)-1)
3541 PyErr_NoMemory();
3542 else
3543 PyErr_SetFromErrno(PyExc_OSError);
3544 return NULL;
3545 }
3546
3547 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003548 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549 }
3550 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003551 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003552#ifndef HAVE_BROKEN_MBSTOWCS
3553 wlen = mbstowcs(NULL, str, 0);
3554#else
3555 wlen = len;
3556#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003557 if (wlen == (size_t)-1)
3558 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003559 if (wlen+1 <= smallbuf_len) {
3560 wstr = smallbuf;
3561 }
3562 else {
3563 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3564 return PyErr_NoMemory();
3565
3566 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3567 if (!wstr)
3568 return PyErr_NoMemory();
3569 }
3570
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003571 wlen2 = mbstowcs(wstr, str, wlen+1);
3572 if (wlen2 == (size_t)-1) {
3573 if (wstr != smallbuf)
3574 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003575 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003576 }
3577#ifdef HAVE_BROKEN_MBSTOWCS
3578 assert(wlen2 == wlen);
3579#endif
3580 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3581 if (wstr != smallbuf)
3582 PyMem_Free(wstr);
3583 }
3584 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003585
3586decode_error:
3587 errmsg = strerror(errno);
3588 assert(errmsg != NULL);
3589
3590 error_pos = mbstowcs_errorpos(str, len);
3591 if (errmsg != NULL) {
3592 size_t errlen;
3593 wstr = _Py_char2wchar(errmsg, &errlen);
3594 if (wstr != NULL) {
3595 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003596 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003597 } else
3598 errmsg = NULL;
3599 }
3600 if (errmsg == NULL)
3601 reason = PyUnicode_FromString(
3602 "mbstowcs() encountered an invalid multibyte sequence");
3603 if (reason == NULL)
3604 return NULL;
3605
3606 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3607 "locale", str, len,
3608 (Py_ssize_t)error_pos,
3609 (Py_ssize_t)(error_pos+1),
3610 reason);
3611 Py_DECREF(reason);
3612 if (exc != NULL) {
3613 PyCodec_StrictErrors(exc);
3614 Py_XDECREF(exc);
3615 }
3616 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003617}
3618
3619PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003620PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003621{
3622 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003623 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003624}
3625
3626
3627PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003628PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003629 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003630 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3631}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003632
Christian Heimes5894ba72007-11-04 11:43:14 +00003633PyObject*
3634PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3635{
Victor Stinner99b95382011-07-04 14:23:54 +02003636#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003637 return PyUnicode_DecodeMBCS(s, size, NULL);
3638#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003639 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003640#else
Victor Stinner793b5312011-04-27 00:24:21 +02003641 PyInterpreterState *interp = PyThreadState_GET()->interp;
3642 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3643 cannot use it to encode and decode filenames before it is loaded. Load
3644 the Python codec requires to encode at least its own filename. Use the C
3645 version of the locale codec until the codec registry is initialized and
3646 the Python codec is loaded.
3647
3648 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3649 cannot only rely on it: check also interp->fscodec_initialized for
3650 subinterpreters. */
3651 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003652 return PyUnicode_Decode(s, size,
3653 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003654 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003655 }
3656 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003657 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003658 }
Victor Stinnerad158722010-10-27 00:25:46 +00003659#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003660}
3661
Martin v. Löwis011e8422009-05-05 04:43:17 +00003662
3663int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003664_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003665{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003666 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003667
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003668 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003669 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003670 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3671 PyUnicode_GET_LENGTH(str), '\0', 1);
3672 if (pos == -1)
3673 return 0;
3674 else
3675 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003676}
3677
Antoine Pitrou13348842012-01-29 18:36:34 +01003678int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003679PyUnicode_FSConverter(PyObject* arg, void* addr)
3680{
3681 PyObject *output = NULL;
3682 Py_ssize_t size;
3683 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003684 if (arg == NULL) {
3685 Py_DECREF(*(PyObject**)addr);
3686 return 1;
3687 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003688 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003689 output = arg;
3690 Py_INCREF(output);
3691 }
3692 else {
3693 arg = PyUnicode_FromObject(arg);
3694 if (!arg)
3695 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003696 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003697 Py_DECREF(arg);
3698 if (!output)
3699 return 0;
3700 if (!PyBytes_Check(output)) {
3701 Py_DECREF(output);
3702 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3703 return 0;
3704 }
3705 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003706 size = PyBytes_GET_SIZE(output);
3707 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003708 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003709 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003710 Py_DECREF(output);
3711 return 0;
3712 }
3713 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003714 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003715}
3716
3717
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003718int
3719PyUnicode_FSDecoder(PyObject* arg, void* addr)
3720{
3721 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003722 if (arg == NULL) {
3723 Py_DECREF(*(PyObject**)addr);
3724 return 1;
3725 }
3726 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003727 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003728 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003729 output = arg;
3730 Py_INCREF(output);
3731 }
3732 else {
3733 arg = PyBytes_FromObject(arg);
3734 if (!arg)
3735 return 0;
3736 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3737 PyBytes_GET_SIZE(arg));
3738 Py_DECREF(arg);
3739 if (!output)
3740 return 0;
3741 if (!PyUnicode_Check(output)) {
3742 Py_DECREF(output);
3743 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3744 return 0;
3745 }
3746 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003747 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003748 Py_DECREF(output);
3749 return 0;
3750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003752 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003753 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3754 Py_DECREF(output);
3755 return 0;
3756 }
3757 *(PyObject**)addr = output;
3758 return Py_CLEANUP_SUPPORTED;
3759}
3760
3761
Martin v. Löwis5b222132007-06-10 09:51:05 +00003762char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003763PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003764{
Christian Heimesf3863112007-11-22 07:46:41 +00003765 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003767 if (!PyUnicode_Check(unicode)) {
3768 PyErr_BadArgument();
3769 return NULL;
3770 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003771 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003772 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003774 if (PyUnicode_UTF8(unicode) == NULL) {
3775 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003776 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3777 if (bytes == NULL)
3778 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003779 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3780 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003781 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003782 Py_DECREF(bytes);
3783 return NULL;
3784 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003785 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3786 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3787 PyBytes_AS_STRING(bytes),
3788 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789 Py_DECREF(bytes);
3790 }
3791
3792 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003793 *psize = PyUnicode_UTF8_LENGTH(unicode);
3794 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003795}
3796
3797char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003800 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3801}
3802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003803Py_UNICODE *
3804PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003806 const unsigned char *one_byte;
3807#if SIZEOF_WCHAR_T == 4
3808 const Py_UCS2 *two_bytes;
3809#else
3810 const Py_UCS4 *four_bytes;
3811 const Py_UCS4 *ucs4_end;
3812 Py_ssize_t num_surrogates;
3813#endif
3814 wchar_t *w;
3815 wchar_t *wchar_end;
3816
3817 if (!PyUnicode_Check(unicode)) {
3818 PyErr_BadArgument();
3819 return NULL;
3820 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003821 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003823 assert(_PyUnicode_KIND(unicode) != 0);
3824 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003825
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003826 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003827#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003828 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3829 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830 num_surrogates = 0;
3831
3832 for (; four_bytes < ucs4_end; ++four_bytes) {
3833 if (*four_bytes > 0xFFFF)
3834 ++num_surrogates;
3835 }
3836
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003837 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3838 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3839 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003840 PyErr_NoMemory();
3841 return NULL;
3842 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003843 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003845 w = _PyUnicode_WSTR(unicode);
3846 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3847 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003848 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3849 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003850 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003851 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003852 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3853 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854 }
3855 else
3856 *w = *four_bytes;
3857
3858 if (w > wchar_end) {
3859 assert(0 && "Miscalculated string end");
3860 }
3861 }
3862 *w = 0;
3863#else
3864 /* sizeof(wchar_t) == 4 */
3865 Py_FatalError("Impossible unicode object state, wstr and str "
3866 "should share memory already.");
3867 return NULL;
3868#endif
3869 }
3870 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003871 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3872 (_PyUnicode_LENGTH(unicode) + 1));
3873 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 PyErr_NoMemory();
3875 return NULL;
3876 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3878 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3879 w = _PyUnicode_WSTR(unicode);
3880 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3883 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884 for (; w < wchar_end; ++one_byte, ++w)
3885 *w = *one_byte;
3886 /* null-terminate the wstr */
3887 *w = 0;
3888 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003889 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003891 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892 for (; w < wchar_end; ++two_bytes, ++w)
3893 *w = *two_bytes;
3894 /* null-terminate the wstr */
3895 *w = 0;
3896#else
3897 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003898 PyObject_FREE(_PyUnicode_WSTR(unicode));
3899 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003900 Py_FatalError("Impossible unicode object state, wstr "
3901 "and str should share memory already.");
3902 return NULL;
3903#endif
3904 }
3905 else {
3906 assert(0 && "This should never happen.");
3907 }
3908 }
3909 }
3910 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003911 *size = PyUnicode_WSTR_LENGTH(unicode);
3912 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003913}
3914
Alexander Belopolsky40018472011-02-26 01:02:56 +00003915Py_UNICODE *
3916PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003918 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003919}
3920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003921
Alexander Belopolsky40018472011-02-26 01:02:56 +00003922Py_ssize_t
3923PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003924{
3925 if (!PyUnicode_Check(unicode)) {
3926 PyErr_BadArgument();
3927 goto onError;
3928 }
3929 return PyUnicode_GET_SIZE(unicode);
3930
Benjamin Peterson29060642009-01-31 22:14:21 +00003931 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003932 return -1;
3933}
3934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935Py_ssize_t
3936PyUnicode_GetLength(PyObject *unicode)
3937{
Victor Stinner07621332012-06-16 04:53:46 +02003938 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003939 PyErr_BadArgument();
3940 return -1;
3941 }
Victor Stinner07621332012-06-16 04:53:46 +02003942 if (PyUnicode_READY(unicode) == -1)
3943 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003944 return PyUnicode_GET_LENGTH(unicode);
3945}
3946
3947Py_UCS4
3948PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3949{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003950 void *data;
3951 int kind;
3952
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003953 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3954 PyErr_BadArgument();
3955 return (Py_UCS4)-1;
3956 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003957 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003958 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959 return (Py_UCS4)-1;
3960 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003961 data = PyUnicode_DATA(unicode);
3962 kind = PyUnicode_KIND(unicode);
3963 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003964}
3965
3966int
3967PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3968{
3969 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003970 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971 return -1;
3972 }
Victor Stinner488fa492011-12-12 00:01:39 +01003973 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003974 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003975 PyErr_SetString(PyExc_IndexError, "string index out of range");
3976 return -1;
3977 }
Victor Stinner488fa492011-12-12 00:01:39 +01003978 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003979 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003980 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3981 PyErr_SetString(PyExc_ValueError, "character out of range");
3982 return -1;
3983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3985 index, ch);
3986 return 0;
3987}
3988
Alexander Belopolsky40018472011-02-26 01:02:56 +00003989const char *
3990PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003991{
Victor Stinner42cb4622010-09-01 19:39:01 +00003992 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003993}
3994
Victor Stinner554f3f02010-06-16 23:33:54 +00003995/* create or adjust a UnicodeDecodeError */
3996static void
3997make_decode_exception(PyObject **exceptionObject,
3998 const char *encoding,
3999 const char *input, Py_ssize_t length,
4000 Py_ssize_t startpos, Py_ssize_t endpos,
4001 const char *reason)
4002{
4003 if (*exceptionObject == NULL) {
4004 *exceptionObject = PyUnicodeDecodeError_Create(
4005 encoding, input, length, startpos, endpos, reason);
4006 }
4007 else {
4008 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4009 goto onError;
4010 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4011 goto onError;
4012 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4013 goto onError;
4014 }
4015 return;
4016
4017onError:
4018 Py_DECREF(*exceptionObject);
4019 *exceptionObject = NULL;
4020}
4021
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004022#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004023/* error handling callback helper:
4024 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004025 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026 and adjust various state variables.
4027 return 0 on success, -1 on error
4028*/
4029
Alexander Belopolsky40018472011-02-26 01:02:56 +00004030static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004031unicode_decode_call_errorhandler_wchar(
4032 const char *errors, PyObject **errorHandler,
4033 const char *encoding, const char *reason,
4034 const char **input, const char **inend, Py_ssize_t *startinpos,
4035 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4036 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004037{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004038 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
4040 PyObject *restuple = NULL;
4041 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004042 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004043 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004044 Py_ssize_t requiredsize;
4045 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004046 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004047 wchar_t *repwstr;
4048 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004049
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004050 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4051 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004052
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004053 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004054 *errorHandler = PyCodec_LookupError(errors);
4055 if (*errorHandler == NULL)
4056 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004057 }
4058
Victor Stinner554f3f02010-06-16 23:33:54 +00004059 make_decode_exception(exceptionObject,
4060 encoding,
4061 *input, *inend - *input,
4062 *startinpos, *endinpos,
4063 reason);
4064 if (*exceptionObject == NULL)
4065 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004066
4067 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4068 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004069 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004070 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004071 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004072 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004073 }
4074 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004076
4077 /* Copy back the bytes variables, which might have been modified by the
4078 callback */
4079 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4080 if (!inputobj)
4081 goto onError;
4082 if (!PyBytes_Check(inputobj)) {
4083 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4084 }
4085 *input = PyBytes_AS_STRING(inputobj);
4086 insize = PyBytes_GET_SIZE(inputobj);
4087 *inend = *input + insize;
4088 /* we can DECREF safely, as the exception has another reference,
4089 so the object won't go away. */
4090 Py_DECREF(inputobj);
4091
4092 if (newpos<0)
4093 newpos = insize+newpos;
4094 if (newpos<0 || newpos>insize) {
4095 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4096 goto onError;
4097 }
4098
4099 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4100 if (repwstr == NULL)
4101 goto onError;
4102 /* need more space? (at least enough for what we
4103 have+the replacement+the rest of the string (starting
4104 at the new input position), so we won't have to check space
4105 when there are no errors in the rest of the string) */
4106 requiredsize = *outpos + repwlen + insize-newpos;
4107 if (requiredsize > outsize) {
4108 if (requiredsize < 2*outsize)
4109 requiredsize = 2*outsize;
4110 if (unicode_resize(output, requiredsize) < 0)
4111 goto onError;
4112 }
4113 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4114 *outpos += repwlen;
4115
4116 *endinpos = newpos;
4117 *inptr = *input + newpos;
4118
4119 /* we made it! */
4120 Py_XDECREF(restuple);
4121 return 0;
4122
4123 onError:
4124 Py_XDECREF(restuple);
4125 return -1;
4126}
4127#endif /* HAVE_MBCS */
4128
4129static int
4130unicode_decode_call_errorhandler_writer(
4131 const char *errors, PyObject **errorHandler,
4132 const char *encoding, const char *reason,
4133 const char **input, const char **inend, Py_ssize_t *startinpos,
4134 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4135 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4136{
4137 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4138
4139 PyObject *restuple = NULL;
4140 PyObject *repunicode = NULL;
4141 Py_ssize_t insize;
4142 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004143 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004144 PyObject *inputobj = NULL;
4145
4146 if (*errorHandler == NULL) {
4147 *errorHandler = PyCodec_LookupError(errors);
4148 if (*errorHandler == NULL)
4149 goto onError;
4150 }
4151
4152 make_decode_exception(exceptionObject,
4153 encoding,
4154 *input, *inend - *input,
4155 *startinpos, *endinpos,
4156 reason);
4157 if (*exceptionObject == NULL)
4158 goto onError;
4159
4160 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4161 if (restuple == NULL)
4162 goto onError;
4163 if (!PyTuple_Check(restuple)) {
4164 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4165 goto onError;
4166 }
4167 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004168 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004169
4170 /* Copy back the bytes variables, which might have been modified by the
4171 callback */
4172 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4173 if (!inputobj)
4174 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004175 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004177 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004178 *input = PyBytes_AS_STRING(inputobj);
4179 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004180 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004181 /* we can DECREF safely, as the exception has another reference,
4182 so the object won't go away. */
4183 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004184
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004185 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004186 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004187 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4189 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004190 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004191
Victor Stinner8f674cc2013-04-17 23:02:17 +02004192 if (PyUnicode_READY(repunicode) < 0)
4193 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004194 replen = PyUnicode_GET_LENGTH(repunicode);
4195 writer->min_length += replen;
4196 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004197 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004198 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004199 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004200
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004202 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004203
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004204 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004205 Py_XDECREF(restuple);
4206 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004207
Benjamin Peterson29060642009-01-31 22:14:21 +00004208 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004210 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004211}
4212
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004213/* --- UTF-7 Codec -------------------------------------------------------- */
4214
Antoine Pitrou244651a2009-05-04 18:56:13 +00004215/* See RFC2152 for details. We encode conservatively and decode liberally. */
4216
4217/* Three simple macros defining base-64. */
4218
4219/* Is c a base-64 character? */
4220
4221#define IS_BASE64(c) \
4222 (((c) >= 'A' && (c) <= 'Z') || \
4223 ((c) >= 'a' && (c) <= 'z') || \
4224 ((c) >= '0' && (c) <= '9') || \
4225 (c) == '+' || (c) == '/')
4226
4227/* given that c is a base-64 character, what is its base-64 value? */
4228
4229#define FROM_BASE64(c) \
4230 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4231 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4232 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4233 (c) == '+' ? 62 : 63)
4234
4235/* What is the base-64 character of the bottom 6 bits of n? */
4236
4237#define TO_BASE64(n) \
4238 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4239
4240/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4241 * decoded as itself. We are permissive on decoding; the only ASCII
4242 * byte not decoding to itself is the + which begins a base64
4243 * string. */
4244
4245#define DECODE_DIRECT(c) \
4246 ((c) <= 127 && (c) != '+')
4247
4248/* The UTF-7 encoder treats ASCII characters differently according to
4249 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4250 * the above). See RFC2152. This array identifies these different
4251 * sets:
4252 * 0 : "Set D"
4253 * alphanumeric and '(),-./:?
4254 * 1 : "Set O"
4255 * !"#$%&*;<=>@[]^_`{|}
4256 * 2 : "whitespace"
4257 * ht nl cr sp
4258 * 3 : special (must be base64 encoded)
4259 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4260 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261
Tim Petersced69f82003-09-16 20:30:58 +00004262static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263char utf7_category[128] = {
4264/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4265 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4266/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4267 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4268/* sp ! " # $ % & ' ( ) * + , - . / */
4269 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4270/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4272/* @ A B C D E F G H I J K L M N O */
4273 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4274/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4276/* ` a b c d e f g h i j k l m n o */
4277 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4278/* p q r s t u v w x y z { | } ~ del */
4279 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004280};
4281
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282/* ENCODE_DIRECT: this character should be encoded as itself. The
4283 * answer depends on whether we are encoding set O as itself, and also
4284 * on whether we are encoding whitespace as itself. RFC2152 makes it
4285 * clear that the answers to these questions vary between
4286 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004287
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288#define ENCODE_DIRECT(c, directO, directWS) \
4289 ((c) < 128 && (c) > 0 && \
4290 ((utf7_category[(c)] == 0) || \
4291 (directWS && (utf7_category[(c)] == 2)) || \
4292 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293
Alexander Belopolsky40018472011-02-26 01:02:56 +00004294PyObject *
4295PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004296 Py_ssize_t size,
4297 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004298{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004299 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4300}
4301
Antoine Pitrou244651a2009-05-04 18:56:13 +00004302/* The decoder. The only state we preserve is our read position,
4303 * i.e. how many characters we have consumed. So if we end in the
4304 * middle of a shift sequence we have to back off the read position
4305 * and the output to the beginning of the sequence, otherwise we lose
4306 * all the shift state (seen bits, number of bits seen, high
4307 * surrogate). */
4308
Alexander Belopolsky40018472011-02-26 01:02:56 +00004309PyObject *
4310PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004311 Py_ssize_t size,
4312 const char *errors,
4313 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004314{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004315 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004316 Py_ssize_t startinpos;
4317 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004319 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320 const char *errmsg = "";
4321 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004322 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004323 unsigned int base64bits = 0;
4324 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004325 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004326 PyObject *errorHandler = NULL;
4327 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004328
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004329 if (size == 0) {
4330 if (consumed)
4331 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004332 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004333 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004334
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004335 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004336 _PyUnicodeWriter_Init(&writer);
4337 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004338
4339 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004340 e = s + size;
4341
4342 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004343 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004344 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004345 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004346
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 if (inShift) { /* in a base-64 section */
4348 if (IS_BASE64(ch)) { /* consume a base-64 character */
4349 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4350 base64bits += 6;
4351 s++;
4352 if (base64bits >= 16) {
4353 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004354 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 base64bits -= 16;
4356 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004357 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 if (surrogate) {
4359 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004360 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4361 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004362 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004363 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004365 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 }
4367 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004368 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 }
Victor Stinner551ac952011-11-29 22:58:13 +01004373 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 /* first surrogate */
4375 surrogate = outCh;
4376 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004378 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004379 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004380 }
4381 }
4382 }
4383 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384 inShift = 0;
4385 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004386 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004387 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004388 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004389 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 if (base64bits > 0) { /* left-over bits */
4392 if (base64bits >= 6) {
4393 /* We've seen at least one base-64 character */
4394 errmsg = "partial character in shift sequence";
4395 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397 else {
4398 /* Some bits remain; they should be zero */
4399 if (base64buffer != 0) {
4400 errmsg = "non-zero padding bits in shift sequence";
4401 goto utf7Error;
4402 }
4403 }
4404 }
4405 if (ch != '-') {
4406 /* '-' is absorbed; other terminating
4407 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004408 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 }
4412 }
4413 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 s++; /* consume '+' */
4416 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004418 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004419 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 }
4421 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004423 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004425 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426 }
4427 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004428 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004430 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004431 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433 else {
4434 startinpos = s-starts;
4435 s++;
4436 errmsg = "unexpected special character";
4437 goto utf7Error;
4438 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004441 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004442 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004443 errors, &errorHandler,
4444 "utf7", errmsg,
4445 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004446 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004448 }
4449
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 /* end of string */
4451
4452 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4453 /* if we're in an inconsistent state, that's an error */
4454 if (surrogate ||
4455 (base64bits >= 6) ||
4456 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004458 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004459 errors, &errorHandler,
4460 "utf7", "unterminated shift sequence",
4461 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004462 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004463 goto onError;
4464 if (s < e)
4465 goto restart;
4466 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004467 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468
4469 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004470 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004471 if (inShift) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004472 writer.pos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004473 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004474 }
4475 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004476 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004477 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004478 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004479
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004480 Py_XDECREF(errorHandler);
4481 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004482 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483
Benjamin Peterson29060642009-01-31 22:14:21 +00004484 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004485 Py_XDECREF(errorHandler);
4486 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004487 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488 return NULL;
4489}
4490
4491
Alexander Belopolsky40018472011-02-26 01:02:56 +00004492PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004493_PyUnicode_EncodeUTF7(PyObject *str,
4494 int base64SetO,
4495 int base64WhiteSpace,
4496 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004498 int kind;
4499 void *data;
4500 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004501 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004503 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504 unsigned int base64bits = 0;
4505 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 char * out;
4507 char * start;
4508
Benjamin Petersonbac79492012-01-14 13:34:47 -05004509 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004510 return NULL;
4511 kind = PyUnicode_KIND(str);
4512 data = PyUnicode_DATA(str);
4513 len = PyUnicode_GET_LENGTH(str);
4514
4515 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004518 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004519 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004520 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004521 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004522 if (v == NULL)
4523 return NULL;
4524
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004525 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004526 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004527 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528
Antoine Pitrou244651a2009-05-04 18:56:13 +00004529 if (inShift) {
4530 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4531 /* shifting out */
4532 if (base64bits) { /* output remaining bits */
4533 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4534 base64buffer = 0;
4535 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536 }
4537 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538 /* Characters not in the BASE64 set implicitly unshift the sequence
4539 so no '-' is required, except if the character is itself a '-' */
4540 if (IS_BASE64(ch) || ch == '-') {
4541 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543 *out++ = (char) ch;
4544 }
4545 else {
4546 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004547 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 else { /* not in a shift sequence */
4550 if (ch == '+') {
4551 *out++ = '+';
4552 *out++ = '-';
4553 }
4554 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4555 *out++ = (char) ch;
4556 }
4557 else {
4558 *out++ = '+';
4559 inShift = 1;
4560 goto encode_char;
4561 }
4562 }
4563 continue;
4564encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004566 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004567
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 /* code first surrogate */
4569 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004570 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 while (base64bits >= 6) {
4572 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4573 base64bits -= 6;
4574 }
4575 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004576 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 base64bits += 16;
4579 base64buffer = (base64buffer << 16) | ch;
4580 while (base64bits >= 6) {
4581 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4582 base64bits -= 6;
4583 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004584 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 if (base64bits)
4586 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4587 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004589 if (_PyBytes_Resize(&v, out - start) < 0)
4590 return NULL;
4591 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004593PyObject *
4594PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4595 Py_ssize_t size,
4596 int base64SetO,
4597 int base64WhiteSpace,
4598 const char *errors)
4599{
4600 PyObject *result;
4601 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4602 if (tmp == NULL)
4603 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004604 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004605 base64WhiteSpace, errors);
4606 Py_DECREF(tmp);
4607 return result;
4608}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004609
Antoine Pitrou244651a2009-05-04 18:56:13 +00004610#undef IS_BASE64
4611#undef FROM_BASE64
4612#undef TO_BASE64
4613#undef DECODE_DIRECT
4614#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615
Guido van Rossumd57fd912000-03-10 22:53:23 +00004616/* --- UTF-8 Codec -------------------------------------------------------- */
4617
Alexander Belopolsky40018472011-02-26 01:02:56 +00004618PyObject *
4619PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004620 Py_ssize_t size,
4621 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004622{
Walter Dörwald69652032004-09-07 20:24:22 +00004623 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4624}
4625
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004626#include "stringlib/asciilib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004630#include "stringlib/ucs1lib.h"
4631#include "stringlib/codecs.h"
4632#include "stringlib/undef.h"
4633
4634#include "stringlib/ucs2lib.h"
4635#include "stringlib/codecs.h"
4636#include "stringlib/undef.h"
4637
4638#include "stringlib/ucs4lib.h"
4639#include "stringlib/codecs.h"
4640#include "stringlib/undef.h"
4641
Antoine Pitrouab868312009-01-10 15:40:25 +00004642/* Mask to quickly check whether a C 'long' contains a
4643 non-ASCII, UTF8-encoded char. */
4644#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004645# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004646#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004647# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004648#else
4649# error C 'long' size should be either 4 or 8!
4650#endif
4651
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004652static Py_ssize_t
4653ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004655 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004656 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004657
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004658 /*
4659 * Issue #17237: m68k is a bit different from most architectures in
4660 * that objects do not use "natural alignment" - for example, int and
4661 * long are only aligned at 2-byte boundaries. Therefore the assert()
4662 * won't work; also, tests have shown that skipping the "optimised
4663 * version" will even speed up m68k.
4664 */
4665#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004666#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004667 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4668 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004669 /* Fast path, see in STRINGLIB(utf8_decode) for
4670 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004671 /* Help allocation */
4672 const char *_p = p;
4673 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004674 while (_p < aligned_end) {
4675 unsigned long value = *(const unsigned long *) _p;
4676 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004677 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678 *((unsigned long *)q) = value;
4679 _p += SIZEOF_LONG;
4680 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004681 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682 p = _p;
4683 while (p < end) {
4684 if ((unsigned char)*p & 0x80)
4685 break;
4686 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004689 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004691#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004692 while (p < end) {
4693 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4694 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004695 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004696 /* Help allocation */
4697 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698 while (_p < aligned_end) {
4699 unsigned long value = *(unsigned long *) _p;
4700 if (value & ASCII_CHAR_MASK)
4701 break;
4702 _p += SIZEOF_LONG;
4703 }
4704 p = _p;
4705 if (_p == end)
4706 break;
4707 }
4708 if ((unsigned char)*p & 0x80)
4709 break;
4710 ++p;
4711 }
4712 memcpy(dest, start, p - start);
4713 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004714}
Antoine Pitrouab868312009-01-10 15:40:25 +00004715
Victor Stinner785938e2011-12-11 20:09:03 +01004716PyObject *
4717PyUnicode_DecodeUTF8Stateful(const char *s,
4718 Py_ssize_t size,
4719 const char *errors,
4720 Py_ssize_t *consumed)
4721{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004722 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004723 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004725
4726 Py_ssize_t startinpos;
4727 Py_ssize_t endinpos;
4728 const char *errmsg = "";
4729 PyObject *errorHandler = NULL;
4730 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004731
4732 if (size == 0) {
4733 if (consumed)
4734 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004735 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004736 }
4737
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4739 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004740 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741 *consumed = 1;
4742 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004743 }
4744
Victor Stinner8f674cc2013-04-17 23:02:17 +02004745 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004746 writer.min_length = size;
4747 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004748 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004749
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004750 writer.pos = ascii_decode(s, end, writer.data);
4751 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004752 while (s < end) {
4753 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004756 if (PyUnicode_IS_ASCII(writer.buffer))
4757 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004759 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004761 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 } else {
4763 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004764 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765 }
4766
4767 switch (ch) {
4768 case 0:
4769 if (s == end || consumed)
4770 goto End;
4771 errmsg = "unexpected end of data";
4772 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004773 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774 break;
4775 case 1:
4776 errmsg = "invalid start byte";
4777 startinpos = s - starts;
4778 endinpos = startinpos + 1;
4779 break;
4780 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004781 case 3:
4782 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004783 errmsg = "invalid continuation byte";
4784 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004785 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004786 break;
4787 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004788 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004789 goto onError;
4790 continue;
4791 }
4792
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004793 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004794 errors, &errorHandler,
4795 "utf-8", errmsg,
4796 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004797 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004799 }
4800
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004802 if (consumed)
4803 *consumed = s - starts;
4804
4805 Py_XDECREF(errorHandler);
4806 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004807 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004808
4809onError:
4810 Py_XDECREF(errorHandler);
4811 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004812 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004814}
4815
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004816#ifdef __APPLE__
4817
4818/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004819 used to decode the command line arguments on Mac OS X.
4820
4821 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004822 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004823
4824wchar_t*
4825_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4826{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004827 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 wchar_t *unicode;
4829 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004830
4831 /* Note: size will always be longer than the resulting Unicode
4832 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004833 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004835 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 if (!unicode)
4837 return NULL;
4838
4839 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 if (ch > 0xFF) {
4850#if SIZEOF_WCHAR_T == 4
4851 assert(0);
4852#else
4853 assert(Py_UNICODE_IS_SURROGATE(ch));
4854 /* compute and append the two surrogates: */
4855 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4856 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4857#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004858 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004859 else {
4860 if (!ch && s == e)
4861 break;
4862 /* surrogateescape */
4863 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4864 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004867 return unicode;
4868}
4869
4870#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004872/* Primary internal function which creates utf8 encoded bytes objects.
4873
4874 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004875 and allocate exactly as much space needed at the end. Else allocate the
4876 maximum possible needed (4 result bytes per Unicode character), and return
4877 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004878*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004879PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004880_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004881{
Victor Stinner6099a032011-12-18 14:22:26 +01004882 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883 void *data;
4884 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886 if (!PyUnicode_Check(unicode)) {
4887 PyErr_BadArgument();
4888 return NULL;
4889 }
4890
4891 if (PyUnicode_READY(unicode) == -1)
4892 return NULL;
4893
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004894 if (PyUnicode_UTF8(unicode))
4895 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4896 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004897
4898 kind = PyUnicode_KIND(unicode);
4899 data = PyUnicode_DATA(unicode);
4900 size = PyUnicode_GET_LENGTH(unicode);
4901
Benjamin Petersonead6b532011-12-20 17:23:42 -06004902 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004903 default:
4904 assert(0);
4905 case PyUnicode_1BYTE_KIND:
4906 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4907 assert(!PyUnicode_IS_ASCII(unicode));
4908 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4909 case PyUnicode_2BYTE_KIND:
4910 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4911 case PyUnicode_4BYTE_KIND:
4912 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004913 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004914}
4915
Alexander Belopolsky40018472011-02-26 01:02:56 +00004916PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004917PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4918 Py_ssize_t size,
4919 const char *errors)
4920{
4921 PyObject *v, *unicode;
4922
4923 unicode = PyUnicode_FromUnicode(s, size);
4924 if (unicode == NULL)
4925 return NULL;
4926 v = _PyUnicode_AsUTF8String(unicode, errors);
4927 Py_DECREF(unicode);
4928 return v;
4929}
4930
4931PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004932PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004934 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004935}
4936
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937/* --- UTF-32 Codec ------------------------------------------------------- */
4938
4939PyObject *
4940PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004941 Py_ssize_t size,
4942 const char *errors,
4943 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004944{
4945 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4946}
4947
4948PyObject *
4949PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 Py_ssize_t size,
4951 const char *errors,
4952 int *byteorder,
4953 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004954{
4955 const char *starts = s;
4956 Py_ssize_t startinpos;
4957 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004958 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004959 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004960 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004961 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004962 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963 PyObject *errorHandler = NULL;
4964 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004965
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966 q = (unsigned char *)s;
4967 e = q + size;
4968
4969 if (byteorder)
4970 bo = *byteorder;
4971
4972 /* Check for BOM marks (U+FEFF) in the input and adjust current
4973 byte order setting accordingly. In native mode, the leading BOM
4974 mark is skipped, in all other modes, it is copied to the output
4975 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004976 if (bo == 0 && size >= 4) {
4977 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4978 if (bom == 0x0000FEFF) {
4979 bo = -1;
4980 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004981 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004982 else if (bom == 0xFFFE0000) {
4983 bo = 1;
4984 q += 4;
4985 }
4986 if (byteorder)
4987 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004988 }
4989
Victor Stinnere64322e2012-10-30 23:12:47 +01004990 if (q == e) {
4991 if (consumed)
4992 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004993 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004994 }
4995
Victor Stinnere64322e2012-10-30 23:12:47 +01004996#ifdef WORDS_BIGENDIAN
4997 le = bo < 0;
4998#else
4999 le = bo <= 0;
5000#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005001 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005002
Victor Stinner8f674cc2013-04-17 23:02:17 +02005003 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005004 writer.min_length = (e - q + 3) / 4;
5005 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005006 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005007
Victor Stinnere64322e2012-10-30 23:12:47 +01005008 while (1) {
5009 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005010 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005011
Victor Stinnere64322e2012-10-30 23:12:47 +01005012 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005013 enum PyUnicode_Kind kind = writer.kind;
5014 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005015 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005016 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005017 if (le) {
5018 do {
5019 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5020 if (ch > maxch)
5021 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005022 if (kind != PyUnicode_1BYTE_KIND &&
5023 Py_UNICODE_IS_SURROGATE(ch))
5024 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005025 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005026 q += 4;
5027 } while (q <= last);
5028 }
5029 else {
5030 do {
5031 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5032 if (ch > maxch)
5033 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005034 if (kind != PyUnicode_1BYTE_KIND &&
5035 Py_UNICODE_IS_SURROGATE(ch))
5036 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005037 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005038 q += 4;
5039 } while (q <= last);
5040 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005041 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005042 }
5043
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005044 if (Py_UNICODE_IS_SURROGATE(ch)) {
5045 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5046 startinpos = ((const char *)q) - starts;
5047 endinpos = startinpos + 4;
5048 }
5049 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005050 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005052 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005053 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005054 startinpos = ((const char *)q) - starts;
5055 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005057 else {
5058 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005059 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005060 goto onError;
5061 q += 4;
5062 continue;
5063 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005064 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005065 startinpos = ((const char *)q) - starts;
5066 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005067 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005068
5069 /* The remaining input chars are ignored if the callback
5070 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005071 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005073 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005074 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005075 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005076 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 }
5078
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081
Walter Dörwald41980ca2007-08-16 21:55:45 +00005082 Py_XDECREF(errorHandler);
5083 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005084 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085
Benjamin Peterson29060642009-01-31 22:14:21 +00005086 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005087 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088 Py_XDECREF(errorHandler);
5089 Py_XDECREF(exc);
5090 return NULL;
5091}
5092
5093PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005094_PyUnicode_EncodeUTF32(PyObject *str,
5095 const char *errors,
5096 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 int kind;
5099 void *data;
5100 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005101 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005102 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005103 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005105#if PY_LITTLE_ENDIAN
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106 int iorder[] = {0, 1, 2, 3};
5107#else
5108 int iorder[] = {3, 2, 1, 0};
5109#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005110 const char *encoding;
5111 PyObject *errorHandler = NULL;
5112 PyObject *exc = NULL;
5113 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114
Benjamin Peterson29060642009-01-31 22:14:21 +00005115#define STORECHAR(CH) \
5116 do { \
5117 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5118 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5119 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5120 p[iorder[0]] = (CH) & 0xff; \
5121 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122 } while(0)
5123
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005124 if (!PyUnicode_Check(str)) {
5125 PyErr_BadArgument();
5126 return NULL;
5127 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005128 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005129 return NULL;
5130 kind = PyUnicode_KIND(str);
5131 data = PyUnicode_DATA(str);
5132 len = PyUnicode_GET_LENGTH(str);
5133
5134 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005135 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005136 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005137 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138 if (v == NULL)
5139 return NULL;
5140
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005141 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005142 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005143 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005144 if (len == 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005145 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005146
5147 if (byteorder == -1) {
5148 /* force LE */
5149 iorder[0] = 0;
5150 iorder[1] = 1;
5151 iorder[2] = 2;
5152 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005153 encoding = "utf-32-le";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154 }
5155 else if (byteorder == 1) {
5156 /* force BE */
5157 iorder[0] = 3;
5158 iorder[1] = 2;
5159 iorder[2] = 1;
5160 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005161 encoding = "utf-32-be";
5162 }
5163 else
5164 encoding = "utf-32";
5165
5166 if (kind == PyUnicode_1BYTE_KIND) {
5167 for (i = 0; i < len; i++)
5168 STORECHAR(PyUnicode_READ(kind, data, i));
5169 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005170 }
5171
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005172 for (i = 0; i < len;) {
5173 Py_ssize_t repsize, moreunits;
5174 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5175 i++;
5176 assert(ch <= MAX_UNICODE);
5177 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5178 STORECHAR(ch);
5179 continue;
5180 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005181
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005182 rep = unicode_encode_call_errorhandler(
5183 errors, &errorHandler,
5184 encoding, "surrogates not allowed",
5185 str, &exc, i-1, i, &i);
5186
5187 if (!rep)
5188 goto error;
5189
5190 if (PyBytes_Check(rep)) {
5191 repsize = PyBytes_GET_SIZE(rep);
5192 if (repsize & 3) {
5193 raise_encode_exception(&exc, encoding,
5194 str, i - 1, i,
5195 "surrogates not allowed");
5196 goto error;
5197 }
5198 moreunits = repsize / 4;
5199 }
5200 else {
5201 assert(PyUnicode_Check(rep));
5202 if (PyUnicode_READY(rep) < 0)
5203 goto error;
5204 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5205 if (!PyUnicode_IS_ASCII(rep)) {
5206 raise_encode_exception(&exc, encoding,
5207 str, i - 1, i,
5208 "surrogates not allowed");
5209 goto error;
5210 }
5211 }
5212
5213 /* four bytes are reserved for each surrogate */
5214 if (moreunits > 1) {
5215 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
5216 Py_ssize_t morebytes = 4 * (moreunits - 1);
5217 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5218 /* integer overflow */
5219 PyErr_NoMemory();
5220 goto error;
5221 }
5222 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5223 goto error;
5224 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
5225 }
5226
5227 if (PyBytes_Check(rep)) {
5228 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5229 p += repsize;
5230 } else /* rep is unicode */ {
5231 const Py_UCS1 *repdata;
5232 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5233 repdata = PyUnicode_1BYTE_DATA(rep);
5234 while (repsize--) {
5235 Py_UCS4 ch = *repdata++;
5236 STORECHAR(ch);
5237 }
5238 }
5239
5240 Py_CLEAR(rep);
5241 }
5242
5243 /* Cut back to size actually needed. This is necessary for, for example,
5244 encoding of a string containing isolated surrogates and the 'ignore'
5245 handler is used. */
5246 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
5247 if (nsize != PyBytes_GET_SIZE(v))
5248 _PyBytes_Resize(&v, nsize);
5249 Py_XDECREF(errorHandler);
5250 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005251 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005252 error:
5253 Py_XDECREF(rep);
5254 Py_XDECREF(errorHandler);
5255 Py_XDECREF(exc);
5256 Py_XDECREF(v);
5257 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258#undef STORECHAR
5259}
5260
Alexander Belopolsky40018472011-02-26 01:02:56 +00005261PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005262PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5263 Py_ssize_t size,
5264 const char *errors,
5265 int byteorder)
5266{
5267 PyObject *result;
5268 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5269 if (tmp == NULL)
5270 return NULL;
5271 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5272 Py_DECREF(tmp);
5273 return result;
5274}
5275
5276PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005277PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005278{
Victor Stinnerb960b342011-11-20 19:12:52 +01005279 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005280}
5281
Guido van Rossumd57fd912000-03-10 22:53:23 +00005282/* --- UTF-16 Codec ------------------------------------------------------- */
5283
Tim Peters772747b2001-08-09 22:21:55 +00005284PyObject *
5285PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005286 Py_ssize_t size,
5287 const char *errors,
5288 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005289{
Walter Dörwald69652032004-09-07 20:24:22 +00005290 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5291}
5292
5293PyObject *
5294PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005295 Py_ssize_t size,
5296 const char *errors,
5297 int *byteorder,
5298 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005299{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005300 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005301 Py_ssize_t startinpos;
5302 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005303 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005304 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005305 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005306 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005307 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005308 PyObject *errorHandler = NULL;
5309 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005310 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005311
Tim Peters772747b2001-08-09 22:21:55 +00005312 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005313 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005314
5315 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005316 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005317
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005318 /* Check for BOM marks (U+FEFF) in the input and adjust current
5319 byte order setting accordingly. In native mode, the leading BOM
5320 mark is skipped, in all other modes, it is copied to the output
5321 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005322 if (bo == 0 && size >= 2) {
5323 const Py_UCS4 bom = (q[1] << 8) | q[0];
5324 if (bom == 0xFEFF) {
5325 q += 2;
5326 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328 else if (bom == 0xFFFE) {
5329 q += 2;
5330 bo = 1;
5331 }
5332 if (byteorder)
5333 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005334 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005335
Antoine Pitrou63065d72012-05-15 23:48:04 +02005336 if (q == e) {
5337 if (consumed)
5338 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005339 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005340 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005341
Christian Heimes743e0cd2012-10-17 23:52:17 +02005342#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005343 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005344 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005345#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005346 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005347 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005348#endif
Tim Peters772747b2001-08-09 22:21:55 +00005349
Antoine Pitrou63065d72012-05-15 23:48:04 +02005350 /* Note: size will always be longer than the resulting Unicode
5351 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005352 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005353 writer.min_length = (e - q + 1) / 2;
5354 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005355 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005356
Antoine Pitrou63065d72012-05-15 23:48:04 +02005357 while (1) {
5358 Py_UCS4 ch = 0;
5359 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005360 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005361 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005364 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005365 native_ordering);
5366 else
5367 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005368 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369 native_ordering);
5370 } else if (kind == PyUnicode_2BYTE_KIND) {
5371 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005372 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005373 native_ordering);
5374 } else {
5375 assert(kind == PyUnicode_4BYTE_KIND);
5376 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005377 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005378 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005379 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005380 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005381
Antoine Pitrou63065d72012-05-15 23:48:04 +02005382 switch (ch)
5383 {
5384 case 0:
5385 /* remaining byte at the end? (size should be even) */
5386 if (q == e || consumed)
5387 goto End;
5388 errmsg = "truncated data";
5389 startinpos = ((const char *)q) - starts;
5390 endinpos = ((const char *)e) - starts;
5391 break;
5392 /* The remaining input chars are ignored if the callback
5393 chooses to skip the input */
5394 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005395 q -= 2;
5396 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005397 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005398 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005399 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005400 endinpos = ((const char *)e) - starts;
5401 break;
5402 case 2:
5403 errmsg = "illegal encoding";
5404 startinpos = ((const char *)q) - 2 - starts;
5405 endinpos = startinpos + 2;
5406 break;
5407 case 3:
5408 errmsg = "illegal UTF-16 surrogate";
5409 startinpos = ((const char *)q) - 4 - starts;
5410 endinpos = startinpos + 2;
5411 break;
5412 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005413 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005414 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005415 continue;
5416 }
5417
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005418 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005419 errors,
5420 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005421 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005422 &starts,
5423 (const char **)&e,
5424 &startinpos,
5425 &endinpos,
5426 &exc,
5427 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005428 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005429 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430 }
5431
Antoine Pitrou63065d72012-05-15 23:48:04 +02005432End:
Walter Dörwald69652032004-09-07 20:24:22 +00005433 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005435
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005436 Py_XDECREF(errorHandler);
5437 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005438 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439
Benjamin Peterson29060642009-01-31 22:14:21 +00005440 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005441 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005442 Py_XDECREF(errorHandler);
5443 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444 return NULL;
5445}
5446
Tim Peters772747b2001-08-09 22:21:55 +00005447PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005448_PyUnicode_EncodeUTF16(PyObject *str,
5449 const char *errors,
5450 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005451{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005452 enum PyUnicode_Kind kind;
5453 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005454 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005455 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005456 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005457 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005458#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005460#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005461 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005462#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 const char *encoding;
5464 Py_ssize_t nsize, pos;
5465 PyObject *errorHandler = NULL;
5466 PyObject *exc = NULL;
5467 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005468
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005469 if (!PyUnicode_Check(str)) {
5470 PyErr_BadArgument();
5471 return NULL;
5472 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005473 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005474 return NULL;
5475 kind = PyUnicode_KIND(str);
5476 data = PyUnicode_DATA(str);
5477 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005478
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005479 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005480 if (kind == PyUnicode_4BYTE_KIND) {
5481 const Py_UCS4 *in = (const Py_UCS4 *)data;
5482 const Py_UCS4 *end = in + len;
5483 while (in < end)
5484 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005485 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005486 }
5487 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005488 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005489 nsize = len + pairs + (byteorder == 0);
5490 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491 if (v == NULL)
5492 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005494 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005495 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005496 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005498 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005499 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005500 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005501
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005502 if (kind == PyUnicode_1BYTE_KIND) {
5503 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5504 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005505 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005506
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005507 if (byteorder < 0)
5508 encoding = "utf-16-le";
5509 else if (byteorder > 0)
5510 encoding = "utf-16-be";
5511 else
5512 encoding = "utf-16";
5513
5514 pos = 0;
5515 while (pos < len) {
5516 Py_ssize_t repsize, moreunits;
5517
5518 if (kind == PyUnicode_2BYTE_KIND) {
5519 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5520 &out, native_ordering);
5521 }
5522 else {
5523 assert(kind == PyUnicode_4BYTE_KIND);
5524 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5525 &out, native_ordering);
5526 }
5527 if (pos == len)
5528 break;
5529
5530 rep = unicode_encode_call_errorhandler(
5531 errors, &errorHandler,
5532 encoding, "surrogates not allowed",
5533 str, &exc, pos, pos + 1, &pos);
5534 if (!rep)
5535 goto error;
5536
5537 if (PyBytes_Check(rep)) {
5538 repsize = PyBytes_GET_SIZE(rep);
5539 if (repsize & 1) {
5540 raise_encode_exception(&exc, encoding,
5541 str, pos - 1, pos,
5542 "surrogates not allowed");
5543 goto error;
5544 }
5545 moreunits = repsize / 2;
5546 }
5547 else {
5548 assert(PyUnicode_Check(rep));
5549 if (PyUnicode_READY(rep) < 0)
5550 goto error;
5551 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5552 if (!PyUnicode_IS_ASCII(rep)) {
5553 raise_encode_exception(&exc, encoding,
5554 str, pos - 1, pos,
5555 "surrogates not allowed");
5556 goto error;
5557 }
5558 }
5559
5560 /* two bytes are reserved for each surrogate */
5561 if (moreunits > 1) {
5562 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5563 Py_ssize_t morebytes = 2 * (moreunits - 1);
5564 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5565 /* integer overflow */
5566 PyErr_NoMemory();
5567 goto error;
5568 }
5569 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5570 goto error;
5571 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5572 }
5573
5574 if (PyBytes_Check(rep)) {
5575 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5576 out += moreunits;
5577 } else /* rep is unicode */ {
5578 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5579 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5580 &out, native_ordering);
5581 }
5582
5583 Py_CLEAR(rep);
5584 }
5585
5586 /* Cut back to size actually needed. This is necessary for, for example,
5587 encoding of a string containing isolated surrogates and the 'ignore' handler
5588 is used. */
5589 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5590 if (nsize != PyBytes_GET_SIZE(v))
5591 _PyBytes_Resize(&v, nsize);
5592 Py_XDECREF(errorHandler);
5593 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005594 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005595 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005596 error:
5597 Py_XDECREF(rep);
5598 Py_XDECREF(errorHandler);
5599 Py_XDECREF(exc);
5600 Py_XDECREF(v);
5601 return NULL;
5602#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005603}
5604
Alexander Belopolsky40018472011-02-26 01:02:56 +00005605PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005606PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5607 Py_ssize_t size,
5608 const char *errors,
5609 int byteorder)
5610{
5611 PyObject *result;
5612 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5613 if (tmp == NULL)
5614 return NULL;
5615 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5616 Py_DECREF(tmp);
5617 return result;
5618}
5619
5620PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005621PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005623 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624}
5625
5626/* --- Unicode Escape Codec ----------------------------------------------- */
5627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005628/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5629 if all the escapes in the string make it still a valid ASCII string.
5630 Returns -1 if any escapes were found which cause the string to
5631 pop out of ASCII range. Otherwise returns the length of the
5632 required buffer to hold the string.
5633 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005634static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005635length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5636{
5637 const unsigned char *p = (const unsigned char *)s;
5638 const unsigned char *end = p + size;
5639 Py_ssize_t length = 0;
5640
5641 if (size < 0)
5642 return -1;
5643
5644 for (; p < end; ++p) {
5645 if (*p > 127) {
5646 /* Non-ASCII */
5647 return -1;
5648 }
5649 else if (*p != '\\') {
5650 /* Normal character */
5651 ++length;
5652 }
5653 else {
5654 /* Backslash-escape, check next char */
5655 ++p;
5656 /* Escape sequence reaches till end of string or
5657 non-ASCII follow-up. */
5658 if (p >= end || *p > 127)
5659 return -1;
5660 switch (*p) {
5661 case '\n':
5662 /* backslash + \n result in zero characters */
5663 break;
5664 case '\\': case '\'': case '\"':
5665 case 'b': case 'f': case 't':
5666 case 'n': case 'r': case 'v': case 'a':
5667 ++length;
5668 break;
5669 case '0': case '1': case '2': case '3':
5670 case '4': case '5': case '6': case '7':
5671 case 'x': case 'u': case 'U': case 'N':
5672 /* these do not guarantee ASCII characters */
5673 return -1;
5674 default:
5675 /* count the backslash + the other character */
5676 length += 2;
5677 }
5678 }
5679 }
5680 return length;
5681}
5682
Fredrik Lundh06d12682001-01-24 07:59:11 +00005683static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005684
Alexander Belopolsky40018472011-02-26 01:02:56 +00005685PyObject *
5686PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005687 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005688 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005690 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005691 Py_ssize_t startinpos;
5692 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005693 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005695 char* message;
5696 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005697 PyObject *errorHandler = NULL;
5698 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005699 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005700
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005702 if (len == 0)
5703 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704
5705 /* After length_of_escaped_ascii_string() there are two alternatives,
5706 either the string is pure ASCII with named escapes like \n, etc.
5707 and we determined it's exact size (common case)
5708 or it contains \x, \u, ... escape sequences. then we create a
5709 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005710 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005711 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005712 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005713 }
5714 else {
5715 /* Escaped strings will always be longer than the resulting
5716 Unicode string, so we start with size here and then reduce the
5717 length after conversion to the true value.
5718 (but if the error callback returns a long replacement string
5719 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005720 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005721 }
5722
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005724 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005726
Guido van Rossumd57fd912000-03-10 22:53:23 +00005727 while (s < end) {
5728 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005729 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005730 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731
5732 /* Non-escape characters are interpreted as Unicode ordinals */
5733 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005734 x = (unsigned char)*s;
5735 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005736 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005737 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 continue;
5739 }
5740
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005741 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742 /* \ - Escapes */
5743 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005744 c = *s++;
5745 if (s > end)
5746 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005747
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005748 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749
Benjamin Peterson29060642009-01-31 22:14:21 +00005750 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005751#define WRITECHAR(ch) \
5752 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005753 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005754 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005755 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005756
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005758 case '\\': WRITECHAR('\\'); break;
5759 case '\'': WRITECHAR('\''); break;
5760 case '\"': WRITECHAR('\"'); break;
5761 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005762 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005763 case 'f': WRITECHAR('\014'); break;
5764 case 't': WRITECHAR('\t'); break;
5765 case 'n': WRITECHAR('\n'); break;
5766 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005768 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005770 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771
Benjamin Peterson29060642009-01-31 22:14:21 +00005772 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773 case '0': case '1': case '2': case '3':
5774 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005775 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005776 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005777 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005778 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005779 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005781 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005782 break;
5783
Benjamin Peterson29060642009-01-31 22:14:21 +00005784 /* hex escapes */
5785 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005787 digits = 2;
5788 message = "truncated \\xXX escape";
5789 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005793 digits = 4;
5794 message = "truncated \\uXXXX escape";
5795 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796
Benjamin Peterson29060642009-01-31 22:14:21 +00005797 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005798 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 digits = 8;
5800 message = "truncated \\UXXXXXXXX escape";
5801 hexescape:
5802 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005803 if (end - s < digits) {
5804 /* count only hex digits */
5805 for (; s < end; ++s) {
5806 c = (unsigned char)*s;
5807 if (!Py_ISXDIGIT(c))
5808 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005809 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005810 goto error;
5811 }
5812 for (; digits--; ++s) {
5813 c = (unsigned char)*s;
5814 if (!Py_ISXDIGIT(c))
5815 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005816 chr = (chr<<4) & ~0xF;
5817 if (c >= '0' && c <= '9')
5818 chr += c - '0';
5819 else if (c >= 'a' && c <= 'f')
5820 chr += 10 + c - 'a';
5821 else
5822 chr += 10 + c - 'A';
5823 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005824 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005825 /* _decoding_error will have already written into the
5826 target buffer. */
5827 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005828 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005829 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005830 message = "illegal Unicode character";
5831 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005832 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005833 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 break;
5835
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837 case 'N':
5838 message = "malformed \\N character escape";
5839 if (ucnhash_CAPI == NULL) {
5840 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005841 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5842 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005843 if (ucnhash_CAPI == NULL)
5844 goto ucnhashError;
5845 }
5846 if (*s == '{') {
5847 const char *start = s+1;
5848 /* look for the closing brace */
5849 while (*s != '}' && s < end)
5850 s++;
5851 if (s > start && s < end && *s == '}') {
5852 /* found a name. look it up in the unicode database */
5853 message = "unknown Unicode character name";
5854 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005855 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005856 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005857 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005858 goto store;
5859 }
5860 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005861 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005862
5863 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005864 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 message = "\\ at end of string";
5866 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005867 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005868 }
5869 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005870 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005871 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005872 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005873 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005875 continue;
5876
5877 error:
5878 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005879 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005880 errors, &errorHandler,
5881 "unicodeescape", message,
5882 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005883 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005884 goto onError;
5885 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005887#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005888
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005889 Py_XDECREF(errorHandler);
5890 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005891 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005892
Benjamin Peterson29060642009-01-31 22:14:21 +00005893 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005894 PyErr_SetString(
5895 PyExc_UnicodeError,
5896 "\\N escapes not supported (can't load unicodedata module)"
5897 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005898 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005899 Py_XDECREF(errorHandler);
5900 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005901 return NULL;
5902
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005904 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005905 Py_XDECREF(errorHandler);
5906 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907 return NULL;
5908}
5909
5910/* Return a Unicode-Escape string version of the Unicode object.
5911
5912 If quotes is true, the string is enclosed in u"" or u'' quotes as
5913 appropriate.
5914
5915*/
5916
Alexander Belopolsky40018472011-02-26 01:02:56 +00005917PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005918PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005920 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005921 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005923 int kind;
5924 void *data;
5925 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926
Ezio Melottie7f90372012-10-05 03:33:31 +03005927 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005928 escape.
5929
Ezio Melottie7f90372012-10-05 03:33:31 +03005930 For UCS1 strings it's '\xxx', 4 bytes per source character.
5931 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5932 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005933 */
5934
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005935 if (!PyUnicode_Check(unicode)) {
5936 PyErr_BadArgument();
5937 return NULL;
5938 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005939 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005940 return NULL;
5941 len = PyUnicode_GET_LENGTH(unicode);
5942 kind = PyUnicode_KIND(unicode);
5943 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005944 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005945 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5946 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5947 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5948 }
5949
5950 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005951 return PyBytes_FromStringAndSize(NULL, 0);
5952
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005953 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005954 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005955
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005956 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005958 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 if (repr == NULL)
5961 return NULL;
5962
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005963 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005965 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005966 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005967
Walter Dörwald79e913e2007-05-12 11:08:06 +00005968 /* Escape backslashes */
5969 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 *p++ = '\\';
5971 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005972 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005973 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005974
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005975 /* Map 21-bit characters to '\U00xxxxxx' */
5976 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005977 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005978 *p++ = '\\';
5979 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005980 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5981 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5982 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5983 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5984 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5985 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5986 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5987 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005989 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005990
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005992 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 *p++ = '\\';
5994 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005995 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5996 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5997 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5998 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006000
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006001 /* Map special whitespace to '\t', \n', '\r' */
6002 else if (ch == '\t') {
6003 *p++ = '\\';
6004 *p++ = 't';
6005 }
6006 else if (ch == '\n') {
6007 *p++ = '\\';
6008 *p++ = 'n';
6009 }
6010 else if (ch == '\r') {
6011 *p++ = '\\';
6012 *p++ = 'r';
6013 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006014
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006015 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006016 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006018 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006019 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6020 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006021 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006022
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 /* Copy everything else as-is */
6024 else
6025 *p++ = (char) ch;
6026 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006028 assert(p - PyBytes_AS_STRING(repr) > 0);
6029 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6030 return NULL;
6031 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032}
6033
Alexander Belopolsky40018472011-02-26 01:02:56 +00006034PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006035PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6036 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038 PyObject *result;
6039 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6040 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042 result = PyUnicode_AsUnicodeEscapeString(tmp);
6043 Py_DECREF(tmp);
6044 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045}
6046
6047/* --- Raw Unicode Escape Codec ------------------------------------------- */
6048
Alexander Belopolsky40018472011-02-26 01:02:56 +00006049PyObject *
6050PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006051 Py_ssize_t size,
6052 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006054 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006055 Py_ssize_t startinpos;
6056 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006057 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 const char *end;
6059 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 PyObject *errorHandler = NULL;
6061 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006062
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006063 if (size == 0)
6064 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006065
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066 /* Escaped strings will always be longer than the resulting
6067 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006068 length after conversion to the true value. (But decoding error
6069 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006070 _PyUnicodeWriter_Init(&writer);
6071 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006072
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 end = s + size;
6074 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 unsigned char c;
6076 Py_UCS4 x;
6077 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006078 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 /* Non-escape characters are interpreted as Unicode ordinals */
6081 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006082 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006083 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006084 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006086 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 startinpos = s-starts;
6088
6089 /* \u-escapes are only interpreted iff the number of leading
6090 backslashes if odd */
6091 bs = s;
6092 for (;s < end;) {
6093 if (*s != '\\')
6094 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006095 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006096 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006097 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 }
6099 if (((s - bs) & 1) == 0 ||
6100 s >= end ||
6101 (*s != 'u' && *s != 'U')) {
6102 continue;
6103 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006104 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 count = *s=='u' ? 4 : 8;
6106 s++;
6107
6108 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 for (x = 0, i = 0; i < count; ++i, ++s) {
6110 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006111 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006113 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 errors, &errorHandler,
6115 "rawunicodeescape", "truncated \\uXXXX",
6116 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006117 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 goto onError;
6119 goto nextByte;
6120 }
6121 x = (x<<4) & ~0xF;
6122 if (c >= '0' && c <= '9')
6123 x += c - '0';
6124 else if (c >= 'a' && c <= 'f')
6125 x += 10 + c - 'a';
6126 else
6127 x += 10 + c - 'A';
6128 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006129 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006130 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006131 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006132 }
6133 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006134 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006135 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006136 errors, &errorHandler,
6137 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006139 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006141 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006142 nextByte:
6143 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006145 Py_XDECREF(errorHandler);
6146 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006147 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006148
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006150 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006151 Py_XDECREF(errorHandler);
6152 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153 return NULL;
6154}
6155
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156
Alexander Belopolsky40018472011-02-26 01:02:56 +00006157PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006158PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006160 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161 char *p;
6162 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006163 Py_ssize_t expandsize, pos;
6164 int kind;
6165 void *data;
6166 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168 if (!PyUnicode_Check(unicode)) {
6169 PyErr_BadArgument();
6170 return NULL;
6171 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006172 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006173 return NULL;
6174 kind = PyUnicode_KIND(unicode);
6175 data = PyUnicode_DATA(unicode);
6176 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006177 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6178 bytes, and 1 byte characters 4. */
6179 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006180
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006181 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006182 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006183
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006184 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006185 if (repr == NULL)
6186 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006188 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006190 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191 for (pos = 0; pos < len; pos++) {
6192 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006193 /* Map 32-bit characters to '\Uxxxxxxxx' */
6194 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006195 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006196 *p++ = '\\';
6197 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006198 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6199 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6200 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6201 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6202 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6203 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6204 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6205 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006206 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006208 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209 *p++ = '\\';
6210 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006211 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6212 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6213 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6214 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006216 /* Copy everything else as-is */
6217 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006218 *p++ = (char) ch;
6219 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006220
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006221 assert(p > q);
6222 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006223 return NULL;
6224 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225}
6226
Alexander Belopolsky40018472011-02-26 01:02:56 +00006227PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006228PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6229 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006231 PyObject *result;
6232 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6233 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006234 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006235 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6236 Py_DECREF(tmp);
6237 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238}
6239
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006240/* --- Unicode Internal Codec ------------------------------------------- */
6241
Alexander Belopolsky40018472011-02-26 01:02:56 +00006242PyObject *
6243_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006244 Py_ssize_t size,
6245 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246{
6247 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006248 Py_ssize_t startinpos;
6249 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006250 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006251 const char *end;
6252 const char *reason;
6253 PyObject *errorHandler = NULL;
6254 PyObject *exc = NULL;
6255
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006256 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006257 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006258 1))
6259 return NULL;
6260
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006261 if (size == 0)
6262 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006263
Victor Stinner8f674cc2013-04-17 23:02:17 +02006264 _PyUnicodeWriter_Init(&writer);
6265 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6266 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006268 }
6269 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270
Victor Stinner8f674cc2013-04-17 23:02:17 +02006271 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006272 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006273 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006274 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006275 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006276 endinpos = end-starts;
6277 reason = "truncated input";
6278 goto error;
6279 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006280 /* We copy the raw representation one byte at a time because the
6281 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006282 ((char *) &uch)[0] = s[0];
6283 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006284#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006285 ((char *) &uch)[2] = s[2];
6286 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006287#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006288 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006289#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006290 /* We have to sanity check the raw data, otherwise doom looms for
6291 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006292 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006293 endinpos = s - starts + Py_UNICODE_SIZE;
6294 reason = "illegal code point (> 0x10FFFF)";
6295 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006296 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006297#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006298 s += Py_UNICODE_SIZE;
6299#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006300 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006301 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006302 Py_UNICODE uch2;
6303 ((char *) &uch2)[0] = s[0];
6304 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006305 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006306 {
Victor Stinner551ac952011-11-29 22:58:13 +01006307 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006308 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006309 }
6310 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006311#endif
6312
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006313 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006314 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006315 continue;
6316
6317 error:
6318 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006319 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006320 errors, &errorHandler,
6321 "unicode_internal", reason,
6322 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006323 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006324 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325 }
6326
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006327 Py_XDECREF(errorHandler);
6328 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006329 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006330
Benjamin Peterson29060642009-01-31 22:14:21 +00006331 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006332 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 Py_XDECREF(errorHandler);
6334 Py_XDECREF(exc);
6335 return NULL;
6336}
6337
Guido van Rossumd57fd912000-03-10 22:53:23 +00006338/* --- Latin-1 Codec ------------------------------------------------------ */
6339
Alexander Belopolsky40018472011-02-26 01:02:56 +00006340PyObject *
6341PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006342 Py_ssize_t size,
6343 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006346 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347}
6348
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006350static void
6351make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006352 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006353 PyObject *unicode,
6354 Py_ssize_t startpos, Py_ssize_t endpos,
6355 const char *reason)
6356{
6357 if (*exceptionObject == NULL) {
6358 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006360 encoding, unicode, startpos, endpos, reason);
6361 }
6362 else {
6363 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6364 goto onError;
6365 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6366 goto onError;
6367 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6368 goto onError;
6369 return;
6370 onError:
6371 Py_DECREF(*exceptionObject);
6372 *exceptionObject = NULL;
6373 }
6374}
6375
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006376/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006377static void
6378raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006379 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006380 PyObject *unicode,
6381 Py_ssize_t startpos, Py_ssize_t endpos,
6382 const char *reason)
6383{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006384 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006385 encoding, unicode, startpos, endpos, reason);
6386 if (*exceptionObject != NULL)
6387 PyCodec_StrictErrors(*exceptionObject);
6388}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389
6390/* error handling callback helper:
6391 build arguments, call the callback and check the arguments,
6392 put the result into newpos and return the replacement string, which
6393 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006394static PyObject *
6395unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006396 PyObject **errorHandler,
6397 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006398 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006399 Py_ssize_t startpos, Py_ssize_t endpos,
6400 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006402 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404 PyObject *restuple;
6405 PyObject *resunicode;
6406
6407 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 }
6412
Benjamin Petersonbac79492012-01-14 13:34:47 -05006413 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006414 return NULL;
6415 len = PyUnicode_GET_LENGTH(unicode);
6416
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006417 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006418 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006421
6422 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006427 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 Py_DECREF(restuple);
6429 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006431 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 &resunicode, newpos)) {
6433 Py_DECREF(restuple);
6434 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006436 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6437 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6438 Py_DECREF(restuple);
6439 return NULL;
6440 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006442 *newpos = len + *newpos;
6443 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006444 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6445 Py_DECREF(restuple);
6446 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006447 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006448 Py_INCREF(resunicode);
6449 Py_DECREF(restuple);
6450 return resunicode;
6451}
6452
Alexander Belopolsky40018472011-02-26 01:02:56 +00006453static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006454unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006455 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006456 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006457{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006458 /* input state */
6459 Py_ssize_t pos=0, size;
6460 int kind;
6461 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462 /* output object */
6463 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464 /* pointer into the output */
6465 char *str;
6466 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006467 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006468 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6469 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470 PyObject *errorHandler = NULL;
6471 PyObject *exc = NULL;
6472 /* the following variable is used for caching string comparisons
6473 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6474 int known_errorHandler = -1;
6475
Benjamin Petersonbac79492012-01-14 13:34:47 -05006476 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006477 return NULL;
6478 size = PyUnicode_GET_LENGTH(unicode);
6479 kind = PyUnicode_KIND(unicode);
6480 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006481 /* allocate enough for a simple encoding without
6482 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006483 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006484 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006485 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006487 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006488 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006489 ressize = size;
6490
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 while (pos < size) {
6492 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493
Benjamin Peterson29060642009-01-31 22:14:21 +00006494 /* can we encode this? */
6495 if (c<limit) {
6496 /* no overflow check, because we know that the space is enough */
6497 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006498 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006499 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 Py_ssize_t requiredsize;
6502 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 Py_ssize_t collstart = pos;
6506 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 ++collend;
6510 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6511 if (known_errorHandler==-1) {
6512 if ((errors==NULL) || (!strcmp(errors, "strict")))
6513 known_errorHandler = 1;
6514 else if (!strcmp(errors, "replace"))
6515 known_errorHandler = 2;
6516 else if (!strcmp(errors, "ignore"))
6517 known_errorHandler = 3;
6518 else if (!strcmp(errors, "xmlcharrefreplace"))
6519 known_errorHandler = 4;
6520 else
6521 known_errorHandler = 0;
6522 }
6523 switch (known_errorHandler) {
6524 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006525 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 goto onError;
6527 case 2: /* replace */
6528 while (collstart++<collend)
6529 *str++ = '?'; /* fall through */
6530 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 break;
6533 case 4: /* xmlcharrefreplace */
6534 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 /* determine replacement size */
6536 for (i = collstart, repsize = 0; i < collend; ++i) {
6537 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6538 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006540 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006541 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006542 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006545 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006550 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006551 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006553 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 if (requiredsize > ressize) {
6557 if (requiredsize<2*ressize)
6558 requiredsize = 2*ressize;
6559 if (_PyBytes_Resize(&res, requiredsize))
6560 goto onError;
6561 str = PyBytes_AS_STRING(res) + respos;
6562 ressize = requiredsize;
6563 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 /* generate replacement */
6565 for (i = collstart; i < collend; ++i) {
6566 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006568 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 break;
6570 default:
6571 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006572 encoding, reason, unicode, &exc,
6573 collstart, collend, &newpos);
6574 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006575 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006577 if (PyBytes_Check(repunicode)) {
6578 /* Directly copy bytes result to output. */
6579 repsize = PyBytes_Size(repunicode);
6580 if (repsize > 1) {
6581 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006582 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006583 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6584 Py_DECREF(repunicode);
6585 goto onError;
6586 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006587 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006588 ressize += repsize-1;
6589 }
6590 memcpy(str, PyBytes_AsString(repunicode), repsize);
6591 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006593 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006594 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006595 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 /* need more space? (at least enough for what we
6597 have+the replacement+the rest of the string, so
6598 we won't have to check space for encodable characters) */
6599 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006600 repsize = PyUnicode_GET_LENGTH(repunicode);
6601 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 if (requiredsize > ressize) {
6603 if (requiredsize<2*ressize)
6604 requiredsize = 2*ressize;
6605 if (_PyBytes_Resize(&res, requiredsize)) {
6606 Py_DECREF(repunicode);
6607 goto onError;
6608 }
6609 str = PyBytes_AS_STRING(res) + respos;
6610 ressize = requiredsize;
6611 }
6612 /* check if there is anything unencodable in the replacement
6613 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614 for (i = 0; repsize-->0; ++i, ++str) {
6615 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006617 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006618 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006619 Py_DECREF(repunicode);
6620 goto onError;
6621 }
6622 *str = (char)c;
6623 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006625 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006626 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006627 }
6628 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006629 /* Resize if we allocated to much */
6630 size = str - PyBytes_AS_STRING(res);
6631 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006632 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006633 if (_PyBytes_Resize(&res, size) < 0)
6634 goto onError;
6635 }
6636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 Py_XDECREF(errorHandler);
6638 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006639 return res;
6640
6641 onError:
6642 Py_XDECREF(res);
6643 Py_XDECREF(errorHandler);
6644 Py_XDECREF(exc);
6645 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646}
6647
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006648/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006649PyObject *
6650PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006651 Py_ssize_t size,
6652 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 PyObject *result;
6655 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6656 if (unicode == NULL)
6657 return NULL;
6658 result = unicode_encode_ucs1(unicode, errors, 256);
6659 Py_DECREF(unicode);
6660 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006661}
6662
Alexander Belopolsky40018472011-02-26 01:02:56 +00006663PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006664_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006665{
6666 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 PyErr_BadArgument();
6668 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006669 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006670 if (PyUnicode_READY(unicode) == -1)
6671 return NULL;
6672 /* Fast path: if it is a one-byte string, construct
6673 bytes object directly. */
6674 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6675 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6676 PyUnicode_GET_LENGTH(unicode));
6677 /* Non-Latin-1 characters present. Defer to above function to
6678 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006679 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006680}
6681
6682PyObject*
6683PyUnicode_AsLatin1String(PyObject *unicode)
6684{
6685 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006686}
6687
6688/* --- 7-bit ASCII Codec -------------------------------------------------- */
6689
Alexander Belopolsky40018472011-02-26 01:02:56 +00006690PyObject *
6691PyUnicode_DecodeASCII(const char *s,
6692 Py_ssize_t size,
6693 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006696 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006697 int kind;
6698 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006699 Py_ssize_t startinpos;
6700 Py_ssize_t endinpos;
6701 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006702 const char *e;
6703 PyObject *errorHandler = NULL;
6704 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006705
Guido van Rossumd57fd912000-03-10 22:53:23 +00006706 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006707 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006708
Guido van Rossumd57fd912000-03-10 22:53:23 +00006709 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006710 if (size == 1 && (unsigned char)s[0] < 128)
6711 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006712
Victor Stinner8f674cc2013-04-17 23:02:17 +02006713 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006714 writer.min_length = size;
6715 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006716 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006717
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006719 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006720 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006721 writer.pos = outpos;
6722 if (writer.pos == size)
6723 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006724
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006725 s += writer.pos;
6726 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006727 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006728 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006730 PyUnicode_WRITE(kind, data, writer.pos, c);
6731 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 ++s;
6733 }
6734 else {
6735 startinpos = s-starts;
6736 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006737 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 errors, &errorHandler,
6739 "ascii", "ordinal not in range(128)",
6740 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006741 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006743 kind = writer.kind;
6744 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006746 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006747 Py_XDECREF(errorHandler);
6748 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006749 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006750
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006752 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006753 Py_XDECREF(errorHandler);
6754 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006755 return NULL;
6756}
6757
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006759PyObject *
6760PyUnicode_EncodeASCII(const Py_UNICODE *p,
6761 Py_ssize_t size,
6762 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006763{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006764 PyObject *result;
6765 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6766 if (unicode == NULL)
6767 return NULL;
6768 result = unicode_encode_ucs1(unicode, errors, 128);
6769 Py_DECREF(unicode);
6770 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006771}
6772
Alexander Belopolsky40018472011-02-26 01:02:56 +00006773PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006774_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006775{
6776 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 PyErr_BadArgument();
6778 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006779 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006780 if (PyUnicode_READY(unicode) == -1)
6781 return NULL;
6782 /* Fast path: if it is an ASCII-only string, construct bytes object
6783 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006784 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006785 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6786 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006787 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006788}
6789
6790PyObject *
6791PyUnicode_AsASCIIString(PyObject *unicode)
6792{
6793 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006794}
6795
Victor Stinner99b95382011-07-04 14:23:54 +02006796#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006797
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006798/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006799
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006800#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006801#define NEED_RETRY
6802#endif
6803
Victor Stinner3a50e702011-10-18 21:21:00 +02006804#ifndef WC_ERR_INVALID_CHARS
6805# define WC_ERR_INVALID_CHARS 0x0080
6806#endif
6807
6808static char*
6809code_page_name(UINT code_page, PyObject **obj)
6810{
6811 *obj = NULL;
6812 if (code_page == CP_ACP)
6813 return "mbcs";
6814 if (code_page == CP_UTF7)
6815 return "CP_UTF7";
6816 if (code_page == CP_UTF8)
6817 return "CP_UTF8";
6818
6819 *obj = PyBytes_FromFormat("cp%u", code_page);
6820 if (*obj == NULL)
6821 return NULL;
6822 return PyBytes_AS_STRING(*obj);
6823}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006824
Alexander Belopolsky40018472011-02-26 01:02:56 +00006825static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006826is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827{
6828 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006829 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006830
Victor Stinner3a50e702011-10-18 21:21:00 +02006831 if (!IsDBCSLeadByteEx(code_page, *curr))
6832 return 0;
6833
6834 prev = CharPrevExA(code_page, s, curr, 0);
6835 if (prev == curr)
6836 return 1;
6837 /* FIXME: This code is limited to "true" double-byte encodings,
6838 as it assumes an incomplete character consists of a single
6839 byte. */
6840 if (curr - prev == 2)
6841 return 1;
6842 if (!IsDBCSLeadByteEx(code_page, *prev))
6843 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006844 return 0;
6845}
6846
Victor Stinner3a50e702011-10-18 21:21:00 +02006847static DWORD
6848decode_code_page_flags(UINT code_page)
6849{
6850 if (code_page == CP_UTF7) {
6851 /* The CP_UTF7 decoder only supports flags=0 */
6852 return 0;
6853 }
6854 else
6855 return MB_ERR_INVALID_CHARS;
6856}
6857
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006858/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006859 * Decode a byte string from a Windows code page into unicode object in strict
6860 * mode.
6861 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006862 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6863 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006864 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006865static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006866decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006867 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006868 const char *in,
6869 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006870{
Victor Stinner3a50e702011-10-18 21:21:00 +02006871 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006872 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006873 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874
6875 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006876 assert(insize > 0);
6877 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6878 if (outsize <= 0)
6879 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880
6881 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006883 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006884 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006885 if (*v == NULL)
6886 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006887 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006888 }
6889 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006890 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006891 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006892 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006893 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006894 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006895 }
6896
6897 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006898 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6899 if (outsize <= 0)
6900 goto error;
6901 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006902
Victor Stinner3a50e702011-10-18 21:21:00 +02006903error:
6904 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6905 return -2;
6906 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006907 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006908}
6909
Victor Stinner3a50e702011-10-18 21:21:00 +02006910/*
6911 * Decode a byte string from a code page into unicode object with an error
6912 * handler.
6913 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006914 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006915 * UnicodeDecodeError exception and returns -1 on error.
6916 */
6917static int
6918decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006919 PyObject **v,
6920 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006921 const char *errors)
6922{
6923 const char *startin = in;
6924 const char *endin = in + size;
6925 const DWORD flags = decode_code_page_flags(code_page);
6926 /* Ideally, we should get reason from FormatMessage. This is the Windows
6927 2000 English version of the message. */
6928 const char *reason = "No mapping for the Unicode character exists "
6929 "in the target code page.";
6930 /* each step cannot decode more than 1 character, but a character can be
6931 represented as a surrogate pair */
6932 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006933 int insize;
6934 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006935 PyObject *errorHandler = NULL;
6936 PyObject *exc = NULL;
6937 PyObject *encoding_obj = NULL;
6938 char *encoding;
6939 DWORD err;
6940 int ret = -1;
6941
6942 assert(size > 0);
6943
6944 encoding = code_page_name(code_page, &encoding_obj);
6945 if (encoding == NULL)
6946 return -1;
6947
6948 if (errors == NULL || strcmp(errors, "strict") == 0) {
6949 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6950 UnicodeDecodeError. */
6951 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6952 if (exc != NULL) {
6953 PyCodec_StrictErrors(exc);
6954 Py_CLEAR(exc);
6955 }
6956 goto error;
6957 }
6958
6959 if (*v == NULL) {
6960 /* Create unicode object */
6961 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6962 PyErr_NoMemory();
6963 goto error;
6964 }
Victor Stinnerab595942011-12-17 04:59:06 +01006965 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006966 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006967 if (*v == NULL)
6968 goto error;
6969 startout = PyUnicode_AS_UNICODE(*v);
6970 }
6971 else {
6972 /* Extend unicode object */
6973 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6974 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6975 PyErr_NoMemory();
6976 goto error;
6977 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006978 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006979 goto error;
6980 startout = PyUnicode_AS_UNICODE(*v) + n;
6981 }
6982
6983 /* Decode the byte string character per character */
6984 out = startout;
6985 while (in < endin)
6986 {
6987 /* Decode a character */
6988 insize = 1;
6989 do
6990 {
6991 outsize = MultiByteToWideChar(code_page, flags,
6992 in, insize,
6993 buffer, Py_ARRAY_LENGTH(buffer));
6994 if (outsize > 0)
6995 break;
6996 err = GetLastError();
6997 if (err != ERROR_NO_UNICODE_TRANSLATION
6998 && err != ERROR_INSUFFICIENT_BUFFER)
6999 {
7000 PyErr_SetFromWindowsErr(0);
7001 goto error;
7002 }
7003 insize++;
7004 }
7005 /* 4=maximum length of a UTF-8 sequence */
7006 while (insize <= 4 && (in + insize) <= endin);
7007
7008 if (outsize <= 0) {
7009 Py_ssize_t startinpos, endinpos, outpos;
7010
7011 startinpos = in - startin;
7012 endinpos = startinpos + 1;
7013 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007014 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007015 errors, &errorHandler,
7016 encoding, reason,
7017 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007018 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007019 {
7020 goto error;
7021 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007022 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007023 }
7024 else {
7025 in += insize;
7026 memcpy(out, buffer, outsize * sizeof(wchar_t));
7027 out += outsize;
7028 }
7029 }
7030
7031 /* write a NUL character at the end */
7032 *out = 0;
7033
7034 /* Extend unicode object */
7035 outsize = out - startout;
7036 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007037 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007039 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007040
7041error:
7042 Py_XDECREF(encoding_obj);
7043 Py_XDECREF(errorHandler);
7044 Py_XDECREF(exc);
7045 return ret;
7046}
7047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048static PyObject *
7049decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007050 const char *s, Py_ssize_t size,
7051 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052{
Victor Stinner76a31a62011-11-04 00:05:13 +01007053 PyObject *v = NULL;
7054 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007055
Victor Stinner3a50e702011-10-18 21:21:00 +02007056 if (code_page < 0) {
7057 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7058 return NULL;
7059 }
7060
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007061 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007062 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
Victor Stinner76a31a62011-11-04 00:05:13 +01007064 do
7065 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007066#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007067 if (size > INT_MAX) {
7068 chunk_size = INT_MAX;
7069 final = 0;
7070 done = 0;
7071 }
7072 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007074 {
7075 chunk_size = (int)size;
7076 final = (consumed == NULL);
7077 done = 1;
7078 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 /* Skip trailing lead-byte unless 'final' is set */
7081 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7082 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007083
Victor Stinner76a31a62011-11-04 00:05:13 +01007084 if (chunk_size == 0 && done) {
7085 if (v != NULL)
7086 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007087 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007088 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
Victor Stinner76a31a62011-11-04 00:05:13 +01007090
7091 converted = decode_code_page_strict(code_page, &v,
7092 s, chunk_size);
7093 if (converted == -2)
7094 converted = decode_code_page_errors(code_page, &v,
7095 s, chunk_size,
7096 errors);
7097 assert(converted != 0);
7098
7099 if (converted < 0) {
7100 Py_XDECREF(v);
7101 return NULL;
7102 }
7103
7104 if (consumed)
7105 *consumed += converted;
7106
7107 s += converted;
7108 size -= converted;
7109 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007110
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007111 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112}
7113
Alexander Belopolsky40018472011-02-26 01:02:56 +00007114PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007115PyUnicode_DecodeCodePageStateful(int code_page,
7116 const char *s,
7117 Py_ssize_t size,
7118 const char *errors,
7119 Py_ssize_t *consumed)
7120{
7121 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7122}
7123
7124PyObject *
7125PyUnicode_DecodeMBCSStateful(const char *s,
7126 Py_ssize_t size,
7127 const char *errors,
7128 Py_ssize_t *consumed)
7129{
7130 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7131}
7132
7133PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007134PyUnicode_DecodeMBCS(const char *s,
7135 Py_ssize_t size,
7136 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007137{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007138 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7139}
7140
Victor Stinner3a50e702011-10-18 21:21:00 +02007141static DWORD
7142encode_code_page_flags(UINT code_page, const char *errors)
7143{
7144 if (code_page == CP_UTF8) {
7145 if (winver.dwMajorVersion >= 6)
7146 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7147 and later */
7148 return WC_ERR_INVALID_CHARS;
7149 else
7150 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7151 return 0;
7152 }
7153 else if (code_page == CP_UTF7) {
7154 /* CP_UTF7 only supports flags=0 */
7155 return 0;
7156 }
7157 else {
7158 if (errors != NULL && strcmp(errors, "replace") == 0)
7159 return 0;
7160 else
7161 return WC_NO_BEST_FIT_CHARS;
7162 }
7163}
7164
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007165/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 * Encode a Unicode string to a Windows code page into a byte string in strict
7167 * mode.
7168 *
7169 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007170 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007171 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007172static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007173encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007174 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007176{
Victor Stinner554f3f02010-06-16 23:33:54 +00007177 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 BOOL *pusedDefaultChar = &usedDefaultChar;
7179 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007180 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007181 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007182 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 const DWORD flags = encode_code_page_flags(code_page, NULL);
7184 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007185 /* Create a substring so that we can get the UTF-16 representation
7186 of just the slice under consideration. */
7187 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007188
Martin v. Löwis3d325192011-11-04 18:23:06 +01007189 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007190
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007192 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007194 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007195
Victor Stinner2fc507f2011-11-04 20:06:39 +01007196 substring = PyUnicode_Substring(unicode, offset, offset+len);
7197 if (substring == NULL)
7198 return -1;
7199 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7200 if (p == NULL) {
7201 Py_DECREF(substring);
7202 return -1;
7203 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007204 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007205
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007206 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007208 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 NULL, 0,
7210 NULL, pusedDefaultChar);
7211 if (outsize <= 0)
7212 goto error;
7213 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 if (pusedDefaultChar && *pusedDefaultChar) {
7215 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007218
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007220 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 if (*outbytes == NULL) {
7223 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007224 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007225 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007226 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007227 }
7228 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007229 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 const Py_ssize_t n = PyBytes_Size(*outbytes);
7231 if (outsize > PY_SSIZE_T_MAX - n) {
7232 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007233 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007234 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7237 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007239 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007241 }
7242
7243 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007245 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 out, outsize,
7247 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 if (outsize <= 0)
7250 goto error;
7251 if (pusedDefaultChar && *pusedDefaultChar)
7252 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007253 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007254
Victor Stinner3a50e702011-10-18 21:21:00 +02007255error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007256 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007257 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7258 return -2;
7259 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007260 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007261}
7262
Victor Stinner3a50e702011-10-18 21:21:00 +02007263/*
7264 * Encode a Unicode string to a Windows code page into a byte string using a
7265 * error handler.
7266 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007267 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007268 * -1 on other error.
7269 */
7270static int
7271encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007272 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007273 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007274{
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007276 Py_ssize_t pos = unicode_offset;
7277 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 /* Ideally, we should get reason from FormatMessage. This is the Windows
7279 2000 English version of the message. */
7280 const char *reason = "invalid character";
7281 /* 4=maximum length of a UTF-8 sequence */
7282 char buffer[4];
7283 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7284 Py_ssize_t outsize;
7285 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 PyObject *errorHandler = NULL;
7287 PyObject *exc = NULL;
7288 PyObject *encoding_obj = NULL;
7289 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007290 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 PyObject *rep;
7292 int ret = -1;
7293
7294 assert(insize > 0);
7295
7296 encoding = code_page_name(code_page, &encoding_obj);
7297 if (encoding == NULL)
7298 return -1;
7299
7300 if (errors == NULL || strcmp(errors, "strict") == 0) {
7301 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7302 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007303 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 if (exc != NULL) {
7305 PyCodec_StrictErrors(exc);
7306 Py_DECREF(exc);
7307 }
7308 Py_XDECREF(encoding_obj);
7309 return -1;
7310 }
7311
7312 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7313 pusedDefaultChar = &usedDefaultChar;
7314 else
7315 pusedDefaultChar = NULL;
7316
7317 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7318 PyErr_NoMemory();
7319 goto error;
7320 }
7321 outsize = insize * Py_ARRAY_LENGTH(buffer);
7322
7323 if (*outbytes == NULL) {
7324 /* Create string object */
7325 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7326 if (*outbytes == NULL)
7327 goto error;
7328 out = PyBytes_AS_STRING(*outbytes);
7329 }
7330 else {
7331 /* Extend string object */
7332 Py_ssize_t n = PyBytes_Size(*outbytes);
7333 if (n > PY_SSIZE_T_MAX - outsize) {
7334 PyErr_NoMemory();
7335 goto error;
7336 }
7337 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7338 goto error;
7339 out = PyBytes_AS_STRING(*outbytes) + n;
7340 }
7341
7342 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007345 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7346 wchar_t chars[2];
7347 int charsize;
7348 if (ch < 0x10000) {
7349 chars[0] = (wchar_t)ch;
7350 charsize = 1;
7351 }
7352 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007353 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7354 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007355 charsize = 2;
7356 }
7357
Victor Stinner3a50e702011-10-18 21:21:00 +02007358 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007360 buffer, Py_ARRAY_LENGTH(buffer),
7361 NULL, pusedDefaultChar);
7362 if (outsize > 0) {
7363 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7364 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007365 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007366 memcpy(out, buffer, outsize);
7367 out += outsize;
7368 continue;
7369 }
7370 }
7371 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7372 PyErr_SetFromWindowsErr(0);
7373 goto error;
7374 }
7375
Victor Stinner3a50e702011-10-18 21:21:00 +02007376 rep = unicode_encode_call_errorhandler(
7377 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007378 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007379 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 if (rep == NULL)
7381 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007382 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007383
7384 if (PyBytes_Check(rep)) {
7385 outsize = PyBytes_GET_SIZE(rep);
7386 if (outsize != 1) {
7387 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7388 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7389 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7390 Py_DECREF(rep);
7391 goto error;
7392 }
7393 out = PyBytes_AS_STRING(*outbytes) + offset;
7394 }
7395 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7396 out += outsize;
7397 }
7398 else {
7399 Py_ssize_t i;
7400 enum PyUnicode_Kind kind;
7401 void *data;
7402
Benjamin Petersonbac79492012-01-14 13:34:47 -05007403 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007404 Py_DECREF(rep);
7405 goto error;
7406 }
7407
7408 outsize = PyUnicode_GET_LENGTH(rep);
7409 if (outsize != 1) {
7410 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7411 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7412 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7413 Py_DECREF(rep);
7414 goto error;
7415 }
7416 out = PyBytes_AS_STRING(*outbytes) + offset;
7417 }
7418 kind = PyUnicode_KIND(rep);
7419 data = PyUnicode_DATA(rep);
7420 for (i=0; i < outsize; i++) {
7421 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7422 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007423 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007424 encoding, unicode,
7425 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 "unable to encode error handler result to ASCII");
7427 Py_DECREF(rep);
7428 goto error;
7429 }
7430 *out = (unsigned char)ch;
7431 out++;
7432 }
7433 }
7434 Py_DECREF(rep);
7435 }
7436 /* write a NUL byte */
7437 *out = 0;
7438 outsize = out - PyBytes_AS_STRING(*outbytes);
7439 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7440 if (_PyBytes_Resize(outbytes, outsize) < 0)
7441 goto error;
7442 ret = 0;
7443
7444error:
7445 Py_XDECREF(encoding_obj);
7446 Py_XDECREF(errorHandler);
7447 Py_XDECREF(exc);
7448 return ret;
7449}
7450
Victor Stinner3a50e702011-10-18 21:21:00 +02007451static PyObject *
7452encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007453 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 const char *errors)
7455{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007456 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007458 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007459 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007460
Benjamin Petersonbac79492012-01-14 13:34:47 -05007461 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007462 return NULL;
7463 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007464
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 if (code_page < 0) {
7466 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7467 return NULL;
7468 }
7469
Martin v. Löwis3d325192011-11-04 18:23:06 +01007470 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007471 return PyBytes_FromStringAndSize(NULL, 0);
7472
Victor Stinner7581cef2011-11-03 22:32:33 +01007473 offset = 0;
7474 do
7475 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007476#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007477 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007478 chunks. */
7479 if (len > INT_MAX/2) {
7480 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007481 done = 0;
7482 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007483 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007484#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007485 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007486 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007487 done = 1;
7488 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007489
Victor Stinner76a31a62011-11-04 00:05:13 +01007490 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007491 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007492 errors);
7493 if (ret == -2)
7494 ret = encode_code_page_errors(code_page, &outbytes,
7495 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007496 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007497 if (ret < 0) {
7498 Py_XDECREF(outbytes);
7499 return NULL;
7500 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007501
Victor Stinner7581cef2011-11-03 22:32:33 +01007502 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007503 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007504 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007505
Victor Stinner3a50e702011-10-18 21:21:00 +02007506 return outbytes;
7507}
7508
7509PyObject *
7510PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7511 Py_ssize_t size,
7512 const char *errors)
7513{
Victor Stinner7581cef2011-11-03 22:32:33 +01007514 PyObject *unicode, *res;
7515 unicode = PyUnicode_FromUnicode(p, size);
7516 if (unicode == NULL)
7517 return NULL;
7518 res = encode_code_page(CP_ACP, unicode, errors);
7519 Py_DECREF(unicode);
7520 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007521}
7522
7523PyObject *
7524PyUnicode_EncodeCodePage(int code_page,
7525 PyObject *unicode,
7526 const char *errors)
7527{
Victor Stinner7581cef2011-11-03 22:32:33 +01007528 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007529}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007530
Alexander Belopolsky40018472011-02-26 01:02:56 +00007531PyObject *
7532PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007533{
7534 if (!PyUnicode_Check(unicode)) {
7535 PyErr_BadArgument();
7536 return NULL;
7537 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007538 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007539}
7540
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007541#undef NEED_RETRY
7542
Victor Stinner99b95382011-07-04 14:23:54 +02007543#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007544
Guido van Rossumd57fd912000-03-10 22:53:23 +00007545/* --- Character Mapping Codec -------------------------------------------- */
7546
Victor Stinnerfb161b12013-04-18 01:44:27 +02007547static int
7548charmap_decode_string(const char *s,
7549 Py_ssize_t size,
7550 PyObject *mapping,
7551 const char *errors,
7552 _PyUnicodeWriter *writer)
7553{
7554 const char *starts = s;
7555 const char *e;
7556 Py_ssize_t startinpos, endinpos;
7557 PyObject *errorHandler = NULL, *exc = NULL;
7558 Py_ssize_t maplen;
7559 enum PyUnicode_Kind mapkind;
7560 void *mapdata;
7561 Py_UCS4 x;
7562 unsigned char ch;
7563
7564 if (PyUnicode_READY(mapping) == -1)
7565 return -1;
7566
7567 maplen = PyUnicode_GET_LENGTH(mapping);
7568 mapdata = PyUnicode_DATA(mapping);
7569 mapkind = PyUnicode_KIND(mapping);
7570
7571 e = s + size;
7572
7573 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7574 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7575 * is disabled in encoding aliases, latin1 is preferred because
7576 * its implementation is faster. */
7577 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7578 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7579 Py_UCS4 maxchar = writer->maxchar;
7580
7581 assert (writer->kind == PyUnicode_1BYTE_KIND);
7582 while (s < e) {
7583 ch = *s;
7584 x = mapdata_ucs1[ch];
7585 if (x > maxchar) {
7586 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7587 goto onError;
7588 maxchar = writer->maxchar;
7589 outdata = (Py_UCS1 *)writer->data;
7590 }
7591 outdata[writer->pos] = x;
7592 writer->pos++;
7593 ++s;
7594 }
7595 return 0;
7596 }
7597
7598 while (s < e) {
7599 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7600 enum PyUnicode_Kind outkind = writer->kind;
7601 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7602 if (outkind == PyUnicode_1BYTE_KIND) {
7603 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7604 Py_UCS4 maxchar = writer->maxchar;
7605 while (s < e) {
7606 ch = *s;
7607 x = mapdata_ucs2[ch];
7608 if (x > maxchar)
7609 goto Error;
7610 outdata[writer->pos] = x;
7611 writer->pos++;
7612 ++s;
7613 }
7614 break;
7615 }
7616 else if (outkind == PyUnicode_2BYTE_KIND) {
7617 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7618 while (s < e) {
7619 ch = *s;
7620 x = mapdata_ucs2[ch];
7621 if (x == 0xFFFE)
7622 goto Error;
7623 outdata[writer->pos] = x;
7624 writer->pos++;
7625 ++s;
7626 }
7627 break;
7628 }
7629 }
7630 ch = *s;
7631
7632 if (ch < maplen)
7633 x = PyUnicode_READ(mapkind, mapdata, ch);
7634 else
7635 x = 0xfffe; /* invalid value */
7636Error:
7637 if (x == 0xfffe)
7638 {
7639 /* undefined mapping */
7640 startinpos = s-starts;
7641 endinpos = startinpos+1;
7642 if (unicode_decode_call_errorhandler_writer(
7643 errors, &errorHandler,
7644 "charmap", "character maps to <undefined>",
7645 &starts, &e, &startinpos, &endinpos, &exc, &s,
7646 writer)) {
7647 goto onError;
7648 }
7649 continue;
7650 }
7651
7652 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7653 goto onError;
7654 ++s;
7655 }
7656 Py_XDECREF(errorHandler);
7657 Py_XDECREF(exc);
7658 return 0;
7659
7660onError:
7661 Py_XDECREF(errorHandler);
7662 Py_XDECREF(exc);
7663 return -1;
7664}
7665
7666static int
7667charmap_decode_mapping(const char *s,
7668 Py_ssize_t size,
7669 PyObject *mapping,
7670 const char *errors,
7671 _PyUnicodeWriter *writer)
7672{
7673 const char *starts = s;
7674 const char *e;
7675 Py_ssize_t startinpos, endinpos;
7676 PyObject *errorHandler = NULL, *exc = NULL;
7677 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007678 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007679
7680 e = s + size;
7681
7682 while (s < e) {
7683 ch = *s;
7684
7685 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7686 key = PyLong_FromLong((long)ch);
7687 if (key == NULL)
7688 goto onError;
7689
7690 item = PyObject_GetItem(mapping, key);
7691 Py_DECREF(key);
7692 if (item == NULL) {
7693 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7694 /* No mapping found means: mapping is undefined. */
7695 PyErr_Clear();
7696 goto Undefined;
7697 } else
7698 goto onError;
7699 }
7700
7701 /* Apply mapping */
7702 if (item == Py_None)
7703 goto Undefined;
7704 if (PyLong_Check(item)) {
7705 long value = PyLong_AS_LONG(item);
7706 if (value == 0xFFFE)
7707 goto Undefined;
7708 if (value < 0 || value > MAX_UNICODE) {
7709 PyErr_Format(PyExc_TypeError,
7710 "character mapping must be in range(0x%lx)",
7711 (unsigned long)MAX_UNICODE + 1);
7712 goto onError;
7713 }
7714
7715 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7716 goto onError;
7717 }
7718 else if (PyUnicode_Check(item)) {
7719 if (PyUnicode_READY(item) == -1)
7720 goto onError;
7721 if (PyUnicode_GET_LENGTH(item) == 1) {
7722 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7723 if (value == 0xFFFE)
7724 goto Undefined;
7725 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7726 goto onError;
7727 }
7728 else {
7729 writer->overallocate = 1;
7730 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7731 goto onError;
7732 }
7733 }
7734 else {
7735 /* wrong return value */
7736 PyErr_SetString(PyExc_TypeError,
7737 "character mapping must return integer, None or str");
7738 goto onError;
7739 }
7740 Py_CLEAR(item);
7741 ++s;
7742 continue;
7743
7744Undefined:
7745 /* undefined mapping */
7746 Py_CLEAR(item);
7747 startinpos = s-starts;
7748 endinpos = startinpos+1;
7749 if (unicode_decode_call_errorhandler_writer(
7750 errors, &errorHandler,
7751 "charmap", "character maps to <undefined>",
7752 &starts, &e, &startinpos, &endinpos, &exc, &s,
7753 writer)) {
7754 goto onError;
7755 }
7756 }
7757 Py_XDECREF(errorHandler);
7758 Py_XDECREF(exc);
7759 return 0;
7760
7761onError:
7762 Py_XDECREF(item);
7763 Py_XDECREF(errorHandler);
7764 Py_XDECREF(exc);
7765 return -1;
7766}
7767
Alexander Belopolsky40018472011-02-26 01:02:56 +00007768PyObject *
7769PyUnicode_DecodeCharmap(const char *s,
7770 Py_ssize_t size,
7771 PyObject *mapping,
7772 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007773{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007774 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007775
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776 /* Default to Latin-1 */
7777 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007779
Guido van Rossumd57fd912000-03-10 22:53:23 +00007780 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007781 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007782 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007783 writer.min_length = size;
7784 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007785 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007786
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007787 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007788 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7789 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007790 }
7791 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007792 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7793 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007795 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007796
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007798 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007799 return NULL;
7800}
7801
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007802/* Charmap encoding: the lookup table */
7803
Alexander Belopolsky40018472011-02-26 01:02:56 +00007804struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007805 PyObject_HEAD
7806 unsigned char level1[32];
7807 int count2, count3;
7808 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007809};
7810
7811static PyObject*
7812encoding_map_size(PyObject *obj, PyObject* args)
7813{
7814 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007815 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007817}
7818
7819static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007820 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007821 PyDoc_STR("Return the size (in bytes) of this object") },
7822 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007823};
7824
7825static void
7826encoding_map_dealloc(PyObject* o)
7827{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007828 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829}
7830
7831static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007832 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 "EncodingMap", /*tp_name*/
7834 sizeof(struct encoding_map), /*tp_basicsize*/
7835 0, /*tp_itemsize*/
7836 /* methods */
7837 encoding_map_dealloc, /*tp_dealloc*/
7838 0, /*tp_print*/
7839 0, /*tp_getattr*/
7840 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007841 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007842 0, /*tp_repr*/
7843 0, /*tp_as_number*/
7844 0, /*tp_as_sequence*/
7845 0, /*tp_as_mapping*/
7846 0, /*tp_hash*/
7847 0, /*tp_call*/
7848 0, /*tp_str*/
7849 0, /*tp_getattro*/
7850 0, /*tp_setattro*/
7851 0, /*tp_as_buffer*/
7852 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7853 0, /*tp_doc*/
7854 0, /*tp_traverse*/
7855 0, /*tp_clear*/
7856 0, /*tp_richcompare*/
7857 0, /*tp_weaklistoffset*/
7858 0, /*tp_iter*/
7859 0, /*tp_iternext*/
7860 encoding_map_methods, /*tp_methods*/
7861 0, /*tp_members*/
7862 0, /*tp_getset*/
7863 0, /*tp_base*/
7864 0, /*tp_dict*/
7865 0, /*tp_descr_get*/
7866 0, /*tp_descr_set*/
7867 0, /*tp_dictoffset*/
7868 0, /*tp_init*/
7869 0, /*tp_alloc*/
7870 0, /*tp_new*/
7871 0, /*tp_free*/
7872 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873};
7874
7875PyObject*
7876PyUnicode_BuildEncodingMap(PyObject* string)
7877{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007878 PyObject *result;
7879 struct encoding_map *mresult;
7880 int i;
7881 int need_dict = 0;
7882 unsigned char level1[32];
7883 unsigned char level2[512];
7884 unsigned char *mlevel1, *mlevel2, *mlevel3;
7885 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 int kind;
7887 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007888 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007889 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007890
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007891 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 PyErr_BadArgument();
7893 return NULL;
7894 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007895 kind = PyUnicode_KIND(string);
7896 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007897 length = PyUnicode_GET_LENGTH(string);
7898 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899 memset(level1, 0xFF, sizeof level1);
7900 memset(level2, 0xFF, sizeof level2);
7901
7902 /* If there isn't a one-to-one mapping of NULL to \0,
7903 or if there are non-BMP characters, we need to use
7904 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007905 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007906 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007907 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007908 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007909 ch = PyUnicode_READ(kind, data, i);
7910 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007911 need_dict = 1;
7912 break;
7913 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007914 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007915 /* unmapped character */
7916 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007917 l1 = ch >> 11;
7918 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007919 if (level1[l1] == 0xFF)
7920 level1[l1] = count2++;
7921 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007922 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007923 }
7924
7925 if (count2 >= 0xFF || count3 >= 0xFF)
7926 need_dict = 1;
7927
7928 if (need_dict) {
7929 PyObject *result = PyDict_New();
7930 PyObject *key, *value;
7931 if (!result)
7932 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007933 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007934 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007935 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007936 if (!key || !value)
7937 goto failed1;
7938 if (PyDict_SetItem(result, key, value) == -1)
7939 goto failed1;
7940 Py_DECREF(key);
7941 Py_DECREF(value);
7942 }
7943 return result;
7944 failed1:
7945 Py_XDECREF(key);
7946 Py_XDECREF(value);
7947 Py_DECREF(result);
7948 return NULL;
7949 }
7950
7951 /* Create a three-level trie */
7952 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7953 16*count2 + 128*count3 - 1);
7954 if (!result)
7955 return PyErr_NoMemory();
7956 PyObject_Init(result, &EncodingMapType);
7957 mresult = (struct encoding_map*)result;
7958 mresult->count2 = count2;
7959 mresult->count3 = count3;
7960 mlevel1 = mresult->level1;
7961 mlevel2 = mresult->level23;
7962 mlevel3 = mresult->level23 + 16*count2;
7963 memcpy(mlevel1, level1, 32);
7964 memset(mlevel2, 0xFF, 16*count2);
7965 memset(mlevel3, 0, 128*count3);
7966 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007967 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007968 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007969 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7970 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007971 /* unmapped character */
7972 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007973 o1 = ch>>11;
7974 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007975 i2 = 16*mlevel1[o1] + o2;
7976 if (mlevel2[i2] == 0xFF)
7977 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007978 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007979 i3 = 128*mlevel2[i2] + o3;
7980 mlevel3[i3] = i;
7981 }
7982 return result;
7983}
7984
7985static int
Victor Stinner22168992011-11-20 17:09:18 +01007986encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007987{
7988 struct encoding_map *map = (struct encoding_map*)mapping;
7989 int l1 = c>>11;
7990 int l2 = (c>>7) & 0xF;
7991 int l3 = c & 0x7F;
7992 int i;
7993
Victor Stinner22168992011-11-20 17:09:18 +01007994 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007996 if (c == 0)
7997 return 0;
7998 /* level 1*/
7999 i = map->level1[l1];
8000 if (i == 0xFF) {
8001 return -1;
8002 }
8003 /* level 2*/
8004 i = map->level23[16*i+l2];
8005 if (i == 0xFF) {
8006 return -1;
8007 }
8008 /* level 3 */
8009 i = map->level23[16*map->count2 + 128*i + l3];
8010 if (i == 0) {
8011 return -1;
8012 }
8013 return i;
8014}
8015
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008016/* Lookup the character ch in the mapping. If the character
8017 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008018 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008019static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008020charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008021{
Christian Heimes217cfd12007-12-02 14:31:20 +00008022 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008023 PyObject *x;
8024
8025 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008027 x = PyObject_GetItem(mapping, w);
8028 Py_DECREF(w);
8029 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008030 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8031 /* No mapping found means: mapping is undefined. */
8032 PyErr_Clear();
8033 x = Py_None;
8034 Py_INCREF(x);
8035 return x;
8036 } else
8037 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008038 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008039 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008041 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 long value = PyLong_AS_LONG(x);
8043 if (value < 0 || value > 255) {
8044 PyErr_SetString(PyExc_TypeError,
8045 "character mapping must be in range(256)");
8046 Py_DECREF(x);
8047 return NULL;
8048 }
8049 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008050 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008051 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008053 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 /* wrong return value */
8055 PyErr_Format(PyExc_TypeError,
8056 "character mapping must return integer, bytes or None, not %.400s",
8057 x->ob_type->tp_name);
8058 Py_DECREF(x);
8059 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008060 }
8061}
8062
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008064charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008066 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8067 /* exponentially overallocate to minimize reallocations */
8068 if (requiredsize < 2*outsize)
8069 requiredsize = 2*outsize;
8070 if (_PyBytes_Resize(outobj, requiredsize))
8071 return -1;
8072 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073}
8074
Benjamin Peterson14339b62009-01-31 16:36:08 +00008075typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008077} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008079 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008080 space is available. Return a new reference to the object that
8081 was put in the output buffer, or Py_None, if the mapping was undefined
8082 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008083 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008084static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008085charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008086 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008087{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 PyObject *rep;
8089 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008090 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008091
Christian Heimes90aa7642007-12-19 02:45:37 +00008092 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095 if (res == -1)
8096 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008097 if (outsize<requiredsize)
8098 if (charmapencode_resize(outobj, outpos, requiredsize))
8099 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008100 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 outstart[(*outpos)++] = (char)res;
8102 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008103 }
8104
8105 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008106 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 Py_DECREF(rep);
8110 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 if (PyLong_Check(rep)) {
8113 Py_ssize_t requiredsize = *outpos+1;
8114 if (outsize<requiredsize)
8115 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8116 Py_DECREF(rep);
8117 return enc_EXCEPTION;
8118 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008119 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 else {
8123 const char *repchars = PyBytes_AS_STRING(rep);
8124 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8125 Py_ssize_t requiredsize = *outpos+repsize;
8126 if (outsize<requiredsize)
8127 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8128 Py_DECREF(rep);
8129 return enc_EXCEPTION;
8130 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008131 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 memcpy(outstart + *outpos, repchars, repsize);
8133 *outpos += repsize;
8134 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 Py_DECREF(rep);
8137 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138}
8139
8140/* handle an error in PyUnicode_EncodeCharmap
8141 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008142static int
8143charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008144 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008145 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008146 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008147 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008148{
8149 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008150 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008151 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008152 enum PyUnicode_Kind kind;
8153 void *data;
8154 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008155 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008156 Py_ssize_t collstartpos = *inpos;
8157 Py_ssize_t collendpos = *inpos+1;
8158 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008159 char *encoding = "charmap";
8160 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008161 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008162 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008163 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008164
Benjamin Petersonbac79492012-01-14 13:34:47 -05008165 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008166 return -1;
8167 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008168 /* find all unencodable characters */
8169 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008170 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008171 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008172 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008173 val = encoding_map_lookup(ch, mapping);
8174 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 break;
8176 ++collendpos;
8177 continue;
8178 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008179
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008180 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8181 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 if (rep==NULL)
8183 return -1;
8184 else if (rep!=Py_None) {
8185 Py_DECREF(rep);
8186 break;
8187 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008188 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008189 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190 }
8191 /* cache callback name lookup
8192 * (if not done yet, i.e. it's the first error) */
8193 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008194 if ((errors==NULL) || (!strcmp(errors, "strict")))
8195 *known_errorHandler = 1;
8196 else if (!strcmp(errors, "replace"))
8197 *known_errorHandler = 2;
8198 else if (!strcmp(errors, "ignore"))
8199 *known_errorHandler = 3;
8200 else if (!strcmp(errors, "xmlcharrefreplace"))
8201 *known_errorHandler = 4;
8202 else
8203 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204 }
8205 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008207 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008208 return -1;
8209 case 2: /* replace */
8210 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 x = charmapencode_output('?', mapping, res, respos);
8212 if (x==enc_EXCEPTION) {
8213 return -1;
8214 }
8215 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008216 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008217 return -1;
8218 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008219 }
8220 /* fall through */
8221 case 3: /* ignore */
8222 *inpos = collendpos;
8223 break;
8224 case 4: /* xmlcharrefreplace */
8225 /* generate replacement (temporarily (mis)uses p) */
8226 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008227 char buffer[2+29+1+1];
8228 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008229 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 for (cp = buffer; *cp; ++cp) {
8231 x = charmapencode_output(*cp, mapping, res, respos);
8232 if (x==enc_EXCEPTION)
8233 return -1;
8234 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008235 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008236 return -1;
8237 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 }
8239 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008240 *inpos = collendpos;
8241 break;
8242 default:
8243 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008244 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008246 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008248 if (PyBytes_Check(repunicode)) {
8249 /* Directly copy bytes result to output. */
8250 Py_ssize_t outsize = PyBytes_Size(*res);
8251 Py_ssize_t requiredsize;
8252 repsize = PyBytes_Size(repunicode);
8253 requiredsize = *respos + repsize;
8254 if (requiredsize > outsize)
8255 /* Make room for all additional bytes. */
8256 if (charmapencode_resize(res, respos, requiredsize)) {
8257 Py_DECREF(repunicode);
8258 return -1;
8259 }
8260 memcpy(PyBytes_AsString(*res) + *respos,
8261 PyBytes_AsString(repunicode), repsize);
8262 *respos += repsize;
8263 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008264 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008265 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008266 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008267 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008268 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008269 Py_DECREF(repunicode);
8270 return -1;
8271 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008272 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008273 data = PyUnicode_DATA(repunicode);
8274 kind = PyUnicode_KIND(repunicode);
8275 for (index = 0; index < repsize; index++) {
8276 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8277 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008279 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 return -1;
8281 }
8282 else if (x==enc_FAILED) {
8283 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008284 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 return -1;
8286 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008287 }
8288 *inpos = newpos;
8289 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 }
8291 return 0;
8292}
8293
Alexander Belopolsky40018472011-02-26 01:02:56 +00008294PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008295_PyUnicode_EncodeCharmap(PyObject *unicode,
8296 PyObject *mapping,
8297 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008298{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299 /* output object */
8300 PyObject *res = NULL;
8301 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008302 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008303 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008305 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 PyObject *errorHandler = NULL;
8307 PyObject *exc = NULL;
8308 /* the following variable is used for caching string comparisons
8309 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8310 * 3=ignore, 4=xmlcharrefreplace */
8311 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008312 void *data;
8313 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008314
Benjamin Petersonbac79492012-01-14 13:34:47 -05008315 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008316 return NULL;
8317 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008318 data = PyUnicode_DATA(unicode);
8319 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008320
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321 /* Default to Latin-1 */
8322 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008323 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 /* allocate enough for a simple encoding without
8326 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008327 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 if (res == NULL)
8329 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008330 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008332
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008334 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008336 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 if (x==enc_EXCEPTION) /* error */
8338 goto onError;
8339 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008340 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 &exc,
8342 &known_errorHandler, &errorHandler, errors,
8343 &res, &respos)) {
8344 goto onError;
8345 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008346 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 else
8348 /* done with this character => adjust input position */
8349 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008351
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008353 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008354 if (_PyBytes_Resize(&res, respos) < 0)
8355 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008356
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 Py_XDECREF(exc);
8358 Py_XDECREF(errorHandler);
8359 return res;
8360
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 Py_XDECREF(res);
8363 Py_XDECREF(exc);
8364 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008365 return NULL;
8366}
8367
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368/* Deprecated */
8369PyObject *
8370PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8371 Py_ssize_t size,
8372 PyObject *mapping,
8373 const char *errors)
8374{
8375 PyObject *result;
8376 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8377 if (unicode == NULL)
8378 return NULL;
8379 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8380 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008381 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008382}
8383
Alexander Belopolsky40018472011-02-26 01:02:56 +00008384PyObject *
8385PyUnicode_AsCharmapString(PyObject *unicode,
8386 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387{
8388 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 PyErr_BadArgument();
8390 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008392 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393}
8394
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008395/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008396static void
8397make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008398 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008399 Py_ssize_t startpos, Py_ssize_t endpos,
8400 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008401{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008403 *exceptionObject = _PyUnicodeTranslateError_Create(
8404 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008405 }
8406 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8408 goto onError;
8409 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8410 goto onError;
8411 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8412 goto onError;
8413 return;
8414 onError:
8415 Py_DECREF(*exceptionObject);
8416 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008417 }
8418}
8419
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420/* error handling callback helper:
8421 build arguments, call the callback and check the arguments,
8422 put the result into newpos and return the replacement string, which
8423 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008424static PyObject *
8425unicode_translate_call_errorhandler(const char *errors,
8426 PyObject **errorHandler,
8427 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008429 Py_ssize_t startpos, Py_ssize_t endpos,
8430 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008432 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008434 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008435 PyObject *restuple;
8436 PyObject *resunicode;
8437
8438 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442 }
8443
8444 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448
8449 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008451 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008454 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 Py_DECREF(restuple);
8456 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457 }
8458 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 &resunicode, &i_newpos)) {
8460 Py_DECREF(restuple);
8461 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008463 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008465 else
8466 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8469 Py_DECREF(restuple);
8470 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008471 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472 Py_INCREF(resunicode);
8473 Py_DECREF(restuple);
8474 return resunicode;
8475}
8476
8477/* Lookup the character ch in the mapping and put the result in result,
8478 which must be decrefed by the caller.
8479 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008480static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008481charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482{
Christian Heimes217cfd12007-12-02 14:31:20 +00008483 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 PyObject *x;
8485
8486 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 x = PyObject_GetItem(mapping, w);
8489 Py_DECREF(w);
8490 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8492 /* No mapping found means: use 1:1 mapping. */
8493 PyErr_Clear();
8494 *result = NULL;
8495 return 0;
8496 } else
8497 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 }
8499 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 *result = x;
8501 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008503 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 long value = PyLong_AS_LONG(x);
8505 long max = PyUnicode_GetMax();
8506 if (value < 0 || value > max) {
8507 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008508 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 Py_DECREF(x);
8510 return -1;
8511 }
8512 *result = x;
8513 return 0;
8514 }
8515 else if (PyUnicode_Check(x)) {
8516 *result = x;
8517 return 0;
8518 }
8519 else {
8520 /* wrong return value */
8521 PyErr_SetString(PyExc_TypeError,
8522 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008523 Py_DECREF(x);
8524 return -1;
8525 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526}
8527/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 if not reallocate and adjust various state variables.
8529 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008530static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008535 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008536 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 /* exponentially overallocate to minimize reallocations */
8538 if (requiredsize < 2 * oldsize)
8539 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008540 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8541 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008543 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008545 }
8546 return 0;
8547}
8548/* lookup the character, put the result in the output string and adjust
8549 various state variables. Return a new reference to the object that
8550 was put in the output buffer in *result, or Py_None, if the mapping was
8551 undefined (in which case no character was written).
8552 The called must decref result.
8553 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008554static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008555charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8556 PyObject *mapping, Py_UCS4 **output,
8557 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008558 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008560 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8561 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008565 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 }
8567 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008569 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 }
8573 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574 Py_ssize_t repsize;
8575 if (PyUnicode_READY(*res) == -1)
8576 return -1;
8577 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 if (repsize==1) {
8579 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 }
8582 else if (repsize!=0) {
8583 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584 Py_ssize_t requiredsize = *opos +
8585 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 Py_ssize_t i;
8588 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 for(i = 0; i < repsize; i++)
8591 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 }
8594 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 return 0;
8597}
8598
Alexander Belopolsky40018472011-02-26 01:02:56 +00008599PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600_PyUnicode_TranslateCharmap(PyObject *input,
8601 PyObject *mapping,
8602 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 /* input object */
8605 char *idata;
8606 Py_ssize_t size, i;
8607 int kind;
8608 /* output buffer */
8609 Py_UCS4 *output = NULL;
8610 Py_ssize_t osize;
8611 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 char *reason = "character maps to <undefined>";
8615 PyObject *errorHandler = NULL;
8616 PyObject *exc = NULL;
8617 /* the following variable is used for caching string comparisons
8618 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8619 * 3=ignore, 4=xmlcharrefreplace */
8620 int known_errorHandler = -1;
8621
Guido van Rossumd57fd912000-03-10 22:53:23 +00008622 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 PyErr_BadArgument();
8624 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008627 if (PyUnicode_READY(input) == -1)
8628 return NULL;
8629 idata = (char*)PyUnicode_DATA(input);
8630 kind = PyUnicode_KIND(input);
8631 size = PyUnicode_GET_LENGTH(input);
8632 i = 0;
8633
8634 if (size == 0) {
8635 Py_INCREF(input);
8636 return input;
8637 }
8638
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 /* allocate enough for a simple 1:1 translation without
8640 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 osize = size;
8642 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8643 opos = 0;
8644 if (output == NULL) {
8645 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 /* try to encode it */
8651 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 if (charmaptranslate_output(input, i, mapping,
8653 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 Py_XDECREF(x);
8655 goto onError;
8656 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008657 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 else { /* untranslatable character */
8661 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8662 Py_ssize_t repsize;
8663 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 Py_ssize_t collstart = i;
8667 Py_ssize_t collend = i+1;
8668 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 while (collend < size) {
8672 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 goto onError;
8674 Py_XDECREF(x);
8675 if (x!=Py_None)
8676 break;
8677 ++collend;
8678 }
8679 /* cache callback name lookup
8680 * (if not done yet, i.e. it's the first error) */
8681 if (known_errorHandler==-1) {
8682 if ((errors==NULL) || (!strcmp(errors, "strict")))
8683 known_errorHandler = 1;
8684 else if (!strcmp(errors, "replace"))
8685 known_errorHandler = 2;
8686 else if (!strcmp(errors, "ignore"))
8687 known_errorHandler = 3;
8688 else if (!strcmp(errors, "xmlcharrefreplace"))
8689 known_errorHandler = 4;
8690 else
8691 known_errorHandler = 0;
8692 }
8693 switch (known_errorHandler) {
8694 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008695 make_translate_exception(&exc,
8696 input, collstart, collend, reason);
8697 if (exc != NULL)
8698 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008699 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 case 2: /* replace */
8701 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008702 for (coll = collstart; coll<collend; coll++)
8703 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 /* fall through */
8705 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 break;
8708 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709 /* generate replacement (temporarily (mis)uses i) */
8710 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 char buffer[2+29+1+1];
8712 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008713 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8714 if (charmaptranslate_makespace(&output, &osize,
8715 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 goto onError;
8717 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 break;
8722 default:
8723 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008724 reason, input, &exc,
8725 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008726 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008728 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008729 Py_DECREF(repunicode);
8730 goto onError;
8731 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008733 repsize = PyUnicode_GET_LENGTH(repunicode);
8734 if (charmaptranslate_makespace(&output, &osize,
8735 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 Py_DECREF(repunicode);
8737 goto onError;
8738 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739 for (uni2 = 0; repsize-->0; ++uni2)
8740 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8741 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008743 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008744 }
8745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8747 if (!res)
8748 goto onError;
8749 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750 Py_XDECREF(exc);
8751 Py_XDECREF(errorHandler);
8752 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008753
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008755 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008756 Py_XDECREF(exc);
8757 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008758 return NULL;
8759}
8760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008761/* Deprecated. Use PyUnicode_Translate instead. */
8762PyObject *
8763PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8764 Py_ssize_t size,
8765 PyObject *mapping,
8766 const char *errors)
8767{
Christian Heimes5f520f42012-09-11 14:03:25 +02008768 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8770 if (!unicode)
8771 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008772 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8773 Py_DECREF(unicode);
8774 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775}
8776
Alexander Belopolsky40018472011-02-26 01:02:56 +00008777PyObject *
8778PyUnicode_Translate(PyObject *str,
8779 PyObject *mapping,
8780 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781{
8782 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008783
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 str = PyUnicode_FromObject(str);
8785 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008786 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008788 Py_DECREF(str);
8789 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008790}
Tim Petersced69f82003-09-16 20:30:58 +00008791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008793fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794{
8795 /* No need to call PyUnicode_READY(self) because this function is only
8796 called as a callback from fixup() which does it already. */
8797 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8798 const int kind = PyUnicode_KIND(self);
8799 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008800 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008801 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802 Py_ssize_t i;
8803
8804 for (i = 0; i < len; ++i) {
8805 ch = PyUnicode_READ(kind, data, i);
8806 fixed = 0;
8807 if (ch > 127) {
8808 if (Py_UNICODE_ISSPACE(ch))
8809 fixed = ' ';
8810 else {
8811 const int decimal = Py_UNICODE_TODECIMAL(ch);
8812 if (decimal >= 0)
8813 fixed = '0' + decimal;
8814 }
8815 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008816 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008817 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008818 PyUnicode_WRITE(kind, data, i, fixed);
8819 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008820 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008821 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 }
8824
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008825 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008826}
8827
8828PyObject *
8829_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8830{
8831 if (!PyUnicode_Check(unicode)) {
8832 PyErr_BadInternalCall();
8833 return NULL;
8834 }
8835 if (PyUnicode_READY(unicode) == -1)
8836 return NULL;
8837 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8838 /* If the string is already ASCII, just return the same string */
8839 Py_INCREF(unicode);
8840 return unicode;
8841 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008842 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843}
8844
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008845PyObject *
8846PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8847 Py_ssize_t length)
8848{
Victor Stinnerf0124502011-11-21 23:12:56 +01008849 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008850 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008851 Py_UCS4 maxchar;
8852 enum PyUnicode_Kind kind;
8853 void *data;
8854
Victor Stinner99d7ad02012-02-22 13:37:39 +01008855 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008856 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008857 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008858 if (ch > 127) {
8859 int decimal = Py_UNICODE_TODECIMAL(ch);
8860 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008861 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008862 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008863 }
8864 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008865
8866 /* Copy to a new string */
8867 decimal = PyUnicode_New(length, maxchar);
8868 if (decimal == NULL)
8869 return decimal;
8870 kind = PyUnicode_KIND(decimal);
8871 data = PyUnicode_DATA(decimal);
8872 /* Iterate over code points */
8873 for (i = 0; i < length; i++) {
8874 Py_UNICODE ch = s[i];
8875 if (ch > 127) {
8876 int decimal = Py_UNICODE_TODECIMAL(ch);
8877 if (decimal >= 0)
8878 ch = '0' + decimal;
8879 }
8880 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008882 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008883}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008884/* --- Decimal Encoder ---------------------------------------------------- */
8885
Alexander Belopolsky40018472011-02-26 01:02:56 +00008886int
8887PyUnicode_EncodeDecimal(Py_UNICODE *s,
8888 Py_ssize_t length,
8889 char *output,
8890 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008891{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008892 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008893 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008894 enum PyUnicode_Kind kind;
8895 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008896
8897 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008898 PyErr_BadArgument();
8899 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008900 }
8901
Victor Stinner42bf7752011-11-21 22:52:58 +01008902 unicode = PyUnicode_FromUnicode(s, length);
8903 if (unicode == NULL)
8904 return -1;
8905
Benjamin Petersonbac79492012-01-14 13:34:47 -05008906 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008907 Py_DECREF(unicode);
8908 return -1;
8909 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008910 kind = PyUnicode_KIND(unicode);
8911 data = PyUnicode_DATA(unicode);
8912
Victor Stinnerb84d7232011-11-22 01:50:07 +01008913 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008914 PyObject *exc;
8915 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008917 Py_ssize_t startpos;
8918
8919 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008920
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008922 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008923 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008925 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008926 decimal = Py_UNICODE_TODECIMAL(ch);
8927 if (decimal >= 0) {
8928 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008929 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008930 continue;
8931 }
8932 if (0 < ch && ch < 256) {
8933 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008934 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008935 continue;
8936 }
Victor Stinner6345be92011-11-25 20:09:01 +01008937
Victor Stinner42bf7752011-11-21 22:52:58 +01008938 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008939 exc = NULL;
8940 raise_encode_exception(&exc, "decimal", unicode,
8941 startpos, startpos+1,
8942 "invalid decimal Unicode string");
8943 Py_XDECREF(exc);
8944 Py_DECREF(unicode);
8945 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008946 }
8947 /* 0-terminate the output string */
8948 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008949 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008950 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008951}
8952
Guido van Rossumd57fd912000-03-10 22:53:23 +00008953/* --- Helpers ------------------------------------------------------------ */
8954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008955static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008956any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008957 Py_ssize_t start,
8958 Py_ssize_t end)
8959{
8960 int kind1, kind2, kind;
8961 void *buf1, *buf2;
8962 Py_ssize_t len1, len2, result;
8963
8964 kind1 = PyUnicode_KIND(s1);
8965 kind2 = PyUnicode_KIND(s2);
8966 kind = kind1 > kind2 ? kind1 : kind2;
8967 buf1 = PyUnicode_DATA(s1);
8968 buf2 = PyUnicode_DATA(s2);
8969 if (kind1 != kind)
8970 buf1 = _PyUnicode_AsKind(s1, kind);
8971 if (!buf1)
8972 return -2;
8973 if (kind2 != kind)
8974 buf2 = _PyUnicode_AsKind(s2, kind);
8975 if (!buf2) {
8976 if (kind1 != kind) PyMem_Free(buf1);
8977 return -2;
8978 }
8979 len1 = PyUnicode_GET_LENGTH(s1);
8980 len2 = PyUnicode_GET_LENGTH(s2);
8981
Victor Stinner794d5672011-10-10 03:21:36 +02008982 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008983 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008984 case PyUnicode_1BYTE_KIND:
8985 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8986 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8987 else
8988 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8989 break;
8990 case PyUnicode_2BYTE_KIND:
8991 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8992 break;
8993 case PyUnicode_4BYTE_KIND:
8994 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8995 break;
8996 default:
8997 assert(0); result = -2;
8998 }
8999 }
9000 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009001 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009002 case PyUnicode_1BYTE_KIND:
9003 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9004 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9005 else
9006 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9007 break;
9008 case PyUnicode_2BYTE_KIND:
9009 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9010 break;
9011 case PyUnicode_4BYTE_KIND:
9012 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9013 break;
9014 default:
9015 assert(0); result = -2;
9016 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017 }
9018
9019 if (kind1 != kind)
9020 PyMem_Free(buf1);
9021 if (kind2 != kind)
9022 PyMem_Free(buf2);
9023
9024 return result;
9025}
9026
9027Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009028_PyUnicode_InsertThousandsGrouping(
9029 PyObject *unicode, Py_ssize_t index,
9030 Py_ssize_t n_buffer,
9031 void *digits, Py_ssize_t n_digits,
9032 Py_ssize_t min_width,
9033 const char *grouping, PyObject *thousands_sep,
9034 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035{
Victor Stinner41a863c2012-02-24 00:37:51 +01009036 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009037 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009038 Py_ssize_t thousands_sep_len;
9039 Py_ssize_t len;
9040
9041 if (unicode != NULL) {
9042 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009043 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009044 }
9045 else {
9046 kind = PyUnicode_1BYTE_KIND;
9047 data = NULL;
9048 }
9049 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9050 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9051 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9052 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009053 if (thousands_sep_kind < kind) {
9054 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9055 if (!thousands_sep_data)
9056 return -1;
9057 }
9058 else {
9059 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9060 if (!data)
9061 return -1;
9062 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009063 }
9064
Benjamin Petersonead6b532011-12-20 17:23:42 -06009065 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009067 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009068 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009069 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009070 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009071 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009072 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009073 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009074 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009075 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009076 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009077 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009079 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009080 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009081 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009082 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009083 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009085 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009086 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009087 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009088 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009089 break;
9090 default:
9091 assert(0);
9092 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009094 if (unicode != NULL && thousands_sep_kind != kind) {
9095 if (thousands_sep_kind < kind)
9096 PyMem_Free(thousands_sep_data);
9097 else
9098 PyMem_Free(data);
9099 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009100 if (unicode == NULL) {
9101 *maxchar = 127;
9102 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009103 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009104 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009105 }
9106 }
9107 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108}
9109
9110
Thomas Wouters477c8d52006-05-27 19:21:47 +00009111/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009112#define ADJUST_INDICES(start, end, len) \
9113 if (end > len) \
9114 end = len; \
9115 else if (end < 0) { \
9116 end += len; \
9117 if (end < 0) \
9118 end = 0; \
9119 } \
9120 if (start < 0) { \
9121 start += len; \
9122 if (start < 0) \
9123 start = 0; \
9124 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009125
Alexander Belopolsky40018472011-02-26 01:02:56 +00009126Py_ssize_t
9127PyUnicode_Count(PyObject *str,
9128 PyObject *substr,
9129 Py_ssize_t start,
9130 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009131{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009132 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009133 PyObject* str_obj;
9134 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 int kind1, kind2, kind;
9136 void *buf1 = NULL, *buf2 = NULL;
9137 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009138
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009139 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009140 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009141 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009142 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009143 if (!sub_obj) {
9144 Py_DECREF(str_obj);
9145 return -1;
9146 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009147 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009148 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 Py_DECREF(str_obj);
9150 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151 }
Tim Petersced69f82003-09-16 20:30:58 +00009152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009153 kind1 = PyUnicode_KIND(str_obj);
9154 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009155 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009156 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009157 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009158 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009159 if (kind2 > kind) {
9160 Py_DECREF(sub_obj);
9161 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009162 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009163 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009164 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166 if (!buf2)
9167 goto onError;
9168 len1 = PyUnicode_GET_LENGTH(str_obj);
9169 len2 = PyUnicode_GET_LENGTH(sub_obj);
9170
9171 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009172 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009174 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9175 result = asciilib_count(
9176 ((Py_UCS1*)buf1) + start, end - start,
9177 buf2, len2, PY_SSIZE_T_MAX
9178 );
9179 else
9180 result = ucs1lib_count(
9181 ((Py_UCS1*)buf1) + start, end - start,
9182 buf2, len2, PY_SSIZE_T_MAX
9183 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009184 break;
9185 case PyUnicode_2BYTE_KIND:
9186 result = ucs2lib_count(
9187 ((Py_UCS2*)buf1) + start, end - start,
9188 buf2, len2, PY_SSIZE_T_MAX
9189 );
9190 break;
9191 case PyUnicode_4BYTE_KIND:
9192 result = ucs4lib_count(
9193 ((Py_UCS4*)buf1) + start, end - start,
9194 buf2, len2, PY_SSIZE_T_MAX
9195 );
9196 break;
9197 default:
9198 assert(0); result = 0;
9199 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009200
9201 Py_DECREF(sub_obj);
9202 Py_DECREF(str_obj);
9203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 if (kind2 != kind)
9205 PyMem_Free(buf2);
9206
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 onError:
9209 Py_DECREF(sub_obj);
9210 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 if (kind2 != kind && buf2)
9212 PyMem_Free(buf2);
9213 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214}
9215
Alexander Belopolsky40018472011-02-26 01:02:56 +00009216Py_ssize_t
9217PyUnicode_Find(PyObject *str,
9218 PyObject *sub,
9219 Py_ssize_t start,
9220 Py_ssize_t end,
9221 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009223 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009224
Guido van Rossumd57fd912000-03-10 22:53:23 +00009225 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009226 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009227 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009228 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009229 if (!sub) {
9230 Py_DECREF(str);
9231 return -2;
9232 }
9233 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9234 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009235 Py_DECREF(str);
9236 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237 }
Tim Petersced69f82003-09-16 20:30:58 +00009238
Victor Stinner794d5672011-10-10 03:21:36 +02009239 result = any_find_slice(direction,
9240 str, sub, start, end
9241 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009242
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009244 Py_DECREF(sub);
9245
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246 return result;
9247}
9248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249Py_ssize_t
9250PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9251 Py_ssize_t start, Py_ssize_t end,
9252 int direction)
9253{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009255 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 if (PyUnicode_READY(str) == -1)
9257 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009258 if (start < 0 || end < 0) {
9259 PyErr_SetString(PyExc_IndexError, "string index out of range");
9260 return -2;
9261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009262 if (end > PyUnicode_GET_LENGTH(str))
9263 end = PyUnicode_GET_LENGTH(str);
9264 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009265 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9266 kind, end-start, ch, direction);
9267 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009269 else
9270 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009271}
9272
Alexander Belopolsky40018472011-02-26 01:02:56 +00009273static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009274tailmatch(PyObject *self,
9275 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009276 Py_ssize_t start,
9277 Py_ssize_t end,
9278 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 int kind_self;
9281 int kind_sub;
9282 void *data_self;
9283 void *data_sub;
9284 Py_ssize_t offset;
9285 Py_ssize_t i;
9286 Py_ssize_t end_sub;
9287
9288 if (PyUnicode_READY(self) == -1 ||
9289 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009290 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291
9292 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293 return 1;
9294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9296 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009298 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 kind_self = PyUnicode_KIND(self);
9301 data_self = PyUnicode_DATA(self);
9302 kind_sub = PyUnicode_KIND(substring);
9303 data_sub = PyUnicode_DATA(substring);
9304 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9305
9306 if (direction > 0)
9307 offset = end;
9308 else
9309 offset = start;
9310
9311 if (PyUnicode_READ(kind_self, data_self, offset) ==
9312 PyUnicode_READ(kind_sub, data_sub, 0) &&
9313 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9314 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9315 /* If both are of the same kind, memcmp is sufficient */
9316 if (kind_self == kind_sub) {
9317 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009318 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 data_sub,
9320 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009321 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009322 }
9323 /* otherwise we have to compare each character by first accesing it */
9324 else {
9325 /* We do not need to compare 0 and len(substring)-1 because
9326 the if statement above ensured already that they are equal
9327 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 for (i = 1; i < end_sub; ++i) {
9329 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9330 PyUnicode_READ(kind_sub, data_sub, i))
9331 return 0;
9332 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009333 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 }
9336
9337 return 0;
9338}
9339
Alexander Belopolsky40018472011-02-26 01:02:56 +00009340Py_ssize_t
9341PyUnicode_Tailmatch(PyObject *str,
9342 PyObject *substr,
9343 Py_ssize_t start,
9344 Py_ssize_t end,
9345 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009347 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009348
Guido van Rossumd57fd912000-03-10 22:53:23 +00009349 str = PyUnicode_FromObject(str);
9350 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009351 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352 substr = PyUnicode_FromObject(substr);
9353 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009354 Py_DECREF(str);
9355 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356 }
Tim Petersced69f82003-09-16 20:30:58 +00009357
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009358 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009359 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360 Py_DECREF(str);
9361 Py_DECREF(substr);
9362 return result;
9363}
9364
Guido van Rossumd57fd912000-03-10 22:53:23 +00009365/* Apply fixfct filter to the Unicode object self and return a
9366 reference to the modified object */
9367
Alexander Belopolsky40018472011-02-26 01:02:56 +00009368static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009369fixup(PyObject *self,
9370 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009372 PyObject *u;
9373 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009374 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009376 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009378 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009379 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381 /* fix functions return the new maximum character in a string,
9382 if the kind of the resulting unicode object does not change,
9383 everything is fine. Otherwise we need to change the string kind
9384 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009385 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009386
9387 if (maxchar_new == 0) {
9388 /* no changes */;
9389 if (PyUnicode_CheckExact(self)) {
9390 Py_DECREF(u);
9391 Py_INCREF(self);
9392 return self;
9393 }
9394 else
9395 return u;
9396 }
9397
Victor Stinnere6abb482012-05-02 01:15:40 +02009398 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009399
Victor Stinnereaab6042011-12-11 22:22:39 +01009400 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009401 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009402
9403 /* In case the maximum character changed, we need to
9404 convert the string to the new category. */
9405 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9406 if (v == NULL) {
9407 Py_DECREF(u);
9408 return NULL;
9409 }
9410 if (maxchar_new > maxchar_old) {
9411 /* If the maxchar increased so that the kind changed, not all
9412 characters are representable anymore and we need to fix the
9413 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009414 _PyUnicode_FastCopyCharacters(v, 0,
9415 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009416 maxchar_old = fixfct(v);
9417 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 }
9419 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009420 _PyUnicode_FastCopyCharacters(v, 0,
9421 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009423 Py_DECREF(u);
9424 assert(_PyUnicode_CheckConsistency(v, 1));
9425 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426}
9427
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009428static PyObject *
9429ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009430{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009431 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9432 char *resdata, *data = PyUnicode_DATA(self);
9433 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009434
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009435 res = PyUnicode_New(len, 127);
9436 if (res == NULL)
9437 return NULL;
9438 resdata = PyUnicode_DATA(res);
9439 if (lower)
9440 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009442 _Py_bytes_upper(resdata, data, len);
9443 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009444}
9445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009447handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009449 Py_ssize_t j;
9450 int final_sigma;
9451 Py_UCS4 c;
9452 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009453
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009454 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9455
9456 where ! is a negation and \p{xxx} is a character with property xxx.
9457 */
9458 for (j = i - 1; j >= 0; j--) {
9459 c = PyUnicode_READ(kind, data, j);
9460 if (!_PyUnicode_IsCaseIgnorable(c))
9461 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009463 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9464 if (final_sigma) {
9465 for (j = i + 1; j < length; j++) {
9466 c = PyUnicode_READ(kind, data, j);
9467 if (!_PyUnicode_IsCaseIgnorable(c))
9468 break;
9469 }
9470 final_sigma = j == length || !_PyUnicode_IsCased(c);
9471 }
9472 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473}
9474
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009475static int
9476lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9477 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009479 /* Obscure special case. */
9480 if (c == 0x3A3) {
9481 mapped[0] = handle_capital_sigma(kind, data, length, i);
9482 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009484 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485}
9486
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009487static Py_ssize_t
9488do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009490 Py_ssize_t i, k = 0;
9491 int n_res, j;
9492 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009493
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009494 c = PyUnicode_READ(kind, data, 0);
9495 n_res = _PyUnicode_ToUpperFull(c, mapped);
9496 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009497 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009498 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009500 for (i = 1; i < length; i++) {
9501 c = PyUnicode_READ(kind, data, i);
9502 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9503 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009504 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009505 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009506 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009507 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009508 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509}
9510
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009511static Py_ssize_t
9512do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9513 Py_ssize_t i, k = 0;
9514
9515 for (i = 0; i < length; i++) {
9516 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9517 int n_res, j;
9518 if (Py_UNICODE_ISUPPER(c)) {
9519 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9520 }
9521 else if (Py_UNICODE_ISLOWER(c)) {
9522 n_res = _PyUnicode_ToUpperFull(c, mapped);
9523 }
9524 else {
9525 n_res = 1;
9526 mapped[0] = c;
9527 }
9528 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009529 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009530 res[k++] = mapped[j];
9531 }
9532 }
9533 return k;
9534}
9535
9536static Py_ssize_t
9537do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9538 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009539{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009540 Py_ssize_t i, k = 0;
9541
9542 for (i = 0; i < length; i++) {
9543 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9544 int n_res, j;
9545 if (lower)
9546 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9547 else
9548 n_res = _PyUnicode_ToUpperFull(c, mapped);
9549 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009550 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009551 res[k++] = mapped[j];
9552 }
9553 }
9554 return k;
9555}
9556
9557static Py_ssize_t
9558do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9559{
9560 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9561}
9562
9563static Py_ssize_t
9564do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9565{
9566 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9567}
9568
Benjamin Petersone51757f2012-01-12 21:10:29 -05009569static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009570do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9571{
9572 Py_ssize_t i, k = 0;
9573
9574 for (i = 0; i < length; i++) {
9575 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9576 Py_UCS4 mapped[3];
9577 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9578 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009579 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009580 res[k++] = mapped[j];
9581 }
9582 }
9583 return k;
9584}
9585
9586static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009587do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9588{
9589 Py_ssize_t i, k = 0;
9590 int previous_is_cased;
9591
9592 previous_is_cased = 0;
9593 for (i = 0; i < length; i++) {
9594 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9595 Py_UCS4 mapped[3];
9596 int n_res, j;
9597
9598 if (previous_is_cased)
9599 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9600 else
9601 n_res = _PyUnicode_ToTitleFull(c, mapped);
9602
9603 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009604 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009605 res[k++] = mapped[j];
9606 }
9607
9608 previous_is_cased = _PyUnicode_IsCased(c);
9609 }
9610 return k;
9611}
9612
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009613static PyObject *
9614case_operation(PyObject *self,
9615 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9616{
9617 PyObject *res = NULL;
9618 Py_ssize_t length, newlength = 0;
9619 int kind, outkind;
9620 void *data, *outdata;
9621 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9622
Benjamin Petersoneea48462012-01-16 14:28:50 -05009623 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624
9625 kind = PyUnicode_KIND(self);
9626 data = PyUnicode_DATA(self);
9627 length = PyUnicode_GET_LENGTH(self);
9628 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9629 if (tmp == NULL)
9630 return PyErr_NoMemory();
9631 newlength = perform(kind, data, length, tmp, &maxchar);
9632 res = PyUnicode_New(newlength, maxchar);
9633 if (res == NULL)
9634 goto leave;
9635 tmpend = tmp + newlength;
9636 outdata = PyUnicode_DATA(res);
9637 outkind = PyUnicode_KIND(res);
9638 switch (outkind) {
9639 case PyUnicode_1BYTE_KIND:
9640 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9641 break;
9642 case PyUnicode_2BYTE_KIND:
9643 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9644 break;
9645 case PyUnicode_4BYTE_KIND:
9646 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9647 break;
9648 default:
9649 assert(0);
9650 break;
9651 }
9652 leave:
9653 PyMem_FREE(tmp);
9654 return res;
9655}
9656
Tim Peters8ce9f162004-08-27 01:49:32 +00009657PyObject *
9658PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009661 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009663 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009664 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9665 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009666 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009668 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009669 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009670 int use_memcpy;
9671 unsigned char *res_data = NULL, *sep_data = NULL;
9672 PyObject *last_obj;
9673 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009674
Tim Peters05eba1f2004-08-27 21:32:02 +00009675 fseq = PySequence_Fast(seq, "");
9676 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009677 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009678 }
9679
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009680 /* NOTE: the following code can't call back into Python code,
9681 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009682 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009683
Tim Peters05eba1f2004-08-27 21:32:02 +00009684 seqlen = PySequence_Fast_GET_SIZE(fseq);
9685 /* If empty sequence, return u"". */
9686 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009687 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009688 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009689 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009690
Tim Peters05eba1f2004-08-27 21:32:02 +00009691 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009692 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009693 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009694 if (seqlen == 1) {
9695 if (PyUnicode_CheckExact(items[0])) {
9696 res = items[0];
9697 Py_INCREF(res);
9698 Py_DECREF(fseq);
9699 return res;
9700 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009701 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009702 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009703 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009704 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009705 /* Set up sep and seplen */
9706 if (separator == NULL) {
9707 /* fall back to a blank space separator */
9708 sep = PyUnicode_FromOrdinal(' ');
9709 if (!sep)
9710 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009711 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009712 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009713 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009714 else {
9715 if (!PyUnicode_Check(separator)) {
9716 PyErr_Format(PyExc_TypeError,
9717 "separator: expected str instance,"
9718 " %.80s found",
9719 Py_TYPE(separator)->tp_name);
9720 goto onError;
9721 }
9722 if (PyUnicode_READY(separator))
9723 goto onError;
9724 sep = separator;
9725 seplen = PyUnicode_GET_LENGTH(separator);
9726 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9727 /* inc refcount to keep this code path symmetric with the
9728 above case of a blank separator */
9729 Py_INCREF(sep);
9730 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009731 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009732 }
9733
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009734 /* There are at least two things to join, or else we have a subclass
9735 * of str in the sequence.
9736 * Do a pre-pass to figure out the total amount of space we'll
9737 * need (sz), and see whether all argument are strings.
9738 */
9739 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009740#ifdef Py_DEBUG
9741 use_memcpy = 0;
9742#else
9743 use_memcpy = 1;
9744#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009745 for (i = 0; i < seqlen; i++) {
9746 const Py_ssize_t old_sz = sz;
9747 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009748 if (!PyUnicode_Check(item)) {
9749 PyErr_Format(PyExc_TypeError,
9750 "sequence item %zd: expected str instance,"
9751 " %.80s found",
9752 i, Py_TYPE(item)->tp_name);
9753 goto onError;
9754 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 if (PyUnicode_READY(item) == -1)
9756 goto onError;
9757 sz += PyUnicode_GET_LENGTH(item);
9758 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009759 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009760 if (i != 0)
9761 sz += seplen;
9762 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9763 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009764 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009765 goto onError;
9766 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009767 if (use_memcpy && last_obj != NULL) {
9768 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9769 use_memcpy = 0;
9770 }
9771 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009772 }
Tim Petersced69f82003-09-16 20:30:58 +00009773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009775 if (res == NULL)
9776 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009777
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009778 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009779#ifdef Py_DEBUG
9780 use_memcpy = 0;
9781#else
9782 if (use_memcpy) {
9783 res_data = PyUnicode_1BYTE_DATA(res);
9784 kind = PyUnicode_KIND(res);
9785 if (seplen != 0)
9786 sep_data = PyUnicode_1BYTE_DATA(sep);
9787 }
9788#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009789 if (use_memcpy) {
9790 for (i = 0; i < seqlen; ++i) {
9791 Py_ssize_t itemlen;
9792 item = items[i];
9793
9794 /* Copy item, and maybe the separator. */
9795 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009796 Py_MEMCPY(res_data,
9797 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009798 kind * seplen);
9799 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009800 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009801
9802 itemlen = PyUnicode_GET_LENGTH(item);
9803 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009804 Py_MEMCPY(res_data,
9805 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009806 kind * itemlen);
9807 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009808 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009809 }
9810 assert(res_data == PyUnicode_1BYTE_DATA(res)
9811 + kind * PyUnicode_GET_LENGTH(res));
9812 }
9813 else {
9814 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9815 Py_ssize_t itemlen;
9816 item = items[i];
9817
9818 /* Copy item, and maybe the separator. */
9819 if (i && seplen != 0) {
9820 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9821 res_offset += seplen;
9822 }
9823
9824 itemlen = PyUnicode_GET_LENGTH(item);
9825 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009826 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009827 res_offset += itemlen;
9828 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009829 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009830 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009831 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009832
Tim Peters05eba1f2004-08-27 21:32:02 +00009833 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009834 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009835 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009837
Benjamin Peterson29060642009-01-31 22:14:21 +00009838 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009839 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009840 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009841 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009842 return NULL;
9843}
9844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845#define FILL(kind, data, value, start, length) \
9846 do { \
9847 Py_ssize_t i_ = 0; \
9848 assert(kind != PyUnicode_WCHAR_KIND); \
9849 switch ((kind)) { \
9850 case PyUnicode_1BYTE_KIND: { \
9851 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009852 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 break; \
9854 } \
9855 case PyUnicode_2BYTE_KIND: { \
9856 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9857 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9858 break; \
9859 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009860 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009861 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9862 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9863 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009864 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 } \
9866 } \
9867 } while (0)
9868
Victor Stinnerd3f08822012-05-29 12:57:52 +02009869void
9870_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9871 Py_UCS4 fill_char)
9872{
9873 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9874 const void *data = PyUnicode_DATA(unicode);
9875 assert(PyUnicode_IS_READY(unicode));
9876 assert(unicode_modifiable(unicode));
9877 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9878 assert(start >= 0);
9879 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9880 FILL(kind, data, fill_char, start, length);
9881}
9882
Victor Stinner3fe55312012-01-04 00:33:50 +01009883Py_ssize_t
9884PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9885 Py_UCS4 fill_char)
9886{
9887 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009888
9889 if (!PyUnicode_Check(unicode)) {
9890 PyErr_BadInternalCall();
9891 return -1;
9892 }
9893 if (PyUnicode_READY(unicode) == -1)
9894 return -1;
9895 if (unicode_check_modifiable(unicode))
9896 return -1;
9897
Victor Stinnerd3f08822012-05-29 12:57:52 +02009898 if (start < 0) {
9899 PyErr_SetString(PyExc_IndexError, "string index out of range");
9900 return -1;
9901 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009902 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9903 PyErr_SetString(PyExc_ValueError,
9904 "fill character is bigger than "
9905 "the string maximum character");
9906 return -1;
9907 }
9908
9909 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9910 length = Py_MIN(maxlen, length);
9911 if (length <= 0)
9912 return 0;
9913
Victor Stinnerd3f08822012-05-29 12:57:52 +02009914 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009915 return length;
9916}
9917
Victor Stinner9310abb2011-10-05 00:59:23 +02009918static PyObject *
9919pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009920 Py_ssize_t left,
9921 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009923{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 PyObject *u;
9925 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009926 int kind;
9927 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009928
9929 if (left < 0)
9930 left = 0;
9931 if (right < 0)
9932 right = 0;
9933
Victor Stinnerc4b49542011-12-11 22:44:26 +01009934 if (left == 0 && right == 0)
9935 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9938 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009939 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9940 return NULL;
9941 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009943 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009944 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009945 if (!u)
9946 return NULL;
9947
9948 kind = PyUnicode_KIND(u);
9949 data = PyUnicode_DATA(u);
9950 if (left)
9951 FILL(kind, data, fill, 0, left);
9952 if (right)
9953 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009954 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009955 assert(_PyUnicode_CheckConsistency(u, 1));
9956 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957}
9958
Alexander Belopolsky40018472011-02-26 01:02:56 +00009959PyObject *
9960PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009961{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009962 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009963
9964 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009965 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009966 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009967 if (PyUnicode_READY(string) == -1) {
9968 Py_DECREF(string);
9969 return NULL;
9970 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971
Benjamin Petersonead6b532011-12-20 17:23:42 -06009972 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009974 if (PyUnicode_IS_ASCII(string))
9975 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009976 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977 PyUnicode_GET_LENGTH(string), keepends);
9978 else
9979 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009980 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009981 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 break;
9983 case PyUnicode_2BYTE_KIND:
9984 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009985 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 PyUnicode_GET_LENGTH(string), keepends);
9987 break;
9988 case PyUnicode_4BYTE_KIND:
9989 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009990 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 PyUnicode_GET_LENGTH(string), keepends);
9992 break;
9993 default:
9994 assert(0);
9995 list = 0;
9996 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009997 Py_DECREF(string);
9998 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009999}
10000
Alexander Belopolsky40018472011-02-26 01:02:56 +000010001static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010002split(PyObject *self,
10003 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010004 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010005{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 int kind1, kind2, kind;
10007 void *buf1, *buf2;
10008 Py_ssize_t len1, len2;
10009 PyObject* out;
10010
Guido van Rossumd57fd912000-03-10 22:53:23 +000010011 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010012 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 if (PyUnicode_READY(self) == -1)
10015 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010018 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010020 if (PyUnicode_IS_ASCII(self))
10021 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010022 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010023 PyUnicode_GET_LENGTH(self), maxcount
10024 );
10025 else
10026 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010027 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010028 PyUnicode_GET_LENGTH(self), maxcount
10029 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010030 case PyUnicode_2BYTE_KIND:
10031 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010032 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 PyUnicode_GET_LENGTH(self), maxcount
10034 );
10035 case PyUnicode_4BYTE_KIND:
10036 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010037 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 PyUnicode_GET_LENGTH(self), maxcount
10039 );
10040 default:
10041 assert(0);
10042 return NULL;
10043 }
10044
10045 if (PyUnicode_READY(substring) == -1)
10046 return NULL;
10047
10048 kind1 = PyUnicode_KIND(self);
10049 kind2 = PyUnicode_KIND(substring);
10050 kind = kind1 > kind2 ? kind1 : kind2;
10051 buf1 = PyUnicode_DATA(self);
10052 buf2 = PyUnicode_DATA(substring);
10053 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010054 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 if (!buf1)
10056 return NULL;
10057 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010058 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 if (!buf2) {
10060 if (kind1 != kind) PyMem_Free(buf1);
10061 return NULL;
10062 }
10063 len1 = PyUnicode_GET_LENGTH(self);
10064 len2 = PyUnicode_GET_LENGTH(substring);
10065
Benjamin Petersonead6b532011-12-20 17:23:42 -060010066 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010068 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10069 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010070 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010071 else
10072 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010073 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 break;
10075 case PyUnicode_2BYTE_KIND:
10076 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010077 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 break;
10079 case PyUnicode_4BYTE_KIND:
10080 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010081 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 break;
10083 default:
10084 out = NULL;
10085 }
10086 if (kind1 != kind)
10087 PyMem_Free(buf1);
10088 if (kind2 != kind)
10089 PyMem_Free(buf2);
10090 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091}
10092
Alexander Belopolsky40018472011-02-26 01:02:56 +000010093static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010094rsplit(PyObject *self,
10095 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010096 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010097{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 int kind1, kind2, kind;
10099 void *buf1, *buf2;
10100 Py_ssize_t len1, len2;
10101 PyObject* out;
10102
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010103 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010104 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 if (PyUnicode_READY(self) == -1)
10107 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010110 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010112 if (PyUnicode_IS_ASCII(self))
10113 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010114 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010115 PyUnicode_GET_LENGTH(self), maxcount
10116 );
10117 else
10118 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010119 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010120 PyUnicode_GET_LENGTH(self), maxcount
10121 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 case PyUnicode_2BYTE_KIND:
10123 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010124 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 PyUnicode_GET_LENGTH(self), maxcount
10126 );
10127 case PyUnicode_4BYTE_KIND:
10128 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010129 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 PyUnicode_GET_LENGTH(self), maxcount
10131 );
10132 default:
10133 assert(0);
10134 return NULL;
10135 }
10136
10137 if (PyUnicode_READY(substring) == -1)
10138 return NULL;
10139
10140 kind1 = PyUnicode_KIND(self);
10141 kind2 = PyUnicode_KIND(substring);
10142 kind = kind1 > kind2 ? kind1 : kind2;
10143 buf1 = PyUnicode_DATA(self);
10144 buf2 = PyUnicode_DATA(substring);
10145 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010146 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 if (!buf1)
10148 return NULL;
10149 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010150 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 if (!buf2) {
10152 if (kind1 != kind) PyMem_Free(buf1);
10153 return NULL;
10154 }
10155 len1 = PyUnicode_GET_LENGTH(self);
10156 len2 = PyUnicode_GET_LENGTH(substring);
10157
Benjamin Petersonead6b532011-12-20 17:23:42 -060010158 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010160 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10161 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010162 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010163 else
10164 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010165 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 break;
10167 case PyUnicode_2BYTE_KIND:
10168 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010169 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 break;
10171 case PyUnicode_4BYTE_KIND:
10172 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010173 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 break;
10175 default:
10176 out = NULL;
10177 }
10178 if (kind1 != kind)
10179 PyMem_Free(buf1);
10180 if (kind2 != kind)
10181 PyMem_Free(buf2);
10182 return out;
10183}
10184
10185static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10187 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010189 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10192 return asciilib_find(buf1, len1, buf2, len2, offset);
10193 else
10194 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 case PyUnicode_2BYTE_KIND:
10196 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10197 case PyUnicode_4BYTE_KIND:
10198 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10199 }
10200 assert(0);
10201 return -1;
10202}
10203
10204static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010205anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10206 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010208 switch (kind) {
10209 case PyUnicode_1BYTE_KIND:
10210 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10211 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10212 else
10213 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10214 case PyUnicode_2BYTE_KIND:
10215 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10216 case PyUnicode_4BYTE_KIND:
10217 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10218 }
10219 assert(0);
10220 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010221}
10222
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010223static void
10224replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10225 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10226{
10227 int kind = PyUnicode_KIND(u);
10228 void *data = PyUnicode_DATA(u);
10229 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10230 if (kind == PyUnicode_1BYTE_KIND) {
10231 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10232 (Py_UCS1 *)data + len,
10233 u1, u2, maxcount);
10234 }
10235 else if (kind == PyUnicode_2BYTE_KIND) {
10236 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10237 (Py_UCS2 *)data + len,
10238 u1, u2, maxcount);
10239 }
10240 else {
10241 assert(kind == PyUnicode_4BYTE_KIND);
10242 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10243 (Py_UCS4 *)data + len,
10244 u1, u2, maxcount);
10245 }
10246}
10247
Alexander Belopolsky40018472011-02-26 01:02:56 +000010248static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249replace(PyObject *self, PyObject *str1,
10250 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010251{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 PyObject *u;
10253 char *sbuf = PyUnicode_DATA(self);
10254 char *buf1 = PyUnicode_DATA(str1);
10255 char *buf2 = PyUnicode_DATA(str2);
10256 int srelease = 0, release1 = 0, release2 = 0;
10257 int skind = PyUnicode_KIND(self);
10258 int kind1 = PyUnicode_KIND(str1);
10259 int kind2 = PyUnicode_KIND(str2);
10260 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10261 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10262 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010263 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010264 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010265
10266 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010267 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010269 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010270
Victor Stinner59de0ee2011-10-07 10:01:28 +020010271 if (str1 == str2)
10272 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273
Victor Stinner49a0a212011-10-12 23:46:10 +020010274 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010275 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10276 if (maxchar < maxchar_str1)
10277 /* substring too wide to be present */
10278 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010279 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10280 /* Replacing str1 with str2 may cause a maxchar reduction in the
10281 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010282 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010283 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010284
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010286 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010288 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010290 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010291 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010292 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010293
Victor Stinner69ed0f42013-04-09 21:48:24 +020010294 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010295 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010296 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010297 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010298 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010300 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010302
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010303 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10304 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010305 }
10306 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 int rkind = skind;
10308 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010309 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 if (kind1 < rkind) {
10312 /* widen substring */
10313 buf1 = _PyUnicode_AsKind(str1, rkind);
10314 if (!buf1) goto error;
10315 release1 = 1;
10316 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010317 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010318 if (i < 0)
10319 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 if (rkind > kind2) {
10321 /* widen replacement */
10322 buf2 = _PyUnicode_AsKind(str2, rkind);
10323 if (!buf2) goto error;
10324 release2 = 1;
10325 }
10326 else if (rkind < kind2) {
10327 /* widen self and buf1 */
10328 rkind = kind2;
10329 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010330 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 sbuf = _PyUnicode_AsKind(self, rkind);
10332 if (!sbuf) goto error;
10333 srelease = 1;
10334 buf1 = _PyUnicode_AsKind(str1, rkind);
10335 if (!buf1) goto error;
10336 release1 = 1;
10337 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010338 u = PyUnicode_New(slen, maxchar);
10339 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010341 assert(PyUnicode_KIND(u) == rkind);
10342 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010343
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010344 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010345 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010346 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010348 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010350
10351 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010352 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010353 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010354 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010355 if (i == -1)
10356 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010357 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010359 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010361 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010362 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010363 }
10364 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010366 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 int rkind = skind;
10368 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010371 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 buf1 = _PyUnicode_AsKind(str1, rkind);
10373 if (!buf1) goto error;
10374 release1 = 1;
10375 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010376 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010377 if (n == 0)
10378 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010380 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 buf2 = _PyUnicode_AsKind(str2, rkind);
10382 if (!buf2) goto error;
10383 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010386 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 rkind = kind2;
10388 sbuf = _PyUnicode_AsKind(self, rkind);
10389 if (!sbuf) goto error;
10390 srelease = 1;
10391 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010392 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 buf1 = _PyUnicode_AsKind(str1, rkind);
10394 if (!buf1) goto error;
10395 release1 = 1;
10396 }
10397 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10398 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010399 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 PyErr_SetString(PyExc_OverflowError,
10401 "replace string is too long");
10402 goto error;
10403 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010404 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010405 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010406 _Py_INCREF_UNICODE_EMPTY();
10407 if (!unicode_empty)
10408 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010409 u = unicode_empty;
10410 goto done;
10411 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010412 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 PyErr_SetString(PyExc_OverflowError,
10414 "replace string is too long");
10415 goto error;
10416 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010417 u = PyUnicode_New(new_size, maxchar);
10418 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010420 assert(PyUnicode_KIND(u) == rkind);
10421 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 ires = i = 0;
10423 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010424 while (n-- > 0) {
10425 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010426 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010427 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010428 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010429 if (j == -1)
10430 break;
10431 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010432 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010433 memcpy(res + rkind * ires,
10434 sbuf + rkind * i,
10435 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010437 }
10438 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010440 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010442 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010446 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010448 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010449 memcpy(res + rkind * ires,
10450 sbuf + rkind * i,
10451 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010452 }
10453 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010454 /* interleave */
10455 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010456 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010460 if (--n <= 0)
10461 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010462 memcpy(res + rkind * ires,
10463 sbuf + rkind * i,
10464 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 ires++;
10466 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010467 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010468 memcpy(res + rkind * ires,
10469 sbuf + rkind * i,
10470 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010471 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010472 }
10473
10474 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010475 unicode_adjust_maxchar(&u);
10476 if (u == NULL)
10477 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010478 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010479
10480 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 if (srelease)
10482 PyMem_FREE(sbuf);
10483 if (release1)
10484 PyMem_FREE(buf1);
10485 if (release2)
10486 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010487 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489
Benjamin Peterson29060642009-01-31 22:14:21 +000010490 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010491 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 if (srelease)
10493 PyMem_FREE(sbuf);
10494 if (release1)
10495 PyMem_FREE(buf1);
10496 if (release2)
10497 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010498 return unicode_result_unchanged(self);
10499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 error:
10501 if (srelease && sbuf)
10502 PyMem_FREE(sbuf);
10503 if (release1 && buf1)
10504 PyMem_FREE(buf1);
10505 if (release2 && buf2)
10506 PyMem_FREE(buf2);
10507 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508}
10509
10510/* --- Unicode Object Methods --------------------------------------------- */
10511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010513 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514\n\
10515Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010516characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517
10518static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010519unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010521 if (PyUnicode_READY(self) == -1)
10522 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010523 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524}
10525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010526PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010527 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528\n\
10529Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010530have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531
10532static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010533unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010535 if (PyUnicode_READY(self) == -1)
10536 return NULL;
10537 if (PyUnicode_GET_LENGTH(self) == 0)
10538 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010539 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540}
10541
Benjamin Petersond5890c82012-01-14 13:23:30 -050010542PyDoc_STRVAR(casefold__doc__,
10543 "S.casefold() -> str\n\
10544\n\
10545Return a version of S suitable for caseless comparisons.");
10546
10547static PyObject *
10548unicode_casefold(PyObject *self)
10549{
10550 if (PyUnicode_READY(self) == -1)
10551 return NULL;
10552 if (PyUnicode_IS_ASCII(self))
10553 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010554 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010555}
10556
10557
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010558/* Argument converter. Coerces to a single unicode character */
10559
10560static int
10561convert_uc(PyObject *obj, void *addr)
10562{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010564 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010565
Benjamin Peterson14339b62009-01-31 16:36:08 +000010566 uniobj = PyUnicode_FromObject(obj);
10567 if (uniobj == NULL) {
10568 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010569 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010570 return 0;
10571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010573 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010574 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575 Py_DECREF(uniobj);
10576 return 0;
10577 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010579 Py_DECREF(uniobj);
10580 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010581}
10582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010583PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010584 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010586Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010587done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010588
10589static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010590unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010591{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010592 Py_ssize_t marg, left;
10593 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 Py_UCS4 fillchar = ' ';
10595
Victor Stinnere9a29352011-10-01 02:14:59 +020010596 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598
Benjamin Petersonbac79492012-01-14 13:34:47 -050010599 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 return NULL;
10601
Victor Stinnerc4b49542011-12-11 22:44:26 +010010602 if (PyUnicode_GET_LENGTH(self) >= width)
10603 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604
Victor Stinnerc4b49542011-12-11 22:44:26 +010010605 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606 left = marg / 2 + (marg & width & 1);
10607
Victor Stinner9310abb2011-10-05 00:59:23 +020010608 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609}
10610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611/* This function assumes that str1 and str2 are readied by the caller. */
10612
Marc-André Lemburge5034372000-08-08 08:04:29 +000010613static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010614unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010615{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010616#define COMPARE(TYPE1, TYPE2) \
10617 do { \
10618 TYPE1* p1 = (TYPE1 *)data1; \
10619 TYPE2* p2 = (TYPE2 *)data2; \
10620 TYPE1* end = p1 + len; \
10621 Py_UCS4 c1, c2; \
10622 for (; p1 != end; p1++, p2++) { \
10623 c1 = *p1; \
10624 c2 = *p2; \
10625 if (c1 != c2) \
10626 return (c1 < c2) ? -1 : 1; \
10627 } \
10628 } \
10629 while (0)
10630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 int kind1, kind2;
10632 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010633 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 kind1 = PyUnicode_KIND(str1);
10636 kind2 = PyUnicode_KIND(str2);
10637 data1 = PyUnicode_DATA(str1);
10638 data2 = PyUnicode_DATA(str2);
10639 len1 = PyUnicode_GET_LENGTH(str1);
10640 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010641 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010642
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010643 switch(kind1) {
10644 case PyUnicode_1BYTE_KIND:
10645 {
10646 switch(kind2) {
10647 case PyUnicode_1BYTE_KIND:
10648 {
10649 int cmp = memcmp(data1, data2, len);
10650 /* normalize result of memcmp() into the range [-1; 1] */
10651 if (cmp < 0)
10652 return -1;
10653 if (cmp > 0)
10654 return 1;
10655 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010656 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010657 case PyUnicode_2BYTE_KIND:
10658 COMPARE(Py_UCS1, Py_UCS2);
10659 break;
10660 case PyUnicode_4BYTE_KIND:
10661 COMPARE(Py_UCS1, Py_UCS4);
10662 break;
10663 default:
10664 assert(0);
10665 }
10666 break;
10667 }
10668 case PyUnicode_2BYTE_KIND:
10669 {
10670 switch(kind2) {
10671 case PyUnicode_1BYTE_KIND:
10672 COMPARE(Py_UCS2, Py_UCS1);
10673 break;
10674 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010675 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010676 COMPARE(Py_UCS2, Py_UCS2);
10677 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010678 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010679 case PyUnicode_4BYTE_KIND:
10680 COMPARE(Py_UCS2, Py_UCS4);
10681 break;
10682 default:
10683 assert(0);
10684 }
10685 break;
10686 }
10687 case PyUnicode_4BYTE_KIND:
10688 {
10689 switch(kind2) {
10690 case PyUnicode_1BYTE_KIND:
10691 COMPARE(Py_UCS4, Py_UCS1);
10692 break;
10693 case PyUnicode_2BYTE_KIND:
10694 COMPARE(Py_UCS4, Py_UCS2);
10695 break;
10696 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010697 {
10698#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10699 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10700 /* normalize result of wmemcmp() into the range [-1; 1] */
10701 if (cmp < 0)
10702 return -1;
10703 if (cmp > 0)
10704 return 1;
10705#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010706 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010707#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010708 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010709 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010710 default:
10711 assert(0);
10712 }
10713 break;
10714 }
10715 default:
10716 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010717 }
10718
Victor Stinner770e19e2012-10-04 22:59:45 +020010719 if (len1 == len2)
10720 return 0;
10721 if (len1 < len2)
10722 return -1;
10723 else
10724 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010725
10726#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010727}
10728
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010729Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010730unicode_compare_eq(PyObject *str1, PyObject *str2)
10731{
10732 int kind;
10733 void *data1, *data2;
10734 Py_ssize_t len;
10735 int cmp;
10736
Victor Stinnere5567ad2012-10-23 02:48:49 +020010737 len = PyUnicode_GET_LENGTH(str1);
10738 if (PyUnicode_GET_LENGTH(str2) != len)
10739 return 0;
10740 kind = PyUnicode_KIND(str1);
10741 if (PyUnicode_KIND(str2) != kind)
10742 return 0;
10743 data1 = PyUnicode_DATA(str1);
10744 data2 = PyUnicode_DATA(str2);
10745
10746 cmp = memcmp(data1, data2, len * kind);
10747 return (cmp == 0);
10748}
10749
10750
Alexander Belopolsky40018472011-02-26 01:02:56 +000010751int
10752PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10755 if (PyUnicode_READY(left) == -1 ||
10756 PyUnicode_READY(right) == -1)
10757 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010758
10759 /* a string is equal to itself */
10760 if (left == right)
10761 return 0;
10762
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010763 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010765 PyErr_Format(PyExc_TypeError,
10766 "Can't compare %.100s and %.100s",
10767 left->ob_type->tp_name,
10768 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769 return -1;
10770}
10771
Martin v. Löwis5b222132007-06-10 09:51:05 +000010772int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010773_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10774{
10775 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10776 if (right_str == NULL)
10777 return -1;
10778 return PyUnicode_Compare(left, right_str);
10779}
10780
10781int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010782PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10783{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 Py_ssize_t i;
10785 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 Py_UCS4 chr;
10787
Victor Stinner910337b2011-10-03 03:20:16 +020010788 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (PyUnicode_READY(uni) == -1)
10790 return -1;
10791 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010792 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010793 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010794 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010795 size_t len, len2 = strlen(str);
10796 int cmp;
10797
10798 len = Py_MIN(len1, len2);
10799 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010800 if (cmp != 0) {
10801 if (cmp < 0)
10802 return -1;
10803 else
10804 return 1;
10805 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010806 if (len1 > len2)
10807 return 1; /* uni is longer */
10808 if (len2 > len1)
10809 return -1; /* str is longer */
10810 return 0;
10811 }
10812 else {
10813 void *data = PyUnicode_DATA(uni);
10814 /* Compare Unicode string and source character set string */
10815 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10816 if (chr != str[i])
10817 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10818 /* This check keeps Python strings that end in '\0' from comparing equal
10819 to C strings identical up to that point. */
10820 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10821 return 1; /* uni is longer */
10822 if (str[i])
10823 return -1; /* str is longer */
10824 return 0;
10825 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010826}
10827
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010828
Benjamin Peterson29060642009-01-31 22:14:21 +000010829#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010830 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010831
Alexander Belopolsky40018472011-02-26 01:02:56 +000010832PyObject *
10833PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010834{
10835 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010836 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010837
Victor Stinnere5567ad2012-10-23 02:48:49 +020010838 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10839 Py_RETURN_NOTIMPLEMENTED;
10840
10841 if (PyUnicode_READY(left) == -1 ||
10842 PyUnicode_READY(right) == -1)
10843 return NULL;
10844
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010845 if (left == right) {
10846 switch (op) {
10847 case Py_EQ:
10848 case Py_LE:
10849 case Py_GE:
10850 /* a string is equal to itself */
10851 v = Py_True;
10852 break;
10853 case Py_NE:
10854 case Py_LT:
10855 case Py_GT:
10856 v = Py_False;
10857 break;
10858 default:
10859 PyErr_BadArgument();
10860 return NULL;
10861 }
10862 }
10863 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010864 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010865 result ^= (op == Py_NE);
10866 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010867 }
10868 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010869 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010870
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010871 /* Convert the return value to a Boolean */
10872 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010873 case Py_LE:
10874 v = TEST_COND(result <= 0);
10875 break;
10876 case Py_GE:
10877 v = TEST_COND(result >= 0);
10878 break;
10879 case Py_LT:
10880 v = TEST_COND(result == -1);
10881 break;
10882 case Py_GT:
10883 v = TEST_COND(result == 1);
10884 break;
10885 default:
10886 PyErr_BadArgument();
10887 return NULL;
10888 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010889 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010890 Py_INCREF(v);
10891 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010892}
10893
Alexander Belopolsky40018472011-02-26 01:02:56 +000010894int
10895PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010896{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010897 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010898 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010899 void *buf1, *buf2;
10900 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010901 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010902
10903 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010904 sub = PyUnicode_FromObject(element);
10905 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010906 PyErr_Format(PyExc_TypeError,
10907 "'in <string>' requires string as left operand, not %s",
10908 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010909 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010910 }
10911
Thomas Wouters477c8d52006-05-27 19:21:47 +000010912 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010913 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010914 Py_DECREF(sub);
10915 return -1;
10916 }
10917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 kind1 = PyUnicode_KIND(str);
10919 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010920 buf1 = PyUnicode_DATA(str);
10921 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010922 if (kind2 != kind1) {
10923 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010924 Py_DECREF(sub);
10925 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010926 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010927 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010928 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010929 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010930 if (!buf2) {
10931 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010932 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010933 return -1;
10934 }
10935 len1 = PyUnicode_GET_LENGTH(str);
10936 len2 = PyUnicode_GET_LENGTH(sub);
10937
Victor Stinner77282cb2013-04-14 19:22:47 +020010938 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 case PyUnicode_1BYTE_KIND:
10940 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10941 break;
10942 case PyUnicode_2BYTE_KIND:
10943 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10944 break;
10945 case PyUnicode_4BYTE_KIND:
10946 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10947 break;
10948 default:
10949 result = -1;
10950 assert(0);
10951 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010952
10953 Py_DECREF(str);
10954 Py_DECREF(sub);
10955
Victor Stinner77282cb2013-04-14 19:22:47 +020010956 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 PyMem_Free(buf2);
10958
Guido van Rossum403d68b2000-03-13 15:55:09 +000010959 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010960}
10961
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962/* Concat to string or Unicode object giving a new Unicode object. */
10963
Alexander Belopolsky40018472011-02-26 01:02:56 +000010964PyObject *
10965PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010967 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010968 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010969 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
10971 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010972 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010974 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010976 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010977 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978
10979 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010980 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010981 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010984 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010987 }
10988
Victor Stinner488fa492011-12-12 00:01:39 +010010989 u_len = PyUnicode_GET_LENGTH(u);
10990 v_len = PyUnicode_GET_LENGTH(v);
10991 if (u_len > PY_SSIZE_T_MAX - v_len) {
10992 PyErr_SetString(PyExc_OverflowError,
10993 "strings are too large to concat");
10994 goto onError;
10995 }
10996 new_len = u_len + v_len;
10997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010999 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011000 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011003 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011004 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011005 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011006 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11007 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008 Py_DECREF(u);
11009 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011010 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011011 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012
Benjamin Peterson29060642009-01-31 22:14:21 +000011013 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014 Py_XDECREF(u);
11015 Py_XDECREF(v);
11016 return NULL;
11017}
11018
Walter Dörwald1ab83302007-05-18 17:15:44 +000011019void
Victor Stinner23e56682011-10-03 03:54:37 +020011020PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011021{
Victor Stinner23e56682011-10-03 03:54:37 +020011022 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011023 Py_UCS4 maxchar, maxchar2;
11024 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011025
11026 if (p_left == NULL) {
11027 if (!PyErr_Occurred())
11028 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011029 return;
11030 }
Victor Stinner23e56682011-10-03 03:54:37 +020011031 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011032 if (right == NULL || left == NULL
11033 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011034 if (!PyErr_Occurred())
11035 PyErr_BadInternalCall();
11036 goto error;
11037 }
11038
Benjamin Petersonbac79492012-01-14 13:34:47 -050011039 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011040 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011041 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011042 goto error;
11043
Victor Stinner488fa492011-12-12 00:01:39 +010011044 /* Shortcuts */
11045 if (left == unicode_empty) {
11046 Py_DECREF(left);
11047 Py_INCREF(right);
11048 *p_left = right;
11049 return;
11050 }
11051 if (right == unicode_empty)
11052 return;
11053
11054 left_len = PyUnicode_GET_LENGTH(left);
11055 right_len = PyUnicode_GET_LENGTH(right);
11056 if (left_len > PY_SSIZE_T_MAX - right_len) {
11057 PyErr_SetString(PyExc_OverflowError,
11058 "strings are too large to concat");
11059 goto error;
11060 }
11061 new_len = left_len + right_len;
11062
11063 if (unicode_modifiable(left)
11064 && PyUnicode_CheckExact(right)
11065 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011066 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11067 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011068 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011069 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011070 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11071 {
11072 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011073 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011074 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011075
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011076 /* copy 'right' into the newly allocated area of 'left' */
11077 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011078 }
Victor Stinner488fa492011-12-12 00:01:39 +010011079 else {
11080 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11081 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011082 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011083
Victor Stinner488fa492011-12-12 00:01:39 +010011084 /* Concat the two Unicode strings */
11085 res = PyUnicode_New(new_len, maxchar);
11086 if (res == NULL)
11087 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011088 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11089 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011090 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011091 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011092 }
11093 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011094 return;
11095
11096error:
Victor Stinner488fa492011-12-12 00:01:39 +010011097 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011098}
11099
11100void
11101PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11102{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011103 PyUnicode_Append(pleft, right);
11104 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011105}
11106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011107PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011108 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011110Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011111string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011112interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113
11114static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011115unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011117 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011118 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011119 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011121 int kind1, kind2, kind;
11122 void *buf1, *buf2;
11123 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124
Jesus Ceaac451502011-04-20 17:09:23 +020011125 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11126 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011127 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 kind1 = PyUnicode_KIND(self);
11130 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011131 if (kind2 > kind1) {
11132 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011133 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011134 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011135 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 buf1 = PyUnicode_DATA(self);
11137 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011139 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 if (!buf2) {
11141 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 return NULL;
11143 }
11144 len1 = PyUnicode_GET_LENGTH(self);
11145 len2 = PyUnicode_GET_LENGTH(substring);
11146
11147 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011148 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 case PyUnicode_1BYTE_KIND:
11150 iresult = ucs1lib_count(
11151 ((Py_UCS1*)buf1) + start, end - start,
11152 buf2, len2, PY_SSIZE_T_MAX
11153 );
11154 break;
11155 case PyUnicode_2BYTE_KIND:
11156 iresult = ucs2lib_count(
11157 ((Py_UCS2*)buf1) + start, end - start,
11158 buf2, len2, PY_SSIZE_T_MAX
11159 );
11160 break;
11161 case PyUnicode_4BYTE_KIND:
11162 iresult = ucs4lib_count(
11163 ((Py_UCS4*)buf1) + start, end - start,
11164 buf2, len2, PY_SSIZE_T_MAX
11165 );
11166 break;
11167 default:
11168 assert(0); iresult = 0;
11169 }
11170
11171 result = PyLong_FromSsize_t(iresult);
11172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 if (kind2 != kind)
11174 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175
11176 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011177
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178 return result;
11179}
11180
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011181PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011182 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011184Encode S using the codec registered for encoding. Default encoding\n\
11185is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011186handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011187a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11188'xmlcharrefreplace' as well as any other name registered with\n\
11189codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
11191static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011192unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011194 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195 char *encoding = NULL;
11196 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011197
Benjamin Peterson308d6372009-09-18 21:42:35 +000011198 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11199 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011201 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011202}
11203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011204PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011205 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206\n\
11207Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011208If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209
11210static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011211unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011213 Py_ssize_t i, j, line_pos, src_len, incr;
11214 Py_UCS4 ch;
11215 PyObject *u;
11216 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011217 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011219 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011220 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221
Ezio Melotti745d54d2013-11-16 19:10:57 +020011222 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11223 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225
Antoine Pitrou22425222011-10-04 19:10:51 +020011226 if (PyUnicode_READY(self) == -1)
11227 return NULL;
11228
Thomas Wouters7e474022000-07-16 12:04:32 +000011229 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011230 src_len = PyUnicode_GET_LENGTH(self);
11231 i = j = line_pos = 0;
11232 kind = PyUnicode_KIND(self);
11233 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011234 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011235 for (; i < src_len; i++) {
11236 ch = PyUnicode_READ(kind, src_data, i);
11237 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011238 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011239 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011240 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011242 goto overflow;
11243 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011244 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011245 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011246 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011248 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011249 goto overflow;
11250 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011252 if (ch == '\n' || ch == '\r')
11253 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011255 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011256 if (!found)
11257 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011258
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261 if (!u)
11262 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
Antoine Pitroue71d5742011-10-04 15:55:09 +020011265 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266
Antoine Pitroue71d5742011-10-04 15:55:09 +020011267 for (; i < src_len; i++) {
11268 ch = PyUnicode_READ(kind, src_data, i);
11269 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011270 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011271 incr = tabsize - (line_pos % tabsize);
11272 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011273 FILL(kind, dest_data, ' ', j, incr);
11274 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011276 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 line_pos++;
11279 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011280 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011281 if (ch == '\n' || ch == '\r')
11282 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011284 }
11285 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011286 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011287
Antoine Pitroue71d5742011-10-04 15:55:09 +020011288 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011289 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11290 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291}
11292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295\n\
11296Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011297such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298arguments start and end are interpreted as in slice notation.\n\
11299\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011300Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301
11302static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011305 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011306 Py_ssize_t start;
11307 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011308 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309
Jesus Ceaac451502011-04-20 17:09:23 +020011310 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11311 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313
Christian Heimesd47802e2013-06-29 21:33:36 +020011314 if (PyUnicode_READY(self) == -1) {
11315 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011316 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011317 }
11318 if (PyUnicode_READY(substring) == -1) {
11319 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011321 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011322
Victor Stinner7931d9a2011-11-04 00:22:48 +010011323 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
11325 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 if (result == -2)
11328 return NULL;
11329
Christian Heimes217cfd12007-12-02 14:31:20 +000011330 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331}
11332
11333static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011334unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011336 void *data;
11337 enum PyUnicode_Kind kind;
11338 Py_UCS4 ch;
11339 PyObject *res;
11340
11341 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11342 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011344 }
11345 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11346 PyErr_SetString(PyExc_IndexError, "string index out of range");
11347 return NULL;
11348 }
11349 kind = PyUnicode_KIND(self);
11350 data = PyUnicode_DATA(self);
11351 ch = PyUnicode_READ(kind, data, index);
11352 if (ch < 256)
11353 return get_latin1_char(ch);
11354
11355 res = PyUnicode_New(1, ch);
11356 if (res == NULL)
11357 return NULL;
11358 kind = PyUnicode_KIND(res);
11359 data = PyUnicode_DATA(res);
11360 PyUnicode_WRITE(kind, data, 0, ch);
11361 assert(_PyUnicode_CheckConsistency(res, 1));
11362 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363}
11364
Guido van Rossumc2504932007-09-18 19:42:40 +000011365/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011366 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011367static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011368unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011369{
Guido van Rossumc2504932007-09-18 19:42:40 +000011370 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011371 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011372
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011373#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011374 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011375#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 if (_PyUnicode_HASH(self) != -1)
11377 return _PyUnicode_HASH(self);
11378 if (PyUnicode_READY(self) == -1)
11379 return -1;
11380 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011381 /*
11382 We make the hash of the empty string be 0, rather than using
11383 (prefix ^ suffix), since this slightly obfuscates the hash secret
11384 */
11385 if (len == 0) {
11386 _PyUnicode_HASH(self) = 0;
11387 return 0;
11388 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389
11390 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011391#define HASH(P) \
11392 x ^= (Py_uhash_t) *P << 7; \
11393 while (--len >= 0) \
11394 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395
Georg Brandl2fb477c2012-02-21 00:33:36 +010011396 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 switch (PyUnicode_KIND(self)) {
11398 case PyUnicode_1BYTE_KIND: {
11399 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11400 HASH(c);
11401 break;
11402 }
11403 case PyUnicode_2BYTE_KIND: {
11404 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11405 HASH(s);
11406 break;
11407 }
11408 default: {
11409 Py_UCS4 *l;
11410 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11411 "Impossible switch case in unicode_hash");
11412 l = PyUnicode_4BYTE_DATA(self);
11413 HASH(l);
11414 break;
11415 }
11416 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011417 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11418 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011419
Guido van Rossumc2504932007-09-18 19:42:40 +000011420 if (x == -1)
11421 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011423 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011427PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011430Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
11432static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011435 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011436 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011437 Py_ssize_t start;
11438 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
Jesus Ceaac451502011-04-20 17:09:23 +020011440 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11441 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443
Christian Heimesd47a0452013-06-29 21:21:37 +020011444 if (PyUnicode_READY(self) == -1) {
11445 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011447 }
11448 if (PyUnicode_READY(substring) == -1) {
11449 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452
Victor Stinner7931d9a2011-11-04 00:22:48 +010011453 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454
11455 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 if (result == -2)
11458 return NULL;
11459
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460 if (result < 0) {
11461 PyErr_SetString(PyExc_ValueError, "substring not found");
11462 return NULL;
11463 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011464
Christian Heimes217cfd12007-12-02 14:31:20 +000011465 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466}
11467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011468PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011471Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011472at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473
11474static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011475unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 Py_ssize_t i, length;
11478 int kind;
11479 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 int cased;
11481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 if (PyUnicode_READY(self) == -1)
11483 return NULL;
11484 length = PyUnicode_GET_LENGTH(self);
11485 kind = PyUnicode_KIND(self);
11486 data = PyUnicode_DATA(self);
11487
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 if (length == 1)
11490 return PyBool_FromLong(
11491 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011493 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011495 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011496
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 for (i = 0; i < length; i++) {
11499 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011500
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11502 return PyBool_FromLong(0);
11503 else if (!cased && Py_UNICODE_ISLOWER(ch))
11504 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011506 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507}
11508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011509PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011510 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011512Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011513at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514
11515static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011516unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 Py_ssize_t i, length;
11519 int kind;
11520 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521 int cased;
11522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 if (PyUnicode_READY(self) == -1)
11524 return NULL;
11525 length = PyUnicode_GET_LENGTH(self);
11526 kind = PyUnicode_KIND(self);
11527 data = PyUnicode_DATA(self);
11528
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 if (length == 1)
11531 return PyBool_FromLong(
11532 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011534 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011536 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011537
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011539 for (i = 0; i < length; i++) {
11540 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011541
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11543 return PyBool_FromLong(0);
11544 else if (!cased && Py_UNICODE_ISUPPER(ch))
11545 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011547 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548}
11549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011550PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011551 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011553Return True if S is a titlecased string and there is at least one\n\
11554character in S, i.e. upper- and titlecase characters may only\n\
11555follow uncased characters and lowercase characters only cased ones.\n\
11556Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557
11558static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011559unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011561 Py_ssize_t i, length;
11562 int kind;
11563 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564 int cased, previous_is_cased;
11565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 if (PyUnicode_READY(self) == -1)
11567 return NULL;
11568 length = PyUnicode_GET_LENGTH(self);
11569 kind = PyUnicode_KIND(self);
11570 data = PyUnicode_DATA(self);
11571
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 if (length == 1) {
11574 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11575 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11576 (Py_UNICODE_ISUPPER(ch) != 0));
11577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011579 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011581 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011582
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 cased = 0;
11584 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 for (i = 0; i < length; i++) {
11586 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011587
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11589 if (previous_is_cased)
11590 return PyBool_FromLong(0);
11591 previous_is_cased = 1;
11592 cased = 1;
11593 }
11594 else if (Py_UNICODE_ISLOWER(ch)) {
11595 if (!previous_is_cased)
11596 return PyBool_FromLong(0);
11597 previous_is_cased = 1;
11598 cased = 1;
11599 }
11600 else
11601 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011603 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011609Return True if all characters in S are whitespace\n\
11610and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611
11612static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011613unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 Py_ssize_t i, length;
11616 int kind;
11617 void *data;
11618
11619 if (PyUnicode_READY(self) == -1)
11620 return NULL;
11621 length = PyUnicode_GET_LENGTH(self);
11622 kind = PyUnicode_KIND(self);
11623 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (length == 1)
11627 return PyBool_FromLong(
11628 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011630 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011632 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 for (i = 0; i < length; i++) {
11635 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011636 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011637 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011639 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640}
11641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011642PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011643 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011644\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011645Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011646and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011647
11648static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011649unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 Py_ssize_t i, length;
11652 int kind;
11653 void *data;
11654
11655 if (PyUnicode_READY(self) == -1)
11656 return NULL;
11657 length = PyUnicode_GET_LENGTH(self);
11658 kind = PyUnicode_KIND(self);
11659 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011660
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011661 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 if (length == 1)
11663 return PyBool_FromLong(
11664 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011665
11666 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011668 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 for (i = 0; i < length; i++) {
11671 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011673 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011674 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011675}
11676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011677PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011678 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011679\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011680Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011681and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011682
11683static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011684unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 int kind;
11687 void *data;
11688 Py_ssize_t len, i;
11689
11690 if (PyUnicode_READY(self) == -1)
11691 return NULL;
11692
11693 kind = PyUnicode_KIND(self);
11694 data = PyUnicode_DATA(self);
11695 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011696
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011697 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 if (len == 1) {
11699 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11700 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11701 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011702
11703 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011704 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011705 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 for (i = 0; i < len; i++) {
11708 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011709 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011710 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011711 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011712 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011713}
11714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011715PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011716 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011718Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011719False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
11721static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011722unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 Py_ssize_t i, length;
11725 int kind;
11726 void *data;
11727
11728 if (PyUnicode_READY(self) == -1)
11729 return NULL;
11730 length = PyUnicode_GET_LENGTH(self);
11731 kind = PyUnicode_KIND(self);
11732 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 if (length == 1)
11736 return PyBool_FromLong(
11737 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011739 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011741 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 for (i = 0; i < length; i++) {
11744 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011745 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011747 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748}
11749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011750PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011751 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011753Return True if all characters in S are digits\n\
11754and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
11756static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011757unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 Py_ssize_t i, length;
11760 int kind;
11761 void *data;
11762
11763 if (PyUnicode_READY(self) == -1)
11764 return NULL;
11765 length = PyUnicode_GET_LENGTH(self);
11766 kind = PyUnicode_KIND(self);
11767 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 if (length == 1) {
11771 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11772 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11773 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011775 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 for (i = 0; i < length; i++) {
11780 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011781 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011783 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784}
11785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011786PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011787 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011789Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011790False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791
11792static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011793unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 Py_ssize_t i, length;
11796 int kind;
11797 void *data;
11798
11799 if (PyUnicode_READY(self) == -1)
11800 return NULL;
11801 length = PyUnicode_GET_LENGTH(self);
11802 kind = PyUnicode_KIND(self);
11803 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (length == 1)
11807 return PyBool_FromLong(
11808 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011810 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011812 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 for (i = 0; i < length; i++) {
11815 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011816 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011818 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819}
11820
Martin v. Löwis47383402007-08-15 07:32:56 +000011821int
11822PyUnicode_IsIdentifier(PyObject *self)
11823{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 int kind;
11825 void *data;
11826 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011827 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 if (PyUnicode_READY(self) == -1) {
11830 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011831 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 }
11833
11834 /* Special case for empty strings */
11835 if (PyUnicode_GET_LENGTH(self) == 0)
11836 return 0;
11837 kind = PyUnicode_KIND(self);
11838 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011839
11840 /* PEP 3131 says that the first character must be in
11841 XID_Start and subsequent characters in XID_Continue,
11842 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011843 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011844 letters, digits, underscore). However, given the current
11845 definition of XID_Start and XID_Continue, it is sufficient
11846 to check just for these, except that _ must be allowed
11847 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011849 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011850 return 0;
11851
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011852 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011853 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011854 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011855 return 1;
11856}
11857
11858PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011860\n\
11861Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011862to the language definition.\n\
11863\n\
11864Use keyword.iskeyword() to test for reserved identifiers\n\
11865such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011866
11867static PyObject*
11868unicode_isidentifier(PyObject *self)
11869{
11870 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11871}
11872
Georg Brandl559e5d72008-06-11 18:37:52 +000011873PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011875\n\
11876Return True if all characters in S are considered\n\
11877printable in repr() or S is empty, False otherwise.");
11878
11879static PyObject*
11880unicode_isprintable(PyObject *self)
11881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 Py_ssize_t i, length;
11883 int kind;
11884 void *data;
11885
11886 if (PyUnicode_READY(self) == -1)
11887 return NULL;
11888 length = PyUnicode_GET_LENGTH(self);
11889 kind = PyUnicode_KIND(self);
11890 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011891
11892 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 if (length == 1)
11894 return PyBool_FromLong(
11895 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 for (i = 0; i < length; i++) {
11898 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011899 Py_RETURN_FALSE;
11900 }
11901 }
11902 Py_RETURN_TRUE;
11903}
11904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011905PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011906 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907\n\
11908Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011909iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910
11911static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011912unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011914 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915}
11916
Martin v. Löwis18e16552006-02-15 17:27:45 +000011917static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011918unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 if (PyUnicode_READY(self) == -1)
11921 return -1;
11922 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923}
11924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011925PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011928Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011929done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930
11931static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011932unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011934 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 Py_UCS4 fillchar = ' ';
11936
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011937 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938 return NULL;
11939
Benjamin Petersonbac79492012-01-14 13:34:47 -050011940 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011941 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942
Victor Stinnerc4b49542011-12-11 22:44:26 +010011943 if (PyUnicode_GET_LENGTH(self) >= width)
11944 return unicode_result_unchanged(self);
11945
11946 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947}
11948
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011949PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011952Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953
11954static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011955unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011957 if (PyUnicode_READY(self) == -1)
11958 return NULL;
11959 if (PyUnicode_IS_ASCII(self))
11960 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011961 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962}
11963
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011964#define LEFTSTRIP 0
11965#define RIGHTSTRIP 1
11966#define BOTHSTRIP 2
11967
11968/* Arrays indexed by above */
11969static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11970
11971#define STRIPNAME(i) (stripformat[i]+3)
11972
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011973/* externally visible for str.strip(unicode) */
11974PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011975_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 void *data;
11978 int kind;
11979 Py_ssize_t i, j, len;
11980 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011981 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11984 return NULL;
11985
11986 kind = PyUnicode_KIND(self);
11987 data = PyUnicode_DATA(self);
11988 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011989 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11991 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011992 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011993
Benjamin Peterson14339b62009-01-31 16:36:08 +000011994 i = 0;
11995 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011996 while (i < len) {
11997 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11998 if (!BLOOM(sepmask, ch))
11999 break;
12000 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12001 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 i++;
12003 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012004 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012005
Benjamin Peterson14339b62009-01-31 16:36:08 +000012006 j = len;
12007 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012008 j--;
12009 while (j >= i) {
12010 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12011 if (!BLOOM(sepmask, ch))
12012 break;
12013 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12014 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012015 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012016 }
12017
Benjamin Peterson29060642009-01-31 22:14:21 +000012018 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012019 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012020
Victor Stinner7931d9a2011-11-04 00:22:48 +010012021 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022}
12023
12024PyObject*
12025PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12026{
12027 unsigned char *data;
12028 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012029 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030
Victor Stinnerde636f32011-10-01 03:55:54 +020012031 if (PyUnicode_READY(self) == -1)
12032 return NULL;
12033
Victor Stinner684d5fd2012-05-03 02:32:34 +020012034 length = PyUnicode_GET_LENGTH(self);
12035 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012036
Victor Stinner684d5fd2012-05-03 02:32:34 +020012037 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012038 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039
Victor Stinnerde636f32011-10-01 03:55:54 +020012040 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012041 PyErr_SetString(PyExc_IndexError, "string index out of range");
12042 return NULL;
12043 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012044 if (start >= length || end < start)
12045 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012046
Victor Stinner684d5fd2012-05-03 02:32:34 +020012047 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012048 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012049 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012050 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012051 }
12052 else {
12053 kind = PyUnicode_KIND(self);
12054 data = PyUnicode_1BYTE_DATA(self);
12055 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012056 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012057 length);
12058 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060
12061static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012062do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 Py_ssize_t len, i, j;
12065
12066 if (PyUnicode_READY(self) == -1)
12067 return NULL;
12068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012070
Victor Stinnercc7af722013-04-09 22:39:24 +020012071 if (PyUnicode_IS_ASCII(self)) {
12072 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12073
12074 i = 0;
12075 if (striptype != RIGHTSTRIP) {
12076 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012077 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012078 if (!_Py_ascii_whitespace[ch])
12079 break;
12080 i++;
12081 }
12082 }
12083
12084 j = len;
12085 if (striptype != LEFTSTRIP) {
12086 j--;
12087 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012088 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012089 if (!_Py_ascii_whitespace[ch])
12090 break;
12091 j--;
12092 }
12093 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012094 }
12095 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012096 else {
12097 int kind = PyUnicode_KIND(self);
12098 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012099
Victor Stinnercc7af722013-04-09 22:39:24 +020012100 i = 0;
12101 if (striptype != RIGHTSTRIP) {
12102 while (i < len) {
12103 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12104 if (!Py_UNICODE_ISSPACE(ch))
12105 break;
12106 i++;
12107 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012108 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012109
12110 j = len;
12111 if (striptype != LEFTSTRIP) {
12112 j--;
12113 while (j >= i) {
12114 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12115 if (!Py_UNICODE_ISSPACE(ch))
12116 break;
12117 j--;
12118 }
12119 j++;
12120 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012121 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122
Victor Stinner7931d9a2011-11-04 00:22:48 +010012123 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124}
12125
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012126
12127static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012128do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012129{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012130 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131
Serhiy Storchakac6792272013-10-19 21:03:34 +030012132 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012133 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012134
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 if (sep != NULL && sep != Py_None) {
12136 if (PyUnicode_Check(sep))
12137 return _PyUnicode_XStrip(self, striptype, sep);
12138 else {
12139 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012140 "%s arg must be None or str",
12141 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012142 return NULL;
12143 }
12144 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012147}
12148
12149
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012150PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012151 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012152\n\
12153Return a copy of the string S with leading and trailing\n\
12154whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012155If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012156
12157static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012158unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012159{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012160 if (PyTuple_GET_SIZE(args) == 0)
12161 return do_strip(self, BOTHSTRIP); /* Common case */
12162 else
12163 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012164}
12165
12166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012167PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012168 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012169\n\
12170Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012171If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012172
12173static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012174unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012175{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012176 if (PyTuple_GET_SIZE(args) == 0)
12177 return do_strip(self, LEFTSTRIP); /* Common case */
12178 else
12179 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012180}
12181
12182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012183PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012184 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012185\n\
12186Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012187If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012188
12189static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012190unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012191{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012192 if (PyTuple_GET_SIZE(args) == 0)
12193 return do_strip(self, RIGHTSTRIP); /* Common case */
12194 else
12195 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012196}
12197
12198
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012200unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012202 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204
Serhiy Storchaka05997252013-01-26 12:14:02 +020012205 if (len < 1)
12206 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207
Victor Stinnerc4b49542011-12-11 22:44:26 +010012208 /* no repeat, return original string */
12209 if (len == 1)
12210 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012211
Benjamin Petersonbac79492012-01-14 13:34:47 -050012212 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 return NULL;
12214
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012215 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012216 PyErr_SetString(PyExc_OverflowError,
12217 "repeated string is too long");
12218 return NULL;
12219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012221
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012222 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223 if (!u)
12224 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012225 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012227 if (PyUnicode_GET_LENGTH(str) == 1) {
12228 const int kind = PyUnicode_KIND(str);
12229 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012230 if (kind == PyUnicode_1BYTE_KIND) {
12231 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012232 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012233 }
12234 else if (kind == PyUnicode_2BYTE_KIND) {
12235 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012236 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012237 ucs2[n] = fill_char;
12238 } else {
12239 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12240 assert(kind == PyUnicode_4BYTE_KIND);
12241 for (n = 0; n < len; ++n)
12242 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012244 }
12245 else {
12246 /* number of characters copied this far */
12247 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012248 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249 char *to = (char *) PyUnicode_DATA(u);
12250 Py_MEMCPY(to, PyUnicode_DATA(str),
12251 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012252 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 n = (done <= nchars-done) ? done : nchars-done;
12254 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012255 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012256 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257 }
12258
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012259 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012260 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261}
12262
Alexander Belopolsky40018472011-02-26 01:02:56 +000012263PyObject *
12264PyUnicode_Replace(PyObject *obj,
12265 PyObject *subobj,
12266 PyObject *replobj,
12267 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268{
12269 PyObject *self;
12270 PyObject *str1;
12271 PyObject *str2;
12272 PyObject *result;
12273
12274 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012275 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012276 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012278 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012279 Py_DECREF(self);
12280 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 }
12282 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012283 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 Py_DECREF(self);
12285 Py_DECREF(str1);
12286 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012288 if (PyUnicode_READY(self) == -1 ||
12289 PyUnicode_READY(str1) == -1 ||
12290 PyUnicode_READY(str2) == -1)
12291 result = NULL;
12292 else
12293 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294 Py_DECREF(self);
12295 Py_DECREF(str1);
12296 Py_DECREF(str2);
12297 return result;
12298}
12299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012300PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012301 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302\n\
12303Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012304old replaced by new. If the optional argument count is\n\
12305given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306
12307static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 PyObject *str1;
12311 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012312 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313 PyObject *result;
12314
Martin v. Löwis18e16552006-02-15 17:27:45 +000012315 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012317 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012318 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012320 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 return NULL;
12322 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012323 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012324 Py_DECREF(str1);
12325 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012326 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012327 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12328 result = NULL;
12329 else
12330 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012331
12332 Py_DECREF(str1);
12333 Py_DECREF(str2);
12334 return result;
12335}
12336
Alexander Belopolsky40018472011-02-26 01:02:56 +000012337static PyObject *
12338unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012340 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 Py_ssize_t isize;
12342 Py_ssize_t osize, squote, dquote, i, o;
12343 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012344 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012348 return NULL;
12349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 isize = PyUnicode_GET_LENGTH(unicode);
12351 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 /* Compute length of output, quote characters, and
12354 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012355 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 max = 127;
12357 squote = dquote = 0;
12358 ikind = PyUnicode_KIND(unicode);
12359 for (i = 0; i < isize; i++) {
12360 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12361 switch (ch) {
12362 case '\'': squote++; osize++; break;
12363 case '"': dquote++; osize++; break;
12364 case '\\': case '\t': case '\r': case '\n':
12365 osize += 2; break;
12366 default:
12367 /* Fast-path ASCII */
12368 if (ch < ' ' || ch == 0x7f)
12369 osize += 4; /* \xHH */
12370 else if (ch < 0x7f)
12371 osize++;
12372 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12373 osize++;
12374 max = ch > max ? ch : max;
12375 }
12376 else if (ch < 0x100)
12377 osize += 4; /* \xHH */
12378 else if (ch < 0x10000)
12379 osize += 6; /* \uHHHH */
12380 else
12381 osize += 10; /* \uHHHHHHHH */
12382 }
12383 }
12384
12385 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012386 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012388 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012389 if (dquote)
12390 /* Both squote and dquote present. Use squote,
12391 and escape them */
12392 osize += squote;
12393 else
12394 quote = '"';
12395 }
Victor Stinner55c08782013-04-14 18:45:39 +020012396 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397
12398 repr = PyUnicode_New(osize, max);
12399 if (repr == NULL)
12400 return NULL;
12401 okind = PyUnicode_KIND(repr);
12402 odata = PyUnicode_DATA(repr);
12403
12404 PyUnicode_WRITE(okind, odata, 0, quote);
12405 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012406 if (unchanged) {
12407 _PyUnicode_FastCopyCharacters(repr, 1,
12408 unicode, 0,
12409 isize);
12410 }
12411 else {
12412 for (i = 0, o = 1; i < isize; i++) {
12413 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414
Victor Stinner55c08782013-04-14 18:45:39 +020012415 /* Escape quotes and backslashes */
12416 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012417 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012419 continue;
12420 }
12421
12422 /* Map special whitespace to '\t', \n', '\r' */
12423 if (ch == '\t') {
12424 PyUnicode_WRITE(okind, odata, o++, '\\');
12425 PyUnicode_WRITE(okind, odata, o++, 't');
12426 }
12427 else if (ch == '\n') {
12428 PyUnicode_WRITE(okind, odata, o++, '\\');
12429 PyUnicode_WRITE(okind, odata, o++, 'n');
12430 }
12431 else if (ch == '\r') {
12432 PyUnicode_WRITE(okind, odata, o++, '\\');
12433 PyUnicode_WRITE(okind, odata, o++, 'r');
12434 }
12435
12436 /* Map non-printable US ASCII to '\xhh' */
12437 else if (ch < ' ' || ch == 0x7F) {
12438 PyUnicode_WRITE(okind, odata, o++, '\\');
12439 PyUnicode_WRITE(okind, odata, o++, 'x');
12440 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12441 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12442 }
12443
12444 /* Copy ASCII characters as-is */
12445 else if (ch < 0x7F) {
12446 PyUnicode_WRITE(okind, odata, o++, ch);
12447 }
12448
12449 /* Non-ASCII characters */
12450 else {
12451 /* Map Unicode whitespace and control characters
12452 (categories Z* and C* except ASCII space)
12453 */
12454 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12455 PyUnicode_WRITE(okind, odata, o++, '\\');
12456 /* Map 8-bit characters to '\xhh' */
12457 if (ch <= 0xff) {
12458 PyUnicode_WRITE(okind, odata, o++, 'x');
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12461 }
12462 /* Map 16-bit characters to '\uxxxx' */
12463 else if (ch <= 0xffff) {
12464 PyUnicode_WRITE(okind, odata, o++, 'u');
12465 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12466 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12467 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12468 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12469 }
12470 /* Map 21-bit characters to '\U00xxxxxx' */
12471 else {
12472 PyUnicode_WRITE(okind, odata, o++, 'U');
12473 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12474 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12475 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12476 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12477 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12478 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12479 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12480 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12481 }
12482 }
12483 /* Copy characters as-is */
12484 else {
12485 PyUnicode_WRITE(okind, odata, o++, ch);
12486 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012487 }
12488 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012489 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012490 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012491 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012492 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493}
12494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012495PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012496 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012497\n\
12498Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012499such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012500arguments start and end are interpreted as in slice notation.\n\
12501\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012502Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
12504static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012507 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012508 Py_ssize_t start;
12509 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012510 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511
Jesus Ceaac451502011-04-20 17:09:23 +020012512 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12513 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012514 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515
Christian Heimesea71a522013-06-29 21:17:34 +020012516 if (PyUnicode_READY(self) == -1) {
12517 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012518 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012519 }
12520 if (PyUnicode_READY(substring) == -1) {
12521 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012523 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012524
Victor Stinner7931d9a2011-11-04 00:22:48 +010012525 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526
12527 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 if (result == -2)
12530 return NULL;
12531
Christian Heimes217cfd12007-12-02 14:31:20 +000012532 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533}
12534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012535PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012536 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012538Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539
12540static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012543 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012544 Py_ssize_t start;
12545 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012546 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547
Jesus Ceaac451502011-04-20 17:09:23 +020012548 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12549 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012550 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551
Christian Heimesea71a522013-06-29 21:17:34 +020012552 if (PyUnicode_READY(self) == -1) {
12553 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012555 }
12556 if (PyUnicode_READY(substring) == -1) {
12557 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560
Victor Stinner7931d9a2011-11-04 00:22:48 +010012561 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562
12563 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 if (result == -2)
12566 return NULL;
12567
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568 if (result < 0) {
12569 PyErr_SetString(PyExc_ValueError, "substring not found");
12570 return NULL;
12571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572
Christian Heimes217cfd12007-12-02 14:31:20 +000012573 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574}
12575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012576PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012577 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012579Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012580done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581
12582static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012583unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012585 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 Py_UCS4 fillchar = ' ';
12587
Victor Stinnere9a29352011-10-01 02:14:59 +020012588 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012590
Benjamin Petersonbac79492012-01-14 13:34:47 -050012591 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012592 return NULL;
12593
Victor Stinnerc4b49542011-12-11 22:44:26 +010012594 if (PyUnicode_GET_LENGTH(self) >= width)
12595 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596
Victor Stinnerc4b49542011-12-11 22:44:26 +010012597 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598}
12599
Alexander Belopolsky40018472011-02-26 01:02:56 +000012600PyObject *
12601PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602{
12603 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012604
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605 s = PyUnicode_FromObject(s);
12606 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012607 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012608 if (sep != NULL) {
12609 sep = PyUnicode_FromObject(sep);
12610 if (sep == NULL) {
12611 Py_DECREF(s);
12612 return NULL;
12613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614 }
12615
Victor Stinner9310abb2011-10-05 00:59:23 +020012616 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617
12618 Py_DECREF(s);
12619 Py_XDECREF(sep);
12620 return result;
12621}
12622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012623PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012624 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625\n\
12626Return a list of the words in S, using sep as the\n\
12627delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012628splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012629whitespace string is a separator and empty strings are\n\
12630removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631
12632static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012633unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012635 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012637 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012639 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12640 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641 return NULL;
12642
12643 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012644 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012646 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012648 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649}
12650
Thomas Wouters477c8d52006-05-27 19:21:47 +000012651PyObject *
12652PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12653{
12654 PyObject* str_obj;
12655 PyObject* sep_obj;
12656 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 int kind1, kind2, kind;
12658 void *buf1 = NULL, *buf2 = NULL;
12659 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012660
12661 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012662 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012663 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012664 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012665 if (!sep_obj) {
12666 Py_DECREF(str_obj);
12667 return NULL;
12668 }
12669 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12670 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012671 Py_DECREF(str_obj);
12672 return NULL;
12673 }
12674
Victor Stinner14f8f022011-10-05 20:58:25 +020012675 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012677 kind = Py_MAX(kind1, kind2);
12678 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012679 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012680 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 if (!buf1)
12682 goto onError;
12683 buf2 = PyUnicode_DATA(sep_obj);
12684 if (kind2 != kind)
12685 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12686 if (!buf2)
12687 goto onError;
12688 len1 = PyUnicode_GET_LENGTH(str_obj);
12689 len2 = PyUnicode_GET_LENGTH(sep_obj);
12690
Benjamin Petersonead6b532011-12-20 17:23:42 -060012691 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012693 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12694 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12695 else
12696 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012697 break;
12698 case PyUnicode_2BYTE_KIND:
12699 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12700 break;
12701 case PyUnicode_4BYTE_KIND:
12702 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12703 break;
12704 default:
12705 assert(0);
12706 out = 0;
12707 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012708
12709 Py_DECREF(sep_obj);
12710 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 if (kind1 != kind)
12712 PyMem_Free(buf1);
12713 if (kind2 != kind)
12714 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012715
12716 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 onError:
12718 Py_DECREF(sep_obj);
12719 Py_DECREF(str_obj);
12720 if (kind1 != kind && buf1)
12721 PyMem_Free(buf1);
12722 if (kind2 != kind && buf2)
12723 PyMem_Free(buf2);
12724 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012725}
12726
12727
12728PyObject *
12729PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12730{
12731 PyObject* str_obj;
12732 PyObject* sep_obj;
12733 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012734 int kind1, kind2, kind;
12735 void *buf1 = NULL, *buf2 = NULL;
12736 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012737
12738 str_obj = PyUnicode_FromObject(str_in);
12739 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012740 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012741 sep_obj = PyUnicode_FromObject(sep_in);
12742 if (!sep_obj) {
12743 Py_DECREF(str_obj);
12744 return NULL;
12745 }
12746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 kind1 = PyUnicode_KIND(str_in);
12748 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012749 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 buf1 = PyUnicode_DATA(str_in);
12751 if (kind1 != kind)
12752 buf1 = _PyUnicode_AsKind(str_in, kind);
12753 if (!buf1)
12754 goto onError;
12755 buf2 = PyUnicode_DATA(sep_obj);
12756 if (kind2 != kind)
12757 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12758 if (!buf2)
12759 goto onError;
12760 len1 = PyUnicode_GET_LENGTH(str_obj);
12761 len2 = PyUnicode_GET_LENGTH(sep_obj);
12762
Benjamin Petersonead6b532011-12-20 17:23:42 -060012763 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012765 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12766 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12767 else
12768 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012769 break;
12770 case PyUnicode_2BYTE_KIND:
12771 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12772 break;
12773 case PyUnicode_4BYTE_KIND:
12774 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12775 break;
12776 default:
12777 assert(0);
12778 out = 0;
12779 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012780
12781 Py_DECREF(sep_obj);
12782 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 if (kind1 != kind)
12784 PyMem_Free(buf1);
12785 if (kind2 != kind)
12786 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012787
12788 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012789 onError:
12790 Py_DECREF(sep_obj);
12791 Py_DECREF(str_obj);
12792 if (kind1 != kind && buf1)
12793 PyMem_Free(buf1);
12794 if (kind2 != kind && buf2)
12795 PyMem_Free(buf2);
12796 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797}
12798
12799PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012800 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012801\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012802Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012803the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012804found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012805
12806static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012807unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012808{
Victor Stinner9310abb2011-10-05 00:59:23 +020012809 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012810}
12811
12812PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012813 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012814\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012815Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012816the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012817separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012818
12819static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012820unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012821{
Victor Stinner9310abb2011-10-05 00:59:23 +020012822 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012823}
12824
Alexander Belopolsky40018472011-02-26 01:02:56 +000012825PyObject *
12826PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012827{
12828 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012829
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012830 s = PyUnicode_FromObject(s);
12831 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012832 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 if (sep != NULL) {
12834 sep = PyUnicode_FromObject(sep);
12835 if (sep == NULL) {
12836 Py_DECREF(s);
12837 return NULL;
12838 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012839 }
12840
Victor Stinner9310abb2011-10-05 00:59:23 +020012841 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012842
12843 Py_DECREF(s);
12844 Py_XDECREF(sep);
12845 return result;
12846}
12847
12848PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012849 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012850\n\
12851Return a list of the words in S, using sep as the\n\
12852delimiter string, starting at the end of the string and\n\
12853working to the front. If maxsplit is given, at most maxsplit\n\
12854splits are done. If sep is not specified, any whitespace string\n\
12855is a separator.");
12856
12857static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012858unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012859{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012860 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012861 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012862 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012863
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012864 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12865 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012866 return NULL;
12867
12868 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012869 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012870 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012871 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012872 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012873 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012874}
12875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012876PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878\n\
12879Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012880Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012881is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882
12883static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012884unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012886 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012887 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012889 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12890 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891 return NULL;
12892
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012893 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012894}
12895
12896static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012897PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012898{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012899 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900}
12901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012902PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012903 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012904\n\
12905Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012906and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907
12908static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012909unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012910{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012911 if (PyUnicode_READY(self) == -1)
12912 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012913 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012914}
12915
Larry Hastings31826802013-10-19 00:09:25 -070012916/*[clinic]
Larry Hastingsed4a1c52013-11-18 09:32:13 -080012917class str
Georg Brandlceee0772007-11-27 23:48:05 +000012918
Larry Hastings31826802013-10-19 00:09:25 -070012919@staticmethod
12920str.maketrans as unicode_maketrans
12921
12922 x: object
12923
12924 y: unicode=NULL
12925
12926 z: unicode=NULL
12927
12928 /
12929
12930Return a translation table usable for str.translate().
12931
12932If there is only one argument, it must be a dictionary mapping Unicode
12933ordinals (integers) or characters to Unicode ordinals, strings or None.
12934Character keys will be then converted to ordinals.
12935If there are two arguments, they must be strings of equal length, and
12936in the resulting dictionary, each character in x will be mapped to the
12937character at the same position in y. If there is a third argument, it
12938must be a string, whose characters will be mapped to None in the result.
12939[clinic]*/
12940
12941PyDoc_STRVAR(unicode_maketrans__doc__,
12942"Return a translation table usable for str.translate().\n"
12943"\n"
12944"str.maketrans(x, y=None, z=None)\n"
12945"\n"
12946"If there is only one argument, it must be a dictionary mapping Unicode\n"
12947"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12948"Character keys will be then converted to ordinals.\n"
12949"If there are two arguments, they must be strings of equal length, and\n"
12950"in the resulting dictionary, each character in x will be mapped to the\n"
12951"character at the same position in y. If there is a third argument, it\n"
12952"must be a string, whose characters will be mapped to None in the result.");
12953
12954#define UNICODE_MAKETRANS_METHODDEF \
12955 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12956
12957static PyObject *
12958unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
12959
12960static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012961unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012962{
Larry Hastings31826802013-10-19 00:09:25 -070012963 PyObject *return_value = NULL;
12964 PyObject *x;
12965 PyObject *y = NULL;
12966 PyObject *z = NULL;
12967
12968 if (!PyArg_ParseTuple(args,
12969 "O|UU:maketrans",
12970 &x, &y, &z))
12971 goto exit;
12972 return_value = unicode_maketrans_impl(x, y, z);
12973
12974exit:
12975 return return_value;
12976}
12977
12978static PyObject *
12979unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
12980/*[clinic checksum: 137db9c3199e7906b7967009f511c24fa3235b5f]*/
12981{
Georg Brandlceee0772007-11-27 23:48:05 +000012982 PyObject *new = NULL, *key, *value;
12983 Py_ssize_t i = 0;
12984 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012985
Georg Brandlceee0772007-11-27 23:48:05 +000012986 new = PyDict_New();
12987 if (!new)
12988 return NULL;
12989 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 int x_kind, y_kind, z_kind;
12991 void *x_data, *y_data, *z_data;
12992
Georg Brandlceee0772007-11-27 23:48:05 +000012993 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012994 if (!PyUnicode_Check(x)) {
12995 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12996 "be a string if there is a second argument");
12997 goto err;
12998 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012999 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013000 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13001 "arguments must have equal length");
13002 goto err;
13003 }
13004 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013005 x_kind = PyUnicode_KIND(x);
13006 y_kind = PyUnicode_KIND(y);
13007 x_data = PyUnicode_DATA(x);
13008 y_data = PyUnicode_DATA(y);
13009 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13010 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013011 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013012 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013013 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013014 if (!value) {
13015 Py_DECREF(key);
13016 goto err;
13017 }
Georg Brandlceee0772007-11-27 23:48:05 +000013018 res = PyDict_SetItem(new, key, value);
13019 Py_DECREF(key);
13020 Py_DECREF(value);
13021 if (res < 0)
13022 goto err;
13023 }
13024 /* create entries for deleting chars in z */
13025 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 z_kind = PyUnicode_KIND(z);
13027 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013028 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013029 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013030 if (!key)
13031 goto err;
13032 res = PyDict_SetItem(new, key, Py_None);
13033 Py_DECREF(key);
13034 if (res < 0)
13035 goto err;
13036 }
13037 }
13038 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 int kind;
13040 void *data;
13041
Georg Brandlceee0772007-11-27 23:48:05 +000013042 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013043 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013044 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13045 "to maketrans it must be a dict");
13046 goto err;
13047 }
13048 /* copy entries into the new dict, converting string keys to int keys */
13049 while (PyDict_Next(x, &i, &key, &value)) {
13050 if (PyUnicode_Check(key)) {
13051 /* convert string keys to integer keys */
13052 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013053 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013054 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13055 "table must be of length 1");
13056 goto err;
13057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013058 kind = PyUnicode_KIND(key);
13059 data = PyUnicode_DATA(key);
13060 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013061 if (!newkey)
13062 goto err;
13063 res = PyDict_SetItem(new, newkey, value);
13064 Py_DECREF(newkey);
13065 if (res < 0)
13066 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013067 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013068 /* just keep integer keys */
13069 if (PyDict_SetItem(new, key, value) < 0)
13070 goto err;
13071 } else {
13072 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13073 "be strings or integers");
13074 goto err;
13075 }
13076 }
13077 }
13078 return new;
13079 err:
13080 Py_DECREF(new);
13081 return NULL;
13082}
13083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013084PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013085 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013086\n\
13087Return a copy of the string S, where all characters have been mapped\n\
13088through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013089Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013090Unmapped characters are left untouched. Characters mapped to None\n\
13091are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013092
13093static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013094unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013096 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097}
13098
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013099PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013100 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013102Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103
13104static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013105unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013107 if (PyUnicode_READY(self) == -1)
13108 return NULL;
13109 if (PyUnicode_IS_ASCII(self))
13110 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013111 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112}
13113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013114PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013115 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013117Pad a numeric string S with zeros on the left, to fill a field\n\
13118of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119
13120static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013121unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013123 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013124 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013125 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013126 int kind;
13127 void *data;
13128 Py_UCS4 chr;
13129
Martin v. Löwis18e16552006-02-15 17:27:45 +000013130 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131 return NULL;
13132
Benjamin Petersonbac79492012-01-14 13:34:47 -050013133 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013134 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135
Victor Stinnerc4b49542011-12-11 22:44:26 +010013136 if (PyUnicode_GET_LENGTH(self) >= width)
13137 return unicode_result_unchanged(self);
13138
13139 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140
13141 u = pad(self, fill, 0, '0');
13142
Walter Dörwald068325e2002-04-15 13:36:47 +000013143 if (u == NULL)
13144 return NULL;
13145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013146 kind = PyUnicode_KIND(u);
13147 data = PyUnicode_DATA(u);
13148 chr = PyUnicode_READ(kind, data, fill);
13149
13150 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 PyUnicode_WRITE(kind, data, 0, chr);
13153 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154 }
13155
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013156 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013157 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013159
13160#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013161static PyObject *
13162unicode__decimal2ascii(PyObject *self)
13163{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013165}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166#endif
13167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013168PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013171Return True if S starts with the specified prefix, False otherwise.\n\
13172With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013173With optional end, stop comparing S at that position.\n\
13174prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175
13176static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013177unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013178 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013181 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013182 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013183 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013184 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013185
Jesus Ceaac451502011-04-20 17:09:23 +020013186 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013188 if (PyTuple_Check(subobj)) {
13189 Py_ssize_t i;
13190 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013191 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013192 if (substring == NULL)
13193 return NULL;
13194 result = tailmatch(self, substring, start, end, -1);
13195 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013196 if (result == -1)
13197 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013198 if (result) {
13199 Py_RETURN_TRUE;
13200 }
13201 }
13202 /* nothing matched */
13203 Py_RETURN_FALSE;
13204 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013205 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013206 if (substring == NULL) {
13207 if (PyErr_ExceptionMatches(PyExc_TypeError))
13208 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13209 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013210 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013211 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013212 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013214 if (result == -1)
13215 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013216 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217}
13218
13219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013220PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013222\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013223Return True if S ends with the specified suffix, False otherwise.\n\
13224With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013225With optional end, stop comparing S at that position.\n\
13226suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227
13228static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013229unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013232 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013233 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013234 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013235 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013236 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237
Jesus Ceaac451502011-04-20 17:09:23 +020013238 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013240 if (PyTuple_Check(subobj)) {
13241 Py_ssize_t i;
13242 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013243 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013245 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013247 result = tailmatch(self, substring, start, end, +1);
13248 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013249 if (result == -1)
13250 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013251 if (result) {
13252 Py_RETURN_TRUE;
13253 }
13254 }
13255 Py_RETURN_FALSE;
13256 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013257 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013258 if (substring == NULL) {
13259 if (PyErr_ExceptionMatches(PyExc_TypeError))
13260 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13261 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013263 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013264 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013265 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013266 if (result == -1)
13267 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013268 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269}
13270
Victor Stinner202fdca2012-05-07 12:47:02 +020013271Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013272_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013273{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013274 if (!writer->readonly)
13275 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13276 else {
13277 /* Copy-on-write mode: set buffer size to 0 so
13278 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13279 * next write. */
13280 writer->size = 0;
13281 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013282 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13283 writer->data = PyUnicode_DATA(writer->buffer);
13284 writer->kind = PyUnicode_KIND(writer->buffer);
13285}
13286
Victor Stinnerd3f08822012-05-29 12:57:52 +020013287void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013288_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013289{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013290 memset(writer, 0, sizeof(*writer));
13291#ifdef Py_DEBUG
13292 writer->kind = 5; /* invalid kind */
13293#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013294 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013295}
13296
Victor Stinnerd3f08822012-05-29 12:57:52 +020013297int
13298_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13299 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013300{
Victor Stinner6989ba02013-11-18 21:08:39 +010013301#ifdef MS_WINDOWS
13302 /* On Windows, overallocate by 50% is the best factor */
13303# define OVERALLOCATE_FACTOR 2
13304#else
13305 /* On Linux, overallocate by 25% is the best factor */
13306# define OVERALLOCATE_FACTOR 4
13307#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013308 Py_ssize_t newlen;
13309 PyObject *newbuffer;
13310
Victor Stinnerd3f08822012-05-29 12:57:52 +020013311 assert(length > 0);
13312
Victor Stinner202fdca2012-05-07 12:47:02 +020013313 if (length > PY_SSIZE_T_MAX - writer->pos) {
13314 PyErr_NoMemory();
13315 return -1;
13316 }
13317 newlen = writer->pos + length;
13318
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013319 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013320
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013322 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013323 if (writer->overallocate
13324 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13325 /* overallocate to limit the number of realloc() */
13326 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013328 if (newlen < writer->min_length)
13329 newlen = writer->min_length;
13330
Victor Stinnerd3f08822012-05-29 12:57:52 +020013331 writer->buffer = PyUnicode_New(newlen, maxchar);
13332 if (writer->buffer == NULL)
13333 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013334 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013335 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013336 if (writer->overallocate
13337 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13338 /* overallocate to limit the number of realloc() */
13339 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013340 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013341 if (newlen < writer->min_length)
13342 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013343
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013344 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013345 /* resize + widen */
13346 newbuffer = PyUnicode_New(newlen, maxchar);
13347 if (newbuffer == NULL)
13348 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13350 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013351 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013352 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013353 }
13354 else {
13355 newbuffer = resize_compact(writer->buffer, newlen);
13356 if (newbuffer == NULL)
13357 return -1;
13358 }
13359 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013360 }
13361 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013362 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013363 newbuffer = PyUnicode_New(writer->size, maxchar);
13364 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013365 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013366 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13367 writer->buffer, 0, writer->pos);
13368 Py_DECREF(writer->buffer);
13369 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013370 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013371 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013372 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013373
13374#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013375}
13376
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013377Py_LOCAL_INLINE(int)
13378_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013379{
13380 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13381 return -1;
13382 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13383 writer->pos++;
13384 return 0;
13385}
13386
13387int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013388_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13389{
13390 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13391}
13392
13393int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013394_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13395{
13396 Py_UCS4 maxchar;
13397 Py_ssize_t len;
13398
13399 if (PyUnicode_READY(str) == -1)
13400 return -1;
13401 len = PyUnicode_GET_LENGTH(str);
13402 if (len == 0)
13403 return 0;
13404 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13405 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013406 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013407 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013408 Py_INCREF(str);
13409 writer->buffer = str;
13410 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013411 writer->pos += len;
13412 return 0;
13413 }
13414 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13415 return -1;
13416 }
13417 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13418 str, 0, len);
13419 writer->pos += len;
13420 return 0;
13421}
13422
Victor Stinnere215d962012-10-06 23:03:36 +020013423int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013424_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13425 Py_ssize_t start, Py_ssize_t end)
13426{
13427 Py_UCS4 maxchar;
13428 Py_ssize_t len;
13429
13430 if (PyUnicode_READY(str) == -1)
13431 return -1;
13432
13433 assert(0 <= start);
13434 assert(end <= PyUnicode_GET_LENGTH(str));
13435 assert(start <= end);
13436
13437 if (end == 0)
13438 return 0;
13439
13440 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13441 return _PyUnicodeWriter_WriteStr(writer, str);
13442
13443 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13444 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13445 else
13446 maxchar = writer->maxchar;
13447 len = end - start;
13448
13449 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13450 return -1;
13451
13452 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13453 str, start, len);
13454 writer->pos += len;
13455 return 0;
13456}
13457
13458int
Victor Stinner4a587072013-11-19 12:54:53 +010013459_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13460 const char *ascii, Py_ssize_t len)
13461{
13462 if (len == -1)
13463 len = strlen(ascii);
13464
13465 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13466
13467 if (writer->buffer == NULL && !writer->overallocate) {
13468 PyObject *str;
13469
13470 str = _PyUnicode_FromASCII(ascii, len);
13471 if (str == NULL)
13472 return -1;
13473
13474 writer->readonly = 1;
13475 writer->buffer = str;
13476 _PyUnicodeWriter_Update(writer);
13477 writer->pos += len;
13478 return 0;
13479 }
13480
13481 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13482 return -1;
13483
13484 switch (writer->kind)
13485 {
13486 case PyUnicode_1BYTE_KIND:
13487 {
13488 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13489 Py_UCS1 *data = writer->data;
13490
13491 Py_MEMCPY(data + writer->pos, str, len);
13492 break;
13493 }
13494 case PyUnicode_2BYTE_KIND:
13495 {
13496 _PyUnicode_CONVERT_BYTES(
13497 Py_UCS1, Py_UCS2,
13498 ascii, ascii + len,
13499 (Py_UCS2 *)writer->data + writer->pos);
13500 break;
13501 }
13502 case PyUnicode_4BYTE_KIND:
13503 {
13504 _PyUnicode_CONVERT_BYTES(
13505 Py_UCS1, Py_UCS4,
13506 ascii, ascii + len,
13507 (Py_UCS4 *)writer->data + writer->pos);
13508 break;
13509 }
13510 default:
13511 assert(0);
13512 }
13513
13514 writer->pos += len;
13515 return 0;
13516}
13517
13518int
13519_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13520 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013521{
13522 Py_UCS4 maxchar;
13523
13524 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13525 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13526 return -1;
13527 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13528 writer->pos += len;
13529 return 0;
13530}
13531
Victor Stinnerd3f08822012-05-29 12:57:52 +020013532PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013533_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013534{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013535 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013536 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013537 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013538 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013540 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013541 str = writer->buffer;
13542 writer->buffer = NULL;
13543 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13544 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013545 }
13546 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13547 PyObject *newbuffer;
13548 newbuffer = resize_compact(writer->buffer, writer->pos);
13549 if (newbuffer == NULL) {
13550 Py_DECREF(writer->buffer);
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013551 writer->buffer = NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013552 return NULL;
13553 }
13554 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013555 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013556 str = writer->buffer;
13557 writer->buffer = NULL;
13558 assert(_PyUnicode_CheckConsistency(str, 1));
13559 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013560}
13561
Victor Stinnerd3f08822012-05-29 12:57:52 +020013562void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013563_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013564{
13565 Py_CLEAR(writer->buffer);
13566}
13567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013568#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013569
13570PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013572\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013573Return a formatted version of S, using substitutions from args and kwargs.\n\
13574The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013575
Eric Smith27bbca62010-11-04 17:06:58 +000013576PyDoc_STRVAR(format_map__doc__,
13577 "S.format_map(mapping) -> str\n\
13578\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013579Return a formatted version of S, using substitutions from mapping.\n\
13580The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013581
Eric Smith4a7d76d2008-05-30 18:10:19 +000013582static PyObject *
13583unicode__format__(PyObject* self, PyObject* args)
13584{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013585 PyObject *format_spec;
13586 _PyUnicodeWriter writer;
13587 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013588
13589 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13590 return NULL;
13591
Victor Stinnerd3f08822012-05-29 12:57:52 +020013592 if (PyUnicode_READY(self) == -1)
13593 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013594 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013595 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13596 self, format_spec, 0,
13597 PyUnicode_GET_LENGTH(format_spec));
13598 if (ret == -1) {
13599 _PyUnicodeWriter_Dealloc(&writer);
13600 return NULL;
13601 }
13602 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013603}
13604
Eric Smith8c663262007-08-25 02:26:07 +000013605PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013607\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013608Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013609
13610static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013611unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 Py_ssize_t size;
13614
13615 /* If it's a compact object, account for base structure +
13616 character data. */
13617 if (PyUnicode_IS_COMPACT_ASCII(v))
13618 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13619 else if (PyUnicode_IS_COMPACT(v))
13620 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013621 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013622 else {
13623 /* If it is a two-block object, account for base object, and
13624 for character block if present. */
13625 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013626 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013627 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013628 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629 }
13630 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013631 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013632 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013633 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013634 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013635 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013636
13637 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013638}
13639
13640PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013642
13643static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013644unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013645{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013646 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013647 if (!copy)
13648 return NULL;
13649 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013650}
13651
Guido van Rossumd57fd912000-03-10 22:53:23 +000013652static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013653 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013654 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013655 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13656 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013657 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13658 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013659 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013660 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13661 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13662 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013663 {"expandtabs", (PyCFunction) unicode_expandtabs,
13664 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013665 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013666 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013667 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13668 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13669 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013670 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013671 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13672 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13673 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013674 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013675 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013676 {"splitlines", (PyCFunction) unicode_splitlines,
13677 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013678 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013679 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13680 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13681 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13682 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13683 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13684 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13685 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13686 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13687 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13688 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13689 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13690 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13691 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13692 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013693 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013694 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013695 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013696 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013697 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013698 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013699 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013700 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013701#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013702 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013703 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013704#endif
13705
Benjamin Peterson14339b62009-01-31 16:36:08 +000013706 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013707 {NULL, NULL}
13708};
13709
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013710static PyObject *
13711unicode_mod(PyObject *v, PyObject *w)
13712{
Brian Curtindfc80e32011-08-10 20:28:54 -050013713 if (!PyUnicode_Check(v))
13714 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013715 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013716}
13717
13718static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013719 0, /*nb_add*/
13720 0, /*nb_subtract*/
13721 0, /*nb_multiply*/
13722 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013723};
13724
Guido van Rossumd57fd912000-03-10 22:53:23 +000013725static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013726 (lenfunc) unicode_length, /* sq_length */
13727 PyUnicode_Concat, /* sq_concat */
13728 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13729 (ssizeargfunc) unicode_getitem, /* sq_item */
13730 0, /* sq_slice */
13731 0, /* sq_ass_item */
13732 0, /* sq_ass_slice */
13733 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013734};
13735
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013736static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013737unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013738{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013739 if (PyUnicode_READY(self) == -1)
13740 return NULL;
13741
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013742 if (PyIndex_Check(item)) {
13743 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013744 if (i == -1 && PyErr_Occurred())
13745 return NULL;
13746 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013747 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013748 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013749 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013750 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013751 PyObject *result;
13752 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013753 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013754 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013756 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013757 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013758 return NULL;
13759 }
13760
13761 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013762 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013763 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013764 slicelength == PyUnicode_GET_LENGTH(self)) {
13765 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013766 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013767 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013768 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013769 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013770 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013771 src_kind = PyUnicode_KIND(self);
13772 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013773 if (!PyUnicode_IS_ASCII(self)) {
13774 kind_limit = kind_maxchar_limit(src_kind);
13775 max_char = 0;
13776 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13777 ch = PyUnicode_READ(src_kind, src_data, cur);
13778 if (ch > max_char) {
13779 max_char = ch;
13780 if (max_char >= kind_limit)
13781 break;
13782 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013783 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013784 }
Victor Stinner55c99112011-10-13 01:17:06 +020013785 else
13786 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013787 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013788 if (result == NULL)
13789 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013790 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013791 dest_data = PyUnicode_DATA(result);
13792
13793 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013794 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13795 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013796 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013797 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013798 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013799 } else {
13800 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13801 return NULL;
13802 }
13803}
13804
13805static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013806 (lenfunc)unicode_length, /* mp_length */
13807 (binaryfunc)unicode_subscript, /* mp_subscript */
13808 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013809};
13810
Guido van Rossumd57fd912000-03-10 22:53:23 +000013811
Guido van Rossumd57fd912000-03-10 22:53:23 +000013812/* Helpers for PyUnicode_Format() */
13813
Victor Stinnera47082312012-10-04 02:19:54 +020013814struct unicode_formatter_t {
13815 PyObject *args;
13816 int args_owned;
13817 Py_ssize_t arglen, argidx;
13818 PyObject *dict;
13819
13820 enum PyUnicode_Kind fmtkind;
13821 Py_ssize_t fmtcnt, fmtpos;
13822 void *fmtdata;
13823 PyObject *fmtstr;
13824
13825 _PyUnicodeWriter writer;
13826};
13827
13828struct unicode_format_arg_t {
13829 Py_UCS4 ch;
13830 int flags;
13831 Py_ssize_t width;
13832 int prec;
13833 int sign;
13834};
13835
Guido van Rossumd57fd912000-03-10 22:53:23 +000013836static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013837unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013838{
Victor Stinnera47082312012-10-04 02:19:54 +020013839 Py_ssize_t argidx = ctx->argidx;
13840
13841 if (argidx < ctx->arglen) {
13842 ctx->argidx++;
13843 if (ctx->arglen < 0)
13844 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013845 else
Victor Stinnera47082312012-10-04 02:19:54 +020013846 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013847 }
13848 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013849 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013850 return NULL;
13851}
13852
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013853/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854
Victor Stinnera47082312012-10-04 02:19:54 +020013855/* Format a float into the writer if the writer is not NULL, or into *p_output
13856 otherwise.
13857
13858 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013859static int
Victor Stinnera47082312012-10-04 02:19:54 +020013860formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13861 PyObject **p_output,
13862 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013864 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013865 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013866 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013867 int prec;
13868 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013869
Guido van Rossumd57fd912000-03-10 22:53:23 +000013870 x = PyFloat_AsDouble(v);
13871 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013872 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013873
Victor Stinnera47082312012-10-04 02:19:54 +020013874 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013875 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013876 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013877
Victor Stinnera47082312012-10-04 02:19:54 +020013878 if (arg->flags & F_ALT)
13879 dtoa_flags = Py_DTSF_ALT;
13880 else
13881 dtoa_flags = 0;
13882 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013883 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013884 return -1;
13885 len = strlen(p);
13886 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013887 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013888 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013889 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013890 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013891 }
13892 else
13893 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013894 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013895 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013896}
13897
Victor Stinnerd0880d52012-04-27 23:40:13 +020013898/* formatlong() emulates the format codes d, u, o, x and X, and
13899 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13900 * Python's regular ints.
13901 * Return value: a new PyUnicodeObject*, or NULL if error.
13902 * The output string is of the form
13903 * "-"? ("0x" | "0X")? digit+
13904 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13905 * set in flags. The case of hex digits will be correct,
13906 * There will be at least prec digits, zero-filled on the left if
13907 * necessary to get that many.
13908 * val object to be converted
13909 * flags bitmask of format flags; only F_ALT is looked at
13910 * prec minimum number of digits; 0-fill on left if needed
13911 * type a character in [duoxX]; u acts the same as d
13912 *
13913 * CAUTION: o, x and X conversions on regular ints can never
13914 * produce a '-' sign, but can for Python's unbounded ints.
13915 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013916static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013917formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013918{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013919 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013920 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013921 Py_ssize_t i;
13922 int sign; /* 1 if '-', else 0 */
13923 int len; /* number of characters */
13924 Py_ssize_t llen;
13925 int numdigits; /* len == numnondigits + numdigits */
13926 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013927 int prec = arg->prec;
13928 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013929
Victor Stinnerd0880d52012-04-27 23:40:13 +020013930 /* Avoid exceeding SSIZE_T_MAX */
13931 if (prec > INT_MAX-3) {
13932 PyErr_SetString(PyExc_OverflowError,
13933 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013934 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013935 }
13936
13937 assert(PyLong_Check(val));
13938
13939 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013940 default:
13941 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013942 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013943 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013944 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013945 /* int and int subclasses should print numerically when a numeric */
13946 /* format code is used (see issue18780) */
13947 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013948 break;
13949 case 'o':
13950 numnondigits = 2;
13951 result = PyNumber_ToBase(val, 8);
13952 break;
13953 case 'x':
13954 case 'X':
13955 numnondigits = 2;
13956 result = PyNumber_ToBase(val, 16);
13957 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013958 }
13959 if (!result)
13960 return NULL;
13961
13962 assert(unicode_modifiable(result));
13963 assert(PyUnicode_IS_READY(result));
13964 assert(PyUnicode_IS_ASCII(result));
13965
13966 /* To modify the string in-place, there can only be one reference. */
13967 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013968 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013969 PyErr_BadInternalCall();
13970 return NULL;
13971 }
13972 buf = PyUnicode_DATA(result);
13973 llen = PyUnicode_GET_LENGTH(result);
13974 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013975 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013976 PyErr_SetString(PyExc_ValueError,
13977 "string too large in _PyBytes_FormatLong");
13978 return NULL;
13979 }
13980 len = (int)llen;
13981 sign = buf[0] == '-';
13982 numnondigits += sign;
13983 numdigits = len - numnondigits;
13984 assert(numdigits > 0);
13985
13986 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013987 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013988 (type == 'o' || type == 'x' || type == 'X'))) {
13989 assert(buf[sign] == '0');
13990 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13991 buf[sign+1] == 'o');
13992 numnondigits -= 2;
13993 buf += 2;
13994 len -= 2;
13995 if (sign)
13996 buf[0] = '-';
13997 assert(len == numnondigits + numdigits);
13998 assert(numdigits > 0);
13999 }
14000
14001 /* Fill with leading zeroes to meet minimum width. */
14002 if (prec > numdigits) {
14003 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14004 numnondigits + prec);
14005 char *b1;
14006 if (!r1) {
14007 Py_DECREF(result);
14008 return NULL;
14009 }
14010 b1 = PyBytes_AS_STRING(r1);
14011 for (i = 0; i < numnondigits; ++i)
14012 *b1++ = *buf++;
14013 for (i = 0; i < prec - numdigits; i++)
14014 *b1++ = '0';
14015 for (i = 0; i < numdigits; i++)
14016 *b1++ = *buf++;
14017 *b1 = '\0';
14018 Py_DECREF(result);
14019 result = r1;
14020 buf = PyBytes_AS_STRING(result);
14021 len = numnondigits + prec;
14022 }
14023
14024 /* Fix up case for hex conversions. */
14025 if (type == 'X') {
14026 /* Need to convert all lower case letters to upper case.
14027 and need to convert 0x to 0X (and -0x to -0X). */
14028 for (i = 0; i < len; i++)
14029 if (buf[i] >= 'a' && buf[i] <= 'x')
14030 buf[i] -= 'a'-'A';
14031 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014032 if (!PyUnicode_Check(result)
14033 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014034 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014035 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014036 Py_DECREF(result);
14037 result = unicode;
14038 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014039 else if (len != PyUnicode_GET_LENGTH(result)) {
14040 if (PyUnicode_Resize(&result, len) < 0)
14041 Py_CLEAR(result);
14042 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014044}
14045
Victor Stinner621ef3d2012-10-02 00:33:47 +020014046/* Format an integer.
14047 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014048 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014049 * -1 and raise an exception on error */
14050static int
Victor Stinnera47082312012-10-04 02:19:54 +020014051mainformatlong(PyObject *v,
14052 struct unicode_format_arg_t *arg,
14053 PyObject **p_output,
14054 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014055{
14056 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014057 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014058
14059 if (!PyNumber_Check(v))
14060 goto wrongtype;
14061
14062 if (!PyLong_Check(v)) {
14063 iobj = PyNumber_Long(v);
14064 if (iobj == NULL) {
14065 if (PyErr_ExceptionMatches(PyExc_TypeError))
14066 goto wrongtype;
14067 return -1;
14068 }
14069 assert(PyLong_Check(iobj));
14070 }
14071 else {
14072 iobj = v;
14073 Py_INCREF(iobj);
14074 }
14075
14076 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014077 && arg->width == -1 && arg->prec == -1
14078 && !(arg->flags & (F_SIGN | F_BLANK))
14079 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014080 {
14081 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014082 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014083 int base;
14084
Victor Stinnera47082312012-10-04 02:19:54 +020014085 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014086 {
14087 default:
14088 assert(0 && "'type' not in [diuoxX]");
14089 case 'd':
14090 case 'i':
14091 case 'u':
14092 base = 10;
14093 break;
14094 case 'o':
14095 base = 8;
14096 break;
14097 case 'x':
14098 case 'X':
14099 base = 16;
14100 break;
14101 }
14102
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014103 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14104 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014105 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014106 }
14107 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014108 return 1;
14109 }
14110
Victor Stinnera47082312012-10-04 02:19:54 +020014111 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014112 Py_DECREF(iobj);
14113 if (res == NULL)
14114 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014115 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014116 return 0;
14117
14118wrongtype:
14119 PyErr_Format(PyExc_TypeError,
14120 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014121 "not %.200s",
14122 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014123 return -1;
14124}
14125
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014126static Py_UCS4
14127formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014128{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014129 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014130 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014131 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014132 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 goto onError;
14135 }
14136 else {
14137 /* Integer input truncated to a character */
14138 long x;
14139 x = PyLong_AsLong(v);
14140 if (x == -1 && PyErr_Occurred())
14141 goto onError;
14142
Victor Stinner8faf8212011-12-08 22:14:11 +010014143 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014144 PyErr_SetString(PyExc_OverflowError,
14145 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014146 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014147 }
14148
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014149 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014150 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014151
Benjamin Peterson29060642009-01-31 22:14:21 +000014152 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014153 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014154 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014155 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014156}
14157
Victor Stinnera47082312012-10-04 02:19:54 +020014158/* Parse options of an argument: flags, width, precision.
14159 Handle also "%(name)" syntax.
14160
14161 Return 0 if the argument has been formatted into arg->str.
14162 Return 1 if the argument has been written into ctx->writer,
14163 Raise an exception and return -1 on error. */
14164static int
14165unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14166 struct unicode_format_arg_t *arg)
14167{
14168#define FORMAT_READ(ctx) \
14169 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14170
14171 PyObject *v;
14172
Victor Stinnera47082312012-10-04 02:19:54 +020014173 if (arg->ch == '(') {
14174 /* Get argument value from a dictionary. Example: "%(name)s". */
14175 Py_ssize_t keystart;
14176 Py_ssize_t keylen;
14177 PyObject *key;
14178 int pcount = 1;
14179
14180 if (ctx->dict == NULL) {
14181 PyErr_SetString(PyExc_TypeError,
14182 "format requires a mapping");
14183 return -1;
14184 }
14185 ++ctx->fmtpos;
14186 --ctx->fmtcnt;
14187 keystart = ctx->fmtpos;
14188 /* Skip over balanced parentheses */
14189 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14190 arg->ch = FORMAT_READ(ctx);
14191 if (arg->ch == ')')
14192 --pcount;
14193 else if (arg->ch == '(')
14194 ++pcount;
14195 ctx->fmtpos++;
14196 }
14197 keylen = ctx->fmtpos - keystart - 1;
14198 if (ctx->fmtcnt < 0 || pcount > 0) {
14199 PyErr_SetString(PyExc_ValueError,
14200 "incomplete format key");
14201 return -1;
14202 }
14203 key = PyUnicode_Substring(ctx->fmtstr,
14204 keystart, keystart + keylen);
14205 if (key == NULL)
14206 return -1;
14207 if (ctx->args_owned) {
14208 Py_DECREF(ctx->args);
14209 ctx->args_owned = 0;
14210 }
14211 ctx->args = PyObject_GetItem(ctx->dict, key);
14212 Py_DECREF(key);
14213 if (ctx->args == NULL)
14214 return -1;
14215 ctx->args_owned = 1;
14216 ctx->arglen = -1;
14217 ctx->argidx = -2;
14218 }
14219
14220 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014221 while (--ctx->fmtcnt >= 0) {
14222 arg->ch = FORMAT_READ(ctx);
14223 ctx->fmtpos++;
14224 switch (arg->ch) {
14225 case '-': arg->flags |= F_LJUST; continue;
14226 case '+': arg->flags |= F_SIGN; continue;
14227 case ' ': arg->flags |= F_BLANK; continue;
14228 case '#': arg->flags |= F_ALT; continue;
14229 case '0': arg->flags |= F_ZERO; continue;
14230 }
14231 break;
14232 }
14233
14234 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014235 if (arg->ch == '*') {
14236 v = unicode_format_getnextarg(ctx);
14237 if (v == NULL)
14238 return -1;
14239 if (!PyLong_Check(v)) {
14240 PyErr_SetString(PyExc_TypeError,
14241 "* wants int");
14242 return -1;
14243 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014244 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014245 if (arg->width == -1 && PyErr_Occurred())
14246 return -1;
14247 if (arg->width < 0) {
14248 arg->flags |= F_LJUST;
14249 arg->width = -arg->width;
14250 }
14251 if (--ctx->fmtcnt >= 0) {
14252 arg->ch = FORMAT_READ(ctx);
14253 ctx->fmtpos++;
14254 }
14255 }
14256 else if (arg->ch >= '0' && arg->ch <= '9') {
14257 arg->width = arg->ch - '0';
14258 while (--ctx->fmtcnt >= 0) {
14259 arg->ch = FORMAT_READ(ctx);
14260 ctx->fmtpos++;
14261 if (arg->ch < '0' || arg->ch > '9')
14262 break;
14263 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14264 mixing signed and unsigned comparison. Since arg->ch is between
14265 '0' and '9', casting to int is safe. */
14266 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14267 PyErr_SetString(PyExc_ValueError,
14268 "width too big");
14269 return -1;
14270 }
14271 arg->width = arg->width*10 + (arg->ch - '0');
14272 }
14273 }
14274
14275 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014276 if (arg->ch == '.') {
14277 arg->prec = 0;
14278 if (--ctx->fmtcnt >= 0) {
14279 arg->ch = FORMAT_READ(ctx);
14280 ctx->fmtpos++;
14281 }
14282 if (arg->ch == '*') {
14283 v = unicode_format_getnextarg(ctx);
14284 if (v == NULL)
14285 return -1;
14286 if (!PyLong_Check(v)) {
14287 PyErr_SetString(PyExc_TypeError,
14288 "* wants int");
14289 return -1;
14290 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014291 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014292 if (arg->prec == -1 && PyErr_Occurred())
14293 return -1;
14294 if (arg->prec < 0)
14295 arg->prec = 0;
14296 if (--ctx->fmtcnt >= 0) {
14297 arg->ch = FORMAT_READ(ctx);
14298 ctx->fmtpos++;
14299 }
14300 }
14301 else if (arg->ch >= '0' && arg->ch <= '9') {
14302 arg->prec = arg->ch - '0';
14303 while (--ctx->fmtcnt >= 0) {
14304 arg->ch = FORMAT_READ(ctx);
14305 ctx->fmtpos++;
14306 if (arg->ch < '0' || arg->ch > '9')
14307 break;
14308 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14309 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014310 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014311 return -1;
14312 }
14313 arg->prec = arg->prec*10 + (arg->ch - '0');
14314 }
14315 }
14316 }
14317
14318 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14319 if (ctx->fmtcnt >= 0) {
14320 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14321 if (--ctx->fmtcnt >= 0) {
14322 arg->ch = FORMAT_READ(ctx);
14323 ctx->fmtpos++;
14324 }
14325 }
14326 }
14327 if (ctx->fmtcnt < 0) {
14328 PyErr_SetString(PyExc_ValueError,
14329 "incomplete format");
14330 return -1;
14331 }
14332 return 0;
14333
14334#undef FORMAT_READ
14335}
14336
14337/* Format one argument. Supported conversion specifiers:
14338
14339 - "s", "r", "a": any type
14340 - "i", "d", "u", "o", "x", "X": int
14341 - "e", "E", "f", "F", "g", "G": float
14342 - "c": int or str (1 character)
14343
Victor Stinner8dbd4212012-12-04 09:30:24 +010014344 When possible, the output is written directly into the Unicode writer
14345 (ctx->writer). A string is created when padding is required.
14346
Victor Stinnera47082312012-10-04 02:19:54 +020014347 Return 0 if the argument has been formatted into *p_str,
14348 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014349 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014350static int
14351unicode_format_arg_format(struct unicode_formatter_t *ctx,
14352 struct unicode_format_arg_t *arg,
14353 PyObject **p_str)
14354{
14355 PyObject *v;
14356 _PyUnicodeWriter *writer = &ctx->writer;
14357
14358 if (ctx->fmtcnt == 0)
14359 ctx->writer.overallocate = 0;
14360
14361 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014362 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014363 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014364 return 1;
14365 }
14366
14367 v = unicode_format_getnextarg(ctx);
14368 if (v == NULL)
14369 return -1;
14370
Victor Stinnera47082312012-10-04 02:19:54 +020014371
14372 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014373 case 's':
14374 case 'r':
14375 case 'a':
14376 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14377 /* Fast path */
14378 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14379 return -1;
14380 return 1;
14381 }
14382
14383 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14384 *p_str = v;
14385 Py_INCREF(*p_str);
14386 }
14387 else {
14388 if (arg->ch == 's')
14389 *p_str = PyObject_Str(v);
14390 else if (arg->ch == 'r')
14391 *p_str = PyObject_Repr(v);
14392 else
14393 *p_str = PyObject_ASCII(v);
14394 }
14395 break;
14396
14397 case 'i':
14398 case 'd':
14399 case 'u':
14400 case 'o':
14401 case 'x':
14402 case 'X':
14403 {
14404 int ret = mainformatlong(v, arg, p_str, writer);
14405 if (ret != 0)
14406 return ret;
14407 arg->sign = 1;
14408 break;
14409 }
14410
14411 case 'e':
14412 case 'E':
14413 case 'f':
14414 case 'F':
14415 case 'g':
14416 case 'G':
14417 if (arg->width == -1 && arg->prec == -1
14418 && !(arg->flags & (F_SIGN | F_BLANK)))
14419 {
14420 /* Fast path */
14421 if (formatfloat(v, arg, NULL, writer) == -1)
14422 return -1;
14423 return 1;
14424 }
14425
14426 arg->sign = 1;
14427 if (formatfloat(v, arg, p_str, NULL) == -1)
14428 return -1;
14429 break;
14430
14431 case 'c':
14432 {
14433 Py_UCS4 ch = formatchar(v);
14434 if (ch == (Py_UCS4) -1)
14435 return -1;
14436 if (arg->width == -1 && arg->prec == -1) {
14437 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014438 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014439 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014440 return 1;
14441 }
14442 *p_str = PyUnicode_FromOrdinal(ch);
14443 break;
14444 }
14445
14446 default:
14447 PyErr_Format(PyExc_ValueError,
14448 "unsupported format character '%c' (0x%x) "
14449 "at index %zd",
14450 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14451 (int)arg->ch,
14452 ctx->fmtpos - 1);
14453 return -1;
14454 }
14455 if (*p_str == NULL)
14456 return -1;
14457 assert (PyUnicode_Check(*p_str));
14458 return 0;
14459}
14460
14461static int
14462unicode_format_arg_output(struct unicode_formatter_t *ctx,
14463 struct unicode_format_arg_t *arg,
14464 PyObject *str)
14465{
14466 Py_ssize_t len;
14467 enum PyUnicode_Kind kind;
14468 void *pbuf;
14469 Py_ssize_t pindex;
14470 Py_UCS4 signchar;
14471 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014472 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014473 Py_ssize_t sublen;
14474 _PyUnicodeWriter *writer = &ctx->writer;
14475 Py_UCS4 fill;
14476
14477 fill = ' ';
14478 if (arg->sign && arg->flags & F_ZERO)
14479 fill = '0';
14480
14481 if (PyUnicode_READY(str) == -1)
14482 return -1;
14483
14484 len = PyUnicode_GET_LENGTH(str);
14485 if ((arg->width == -1 || arg->width <= len)
14486 && (arg->prec == -1 || arg->prec >= len)
14487 && !(arg->flags & (F_SIGN | F_BLANK)))
14488 {
14489 /* Fast path */
14490 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14491 return -1;
14492 return 0;
14493 }
14494
14495 /* Truncate the string for "s", "r" and "a" formats
14496 if the precision is set */
14497 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14498 if (arg->prec >= 0 && len > arg->prec)
14499 len = arg->prec;
14500 }
14501
14502 /* Adjust sign and width */
14503 kind = PyUnicode_KIND(str);
14504 pbuf = PyUnicode_DATA(str);
14505 pindex = 0;
14506 signchar = '\0';
14507 if (arg->sign) {
14508 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14509 if (ch == '-' || ch == '+') {
14510 signchar = ch;
14511 len--;
14512 pindex++;
14513 }
14514 else if (arg->flags & F_SIGN)
14515 signchar = '+';
14516 else if (arg->flags & F_BLANK)
14517 signchar = ' ';
14518 else
14519 arg->sign = 0;
14520 }
14521 if (arg->width < len)
14522 arg->width = len;
14523
14524 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014525 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014526 if (!(arg->flags & F_LJUST)) {
14527 if (arg->sign) {
14528 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014529 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014530 }
14531 else {
14532 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014533 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014534 }
14535 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014536 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14537 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014538 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014539 }
14540
Victor Stinnera47082312012-10-04 02:19:54 +020014541 buflen = arg->width;
14542 if (arg->sign && len == arg->width)
14543 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014544 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014545 return -1;
14546
14547 /* Write the sign if needed */
14548 if (arg->sign) {
14549 if (fill != ' ') {
14550 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14551 writer->pos += 1;
14552 }
14553 if (arg->width > len)
14554 arg->width--;
14555 }
14556
14557 /* Write the numeric prefix for "x", "X" and "o" formats
14558 if the alternate form is used.
14559 For example, write "0x" for the "%#x" format. */
14560 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14561 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14562 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14563 if (fill != ' ') {
14564 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14565 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14566 writer->pos += 2;
14567 pindex += 2;
14568 }
14569 arg->width -= 2;
14570 if (arg->width < 0)
14571 arg->width = 0;
14572 len -= 2;
14573 }
14574
14575 /* Pad left with the fill character if needed */
14576 if (arg->width > len && !(arg->flags & F_LJUST)) {
14577 sublen = arg->width - len;
14578 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14579 writer->pos += sublen;
14580 arg->width = len;
14581 }
14582
14583 /* If padding with spaces: write sign if needed and/or numeric prefix if
14584 the alternate form is used */
14585 if (fill == ' ') {
14586 if (arg->sign) {
14587 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14588 writer->pos += 1;
14589 }
14590 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14591 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14592 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14593 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14594 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14595 writer->pos += 2;
14596 pindex += 2;
14597 }
14598 }
14599
14600 /* Write characters */
14601 if (len) {
14602 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14603 str, pindex, len);
14604 writer->pos += len;
14605 }
14606
14607 /* Pad right with the fill character if needed */
14608 if (arg->width > len) {
14609 sublen = arg->width - len;
14610 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14611 writer->pos += sublen;
14612 }
14613 return 0;
14614}
14615
14616/* Helper of PyUnicode_Format(): format one arg.
14617 Return 0 on success, raise an exception and return -1 on error. */
14618static int
14619unicode_format_arg(struct unicode_formatter_t *ctx)
14620{
14621 struct unicode_format_arg_t arg;
14622 PyObject *str;
14623 int ret;
14624
Victor Stinner8dbd4212012-12-04 09:30:24 +010014625 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14626 arg.flags = 0;
14627 arg.width = -1;
14628 arg.prec = -1;
14629 arg.sign = 0;
14630 str = NULL;
14631
Victor Stinnera47082312012-10-04 02:19:54 +020014632 ret = unicode_format_arg_parse(ctx, &arg);
14633 if (ret == -1)
14634 return -1;
14635
14636 ret = unicode_format_arg_format(ctx, &arg, &str);
14637 if (ret == -1)
14638 return -1;
14639
14640 if (ret != 1) {
14641 ret = unicode_format_arg_output(ctx, &arg, str);
14642 Py_DECREF(str);
14643 if (ret == -1)
14644 return -1;
14645 }
14646
14647 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14648 PyErr_SetString(PyExc_TypeError,
14649 "not all arguments converted during string formatting");
14650 return -1;
14651 }
14652 return 0;
14653}
14654
Alexander Belopolsky40018472011-02-26 01:02:56 +000014655PyObject *
14656PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014657{
Victor Stinnera47082312012-10-04 02:19:54 +020014658 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014659
Guido van Rossumd57fd912000-03-10 22:53:23 +000014660 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014661 PyErr_BadInternalCall();
14662 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014663 }
Victor Stinnera47082312012-10-04 02:19:54 +020014664
14665 ctx.fmtstr = PyUnicode_FromObject(format);
14666 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014667 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014668 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14669 Py_DECREF(ctx.fmtstr);
14670 return NULL;
14671 }
14672 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14673 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14674 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14675 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014676
Victor Stinner8f674cc2013-04-17 23:02:17 +020014677 _PyUnicodeWriter_Init(&ctx.writer);
14678 ctx.writer.min_length = ctx.fmtcnt + 100;
14679 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014680
Guido van Rossumd57fd912000-03-10 22:53:23 +000014681 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014682 ctx.arglen = PyTuple_Size(args);
14683 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014684 }
14685 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014686 ctx.arglen = -1;
14687 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014688 }
Victor Stinnera47082312012-10-04 02:19:54 +020014689 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014690 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014691 ctx.dict = args;
14692 else
14693 ctx.dict = NULL;
14694 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014695
Victor Stinnera47082312012-10-04 02:19:54 +020014696 while (--ctx.fmtcnt >= 0) {
14697 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014698 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014699
14700 nonfmtpos = ctx.fmtpos++;
14701 while (ctx.fmtcnt >= 0 &&
14702 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14703 ctx.fmtpos++;
14704 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014705 }
Victor Stinnera47082312012-10-04 02:19:54 +020014706 if (ctx.fmtcnt < 0) {
14707 ctx.fmtpos--;
14708 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014709 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014710
Victor Stinnercfc4c132013-04-03 01:48:39 +020014711 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14712 nonfmtpos, ctx.fmtpos) < 0)
14713 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014714 }
14715 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014716 ctx.fmtpos++;
14717 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014718 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014719 }
14720 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014721
Victor Stinnera47082312012-10-04 02:19:54 +020014722 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014723 PyErr_SetString(PyExc_TypeError,
14724 "not all arguments converted during string formatting");
14725 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014726 }
14727
Victor Stinnera47082312012-10-04 02:19:54 +020014728 if (ctx.args_owned) {
14729 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014730 }
Victor Stinnera47082312012-10-04 02:19:54 +020014731 Py_DECREF(ctx.fmtstr);
14732 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014733
Benjamin Peterson29060642009-01-31 22:14:21 +000014734 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014735 Py_DECREF(ctx.fmtstr);
14736 _PyUnicodeWriter_Dealloc(&ctx.writer);
14737 if (ctx.args_owned) {
14738 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014739 }
14740 return NULL;
14741}
14742
Jeremy Hylton938ace62002-07-17 16:30:39 +000014743static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014744unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14745
Tim Peters6d6c1a32001-08-02 04:15:00 +000014746static PyObject *
14747unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14748{
Benjamin Peterson29060642009-01-31 22:14:21 +000014749 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014750 static char *kwlist[] = {"object", "encoding", "errors", 0};
14751 char *encoding = NULL;
14752 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014753
Benjamin Peterson14339b62009-01-31 16:36:08 +000014754 if (type != &PyUnicode_Type)
14755 return unicode_subtype_new(type, args, kwds);
14756 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014757 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014758 return NULL;
14759 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014760 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014761 if (encoding == NULL && errors == NULL)
14762 return PyObject_Str(x);
14763 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014764 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014765}
14766
Guido van Rossume023fe02001-08-30 03:12:59 +000014767static PyObject *
14768unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14769{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014770 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014771 Py_ssize_t length, char_size;
14772 int share_wstr, share_utf8;
14773 unsigned int kind;
14774 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014775
Benjamin Peterson14339b62009-01-31 16:36:08 +000014776 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014777
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014778 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014779 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014780 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014781 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014782 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014783 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014784 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014785 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014786
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014787 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014788 if (self == NULL) {
14789 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014790 return NULL;
14791 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014792 kind = PyUnicode_KIND(unicode);
14793 length = PyUnicode_GET_LENGTH(unicode);
14794
14795 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014796#ifdef Py_DEBUG
14797 _PyUnicode_HASH(self) = -1;
14798#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014799 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014800#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014801 _PyUnicode_STATE(self).interned = 0;
14802 _PyUnicode_STATE(self).kind = kind;
14803 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014804 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014805 _PyUnicode_STATE(self).ready = 1;
14806 _PyUnicode_WSTR(self) = NULL;
14807 _PyUnicode_UTF8_LENGTH(self) = 0;
14808 _PyUnicode_UTF8(self) = NULL;
14809 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014810 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014811
14812 share_utf8 = 0;
14813 share_wstr = 0;
14814 if (kind == PyUnicode_1BYTE_KIND) {
14815 char_size = 1;
14816 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14817 share_utf8 = 1;
14818 }
14819 else if (kind == PyUnicode_2BYTE_KIND) {
14820 char_size = 2;
14821 if (sizeof(wchar_t) == 2)
14822 share_wstr = 1;
14823 }
14824 else {
14825 assert(kind == PyUnicode_4BYTE_KIND);
14826 char_size = 4;
14827 if (sizeof(wchar_t) == 4)
14828 share_wstr = 1;
14829 }
14830
14831 /* Ensure we won't overflow the length. */
14832 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14833 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014834 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014835 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014836 data = PyObject_MALLOC((length + 1) * char_size);
14837 if (data == NULL) {
14838 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014839 goto onError;
14840 }
14841
Victor Stinnerc3c74152011-10-02 20:39:55 +020014842 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014843 if (share_utf8) {
14844 _PyUnicode_UTF8_LENGTH(self) = length;
14845 _PyUnicode_UTF8(self) = data;
14846 }
14847 if (share_wstr) {
14848 _PyUnicode_WSTR_LENGTH(self) = length;
14849 _PyUnicode_WSTR(self) = (wchar_t *)data;
14850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014851
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014852 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014853 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014854 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014855#ifdef Py_DEBUG
14856 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14857#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014858 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014859 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014860
14861onError:
14862 Py_DECREF(unicode);
14863 Py_DECREF(self);
14864 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014865}
14866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014867PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014868"str(object='') -> str\n\
14869str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014870\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014871Create a new string object from the given object. If encoding or\n\
14872errors is specified, then the object must expose a data buffer\n\
14873that will be decoded using the given encoding and error handler.\n\
14874Otherwise, returns the result of object.__str__() (if defined)\n\
14875or repr(object).\n\
14876encoding defaults to sys.getdefaultencoding().\n\
14877errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014878
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014879static PyObject *unicode_iter(PyObject *seq);
14880
Guido van Rossumd57fd912000-03-10 22:53:23 +000014881PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014882 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014883 "str", /* tp_name */
14884 sizeof(PyUnicodeObject), /* tp_size */
14885 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014886 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014887 (destructor)unicode_dealloc, /* tp_dealloc */
14888 0, /* tp_print */
14889 0, /* tp_getattr */
14890 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014891 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014892 unicode_repr, /* tp_repr */
14893 &unicode_as_number, /* tp_as_number */
14894 &unicode_as_sequence, /* tp_as_sequence */
14895 &unicode_as_mapping, /* tp_as_mapping */
14896 (hashfunc) unicode_hash, /* tp_hash*/
14897 0, /* tp_call*/
14898 (reprfunc) unicode_str, /* tp_str */
14899 PyObject_GenericGetAttr, /* tp_getattro */
14900 0, /* tp_setattro */
14901 0, /* tp_as_buffer */
14902 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014903 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014904 unicode_doc, /* tp_doc */
14905 0, /* tp_traverse */
14906 0, /* tp_clear */
14907 PyUnicode_RichCompare, /* tp_richcompare */
14908 0, /* tp_weaklistoffset */
14909 unicode_iter, /* tp_iter */
14910 0, /* tp_iternext */
14911 unicode_methods, /* tp_methods */
14912 0, /* tp_members */
14913 0, /* tp_getset */
14914 &PyBaseObject_Type, /* tp_base */
14915 0, /* tp_dict */
14916 0, /* tp_descr_get */
14917 0, /* tp_descr_set */
14918 0, /* tp_dictoffset */
14919 0, /* tp_init */
14920 0, /* tp_alloc */
14921 unicode_new, /* tp_new */
14922 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014923};
14924
14925/* Initialize the Unicode implementation */
14926
Victor Stinner3a50e702011-10-18 21:21:00 +020014927int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014928{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014929 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014930 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014931 0x000A, /* LINE FEED */
14932 0x000D, /* CARRIAGE RETURN */
14933 0x001C, /* FILE SEPARATOR */
14934 0x001D, /* GROUP SEPARATOR */
14935 0x001E, /* RECORD SEPARATOR */
14936 0x0085, /* NEXT LINE */
14937 0x2028, /* LINE SEPARATOR */
14938 0x2029, /* PARAGRAPH SEPARATOR */
14939 };
14940
Fred Drakee4315f52000-05-09 19:53:39 +000014941 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014942 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014943 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014944 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014945 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014946
Guido van Rossumcacfc072002-05-24 19:01:59 +000014947 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014948 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014949
14950 /* initialize the linebreak bloom filter */
14951 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014952 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014953 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014954
Christian Heimes26532f72013-07-20 14:57:16 +020014955 if (PyType_Ready(&EncodingMapType) < 0)
14956 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014957
Benjamin Petersonc4311282012-10-30 23:21:10 -040014958 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14959 Py_FatalError("Can't initialize field name iterator type");
14960
14961 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14962 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014963
Victor Stinner3a50e702011-10-18 21:21:00 +020014964#ifdef HAVE_MBCS
14965 winver.dwOSVersionInfoSize = sizeof(winver);
14966 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14967 PyErr_SetFromWindowsErr(0);
14968 return -1;
14969 }
14970#endif
14971 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014972}
14973
14974/* Finalize the Unicode implementation */
14975
Christian Heimesa156e092008-02-16 07:38:31 +000014976int
14977PyUnicode_ClearFreeList(void)
14978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014979 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014980}
14981
Guido van Rossumd57fd912000-03-10 22:53:23 +000014982void
Thomas Wouters78890102000-07-22 19:25:51 +000014983_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014984{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014985 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014986
Serhiy Storchaka05997252013-01-26 12:14:02 +020014987 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014988
Serhiy Storchaka05997252013-01-26 12:14:02 +020014989 for (i = 0; i < 256; i++)
14990 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014991 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014992 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014993}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014994
Walter Dörwald16807132007-05-25 13:52:07 +000014995void
14996PyUnicode_InternInPlace(PyObject **p)
14997{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014998 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014999 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015000#ifdef Py_DEBUG
15001 assert(s != NULL);
15002 assert(_PyUnicode_CHECK(s));
15003#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015004 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015005 return;
15006#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015007 /* If it's a subclass, we don't really know what putting
15008 it in the interned dict might do. */
15009 if (!PyUnicode_CheckExact(s))
15010 return;
15011 if (PyUnicode_CHECK_INTERNED(s))
15012 return;
15013 if (interned == NULL) {
15014 interned = PyDict_New();
15015 if (interned == NULL) {
15016 PyErr_Clear(); /* Don't leave an exception */
15017 return;
15018 }
15019 }
15020 /* It might be that the GetItem call fails even
15021 though the key is present in the dictionary,
15022 namely when this happens during a stack overflow. */
15023 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015024 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015025 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015026
Victor Stinnerf0335102013-04-14 19:13:03 +020015027 if (t) {
15028 Py_INCREF(t);
15029 Py_DECREF(*p);
15030 *p = t;
15031 return;
15032 }
Walter Dörwald16807132007-05-25 13:52:07 +000015033
Benjamin Peterson14339b62009-01-31 16:36:08 +000015034 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015035 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 PyErr_Clear();
15037 PyThreadState_GET()->recursion_critical = 0;
15038 return;
15039 }
15040 PyThreadState_GET()->recursion_critical = 0;
15041 /* The two references in interned are not counted by refcnt.
15042 The deallocator will take care of this */
15043 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015044 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015045}
15046
15047void
15048PyUnicode_InternImmortal(PyObject **p)
15049{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015050 PyUnicode_InternInPlace(p);
15051 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015052 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015053 Py_INCREF(*p);
15054 }
Walter Dörwald16807132007-05-25 13:52:07 +000015055}
15056
15057PyObject *
15058PyUnicode_InternFromString(const char *cp)
15059{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015060 PyObject *s = PyUnicode_FromString(cp);
15061 if (s == NULL)
15062 return NULL;
15063 PyUnicode_InternInPlace(&s);
15064 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015065}
15066
Alexander Belopolsky40018472011-02-26 01:02:56 +000015067void
15068_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015069{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015070 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015071 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015072 Py_ssize_t i, n;
15073 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015074
Benjamin Peterson14339b62009-01-31 16:36:08 +000015075 if (interned == NULL || !PyDict_Check(interned))
15076 return;
15077 keys = PyDict_Keys(interned);
15078 if (keys == NULL || !PyList_Check(keys)) {
15079 PyErr_Clear();
15080 return;
15081 }
Walter Dörwald16807132007-05-25 13:52:07 +000015082
Benjamin Peterson14339b62009-01-31 16:36:08 +000015083 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15084 detector, interned unicode strings are not forcibly deallocated;
15085 rather, we give them their stolen references back, and then clear
15086 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015087
Benjamin Peterson14339b62009-01-31 16:36:08 +000015088 n = PyList_GET_SIZE(keys);
15089 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015090 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015091 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015092 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015093 if (PyUnicode_READY(s) == -1) {
15094 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015095 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015096 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015097 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015098 case SSTATE_NOT_INTERNED:
15099 /* XXX Shouldn't happen */
15100 break;
15101 case SSTATE_INTERNED_IMMORTAL:
15102 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015103 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015104 break;
15105 case SSTATE_INTERNED_MORTAL:
15106 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015107 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015108 break;
15109 default:
15110 Py_FatalError("Inconsistent interned string state.");
15111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015112 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015113 }
15114 fprintf(stderr, "total size of all interned strings: "
15115 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15116 "mortal/immortal\n", mortal_size, immortal_size);
15117 Py_DECREF(keys);
15118 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015119 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015120}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015121
15122
15123/********************* Unicode Iterator **************************/
15124
15125typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015126 PyObject_HEAD
15127 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015128 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015129} unicodeiterobject;
15130
15131static void
15132unicodeiter_dealloc(unicodeiterobject *it)
15133{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015134 _PyObject_GC_UNTRACK(it);
15135 Py_XDECREF(it->it_seq);
15136 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015137}
15138
15139static int
15140unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15141{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015142 Py_VISIT(it->it_seq);
15143 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015144}
15145
15146static PyObject *
15147unicodeiter_next(unicodeiterobject *it)
15148{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015149 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015150
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 assert(it != NULL);
15152 seq = it->it_seq;
15153 if (seq == NULL)
15154 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015155 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015157 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15158 int kind = PyUnicode_KIND(seq);
15159 void *data = PyUnicode_DATA(seq);
15160 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15161 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015162 if (item != NULL)
15163 ++it->it_index;
15164 return item;
15165 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015166
Benjamin Peterson14339b62009-01-31 16:36:08 +000015167 Py_DECREF(seq);
15168 it->it_seq = NULL;
15169 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015170}
15171
15172static PyObject *
15173unicodeiter_len(unicodeiterobject *it)
15174{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015175 Py_ssize_t len = 0;
15176 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015177 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015179}
15180
15181PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15182
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015183static PyObject *
15184unicodeiter_reduce(unicodeiterobject *it)
15185{
15186 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015187 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015188 it->it_seq, it->it_index);
15189 } else {
15190 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15191 if (u == NULL)
15192 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015193 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015194 }
15195}
15196
15197PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15198
15199static PyObject *
15200unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15201{
15202 Py_ssize_t index = PyLong_AsSsize_t(state);
15203 if (index == -1 && PyErr_Occurred())
15204 return NULL;
15205 if (index < 0)
15206 index = 0;
15207 it->it_index = index;
15208 Py_RETURN_NONE;
15209}
15210
15211PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15212
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015213static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015214 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015215 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015216 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15217 reduce_doc},
15218 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15219 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015220 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015221};
15222
15223PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015224 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15225 "str_iterator", /* tp_name */
15226 sizeof(unicodeiterobject), /* tp_basicsize */
15227 0, /* tp_itemsize */
15228 /* methods */
15229 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15230 0, /* tp_print */
15231 0, /* tp_getattr */
15232 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015233 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015234 0, /* tp_repr */
15235 0, /* tp_as_number */
15236 0, /* tp_as_sequence */
15237 0, /* tp_as_mapping */
15238 0, /* tp_hash */
15239 0, /* tp_call */
15240 0, /* tp_str */
15241 PyObject_GenericGetAttr, /* tp_getattro */
15242 0, /* tp_setattro */
15243 0, /* tp_as_buffer */
15244 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15245 0, /* tp_doc */
15246 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15247 0, /* tp_clear */
15248 0, /* tp_richcompare */
15249 0, /* tp_weaklistoffset */
15250 PyObject_SelfIter, /* tp_iter */
15251 (iternextfunc)unicodeiter_next, /* tp_iternext */
15252 unicodeiter_methods, /* tp_methods */
15253 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015254};
15255
15256static PyObject *
15257unicode_iter(PyObject *seq)
15258{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015260
Benjamin Peterson14339b62009-01-31 16:36:08 +000015261 if (!PyUnicode_Check(seq)) {
15262 PyErr_BadInternalCall();
15263 return NULL;
15264 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015265 if (PyUnicode_READY(seq) == -1)
15266 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015267 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15268 if (it == NULL)
15269 return NULL;
15270 it->it_index = 0;
15271 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015272 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 _PyObject_GC_TRACK(it);
15274 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015275}
15276
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015277
15278size_t
15279Py_UNICODE_strlen(const Py_UNICODE *u)
15280{
15281 int res = 0;
15282 while(*u++)
15283 res++;
15284 return res;
15285}
15286
15287Py_UNICODE*
15288Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15289{
15290 Py_UNICODE *u = s1;
15291 while ((*u++ = *s2++));
15292 return s1;
15293}
15294
15295Py_UNICODE*
15296Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15297{
15298 Py_UNICODE *u = s1;
15299 while ((*u++ = *s2++))
15300 if (n-- == 0)
15301 break;
15302 return s1;
15303}
15304
15305Py_UNICODE*
15306Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15307{
15308 Py_UNICODE *u1 = s1;
15309 u1 += Py_UNICODE_strlen(u1);
15310 Py_UNICODE_strcpy(u1, s2);
15311 return s1;
15312}
15313
15314int
15315Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15316{
15317 while (*s1 && *s2 && *s1 == *s2)
15318 s1++, s2++;
15319 if (*s1 && *s2)
15320 return (*s1 < *s2) ? -1 : +1;
15321 if (*s1)
15322 return 1;
15323 if (*s2)
15324 return -1;
15325 return 0;
15326}
15327
15328int
15329Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15330{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015331 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015332 for (; n != 0; n--) {
15333 u1 = *s1;
15334 u2 = *s2;
15335 if (u1 != u2)
15336 return (u1 < u2) ? -1 : +1;
15337 if (u1 == '\0')
15338 return 0;
15339 s1++;
15340 s2++;
15341 }
15342 return 0;
15343}
15344
15345Py_UNICODE*
15346Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15347{
15348 const Py_UNICODE *p;
15349 for (p = s; *p; p++)
15350 if (*p == c)
15351 return (Py_UNICODE*)p;
15352 return NULL;
15353}
15354
15355Py_UNICODE*
15356Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15357{
15358 const Py_UNICODE *p;
15359 p = s + Py_UNICODE_strlen(s);
15360 while (p != s) {
15361 p--;
15362 if (*p == c)
15363 return (Py_UNICODE*)p;
15364 }
15365 return NULL;
15366}
Victor Stinner331ea922010-08-10 16:37:20 +000015367
Victor Stinner71133ff2010-09-01 23:43:53 +000015368Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015369PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015370{
Victor Stinner577db2c2011-10-11 22:12:48 +020015371 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015372 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015373
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015374 if (!PyUnicode_Check(unicode)) {
15375 PyErr_BadArgument();
15376 return NULL;
15377 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015378 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015379 if (u == NULL)
15380 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015381 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015382 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015383 PyErr_NoMemory();
15384 return NULL;
15385 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015386 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015387 size *= sizeof(Py_UNICODE);
15388 copy = PyMem_Malloc(size);
15389 if (copy == NULL) {
15390 PyErr_NoMemory();
15391 return NULL;
15392 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015393 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015394 return copy;
15395}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015396
Georg Brandl66c221e2010-10-14 07:04:07 +000015397/* A _string module, to export formatter_parser and formatter_field_name_split
15398 to the string.Formatter class implemented in Python. */
15399
15400static PyMethodDef _string_methods[] = {
15401 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15402 METH_O, PyDoc_STR("split the argument as a field name")},
15403 {"formatter_parser", (PyCFunction) formatter_parser,
15404 METH_O, PyDoc_STR("parse the argument as a format string")},
15405 {NULL, NULL}
15406};
15407
15408static struct PyModuleDef _string_module = {
15409 PyModuleDef_HEAD_INIT,
15410 "_string",
15411 PyDoc_STR("string helper module"),
15412 0,
15413 _string_methods,
15414 NULL,
15415 NULL,
15416 NULL,
15417 NULL
15418};
15419
15420PyMODINIT_FUNC
15421PyInit__string(void)
15422{
15423 return PyModule_Create(&_string_module);
15424}
15425
15426
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015427#ifdef __cplusplus
15428}
15429#endif