blob: 4c532afc3e9403733c7ab1873e2cb0dd9d4f0b63 [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 Stinnere6abb482012-05-02 01:15:40 +0200107/* Optimized version of Py_MAX() to compute the maximum character:
108 use it when your are computing the second argument of PyUnicode_New() */
109#define MAX_MAXCHAR(maxchar1, maxchar2) \
110 ((maxchar1) | (maxchar2))
111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
130 (assert(_PyUnicode_CHECK(op)), \
131 (!PyUnicode_IS_COMPACT_ASCII(op) \
132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
138 (assert(_PyUnicode_CHECK(op)), \
139 (_PyUnicode_WSTR(op) && \
140 (!PyUnicode_IS_READY(op) || \
141 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
142
Victor Stinner910337b2011-10-03 03:20:16 +0200143/* Generic helper macro to convert characters of different types.
144 from_type and to_type have to be valid type names, begin and end
145 are pointers to the source characters which should be of type
146 "from_type *". to is a pointer of type "to_type *" and points to the
147 buffer where the result characters are written to. */
148#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
149 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200150 to_type *_to = (to_type *) to; \
151 const from_type *_iter = (begin); \
152 const from_type *_end = (end); \
153 Py_ssize_t n = (_end) - (_iter); \
154 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200155 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200156 while (_iter < (_unrolled_end)) { \
157 _to[0] = (to_type) _iter[0]; \
158 _to[1] = (to_type) _iter[1]; \
159 _to[2] = (to_type) _iter[2]; \
160 _to[3] = (to_type) _iter[3]; \
161 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200162 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200163 while (_iter < (_end)) \
164 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200165 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200166
Walter Dörwald16807132007-05-25 13:52:07 +0000167/* This dictionary holds all interned unicode strings. Note that references
168 to strings in this dictionary are *not* counted in the string's ob_refcnt.
169 When the interned string reaches a refcnt of 0 the string deallocation
170 function will delete the reference from this dictionary.
171
172 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000173 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000174*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200175static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000176
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000177/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179
Serhiy Storchaka678db842013-01-26 12:16:36 +0200180#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200181 do { \
182 if (unicode_empty != NULL) \
183 Py_INCREF(unicode_empty); \
184 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185 unicode_empty = PyUnicode_New(0, 0); \
186 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200187 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200188 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
189 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200190 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200191 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000192
Serhiy Storchaka678db842013-01-26 12:16:36 +0200193#define _Py_RETURN_UNICODE_EMPTY() \
194 do { \
195 _Py_INCREF_UNICODE_EMPTY(); \
196 return unicode_empty; \
197 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000198
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200199/* Forward declaration */
200Py_LOCAL_INLINE(int)
201_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
202
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200204static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200205
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000206/* Single character Unicode strings in the Latin-1 range are being
207 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200208static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000209
Christian Heimes190d79e2008-01-30 11:58:22 +0000210/* Fast detection of the most frequent whitespace characters */
211const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000212 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000215/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000216/* case 0x000C: * FORM FEED */
217/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 1, 1, 1, 1, 1, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000220/* case 0x001C: * FILE SEPARATOR */
221/* case 0x001D: * GROUP SEPARATOR */
222/* case 0x001E: * RECORD SEPARATOR */
223/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000225/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000226 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000230
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
237 0, 0, 0, 0, 0, 0, 0, 0,
238 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000239};
240
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200242static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200243static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100244static int unicode_modifiable(PyObject *unicode);
245
Victor Stinnerfe226c02011-10-03 03:52:20 +0200246
Alexander Belopolsky40018472011-02-26 01:02:56 +0000247static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100248_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200249static PyObject *
250_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
251static PyObject *
252_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
253
254static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000255unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100257 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000258 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
259
Alexander Belopolsky40018472011-02-26 01:02:56 +0000260static void
261raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300262 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100263 PyObject *unicode,
264 Py_ssize_t startpos, Py_ssize_t endpos,
265 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000266
Christian Heimes190d79e2008-01-30 11:58:22 +0000267/* Same for linebreaks */
268static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000271/* 0x000B, * LINE TABULATION */
272/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000273/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000274 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000276/* 0x001C, * FILE SEPARATOR */
277/* 0x001D, * GROUP SEPARATOR */
278/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 1, 1, 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000284
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
292 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000293};
294
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300295/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
296 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000298PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000299{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000300#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000303 /* This is actually an illegal character, so it should
304 not be passed to unichr. */
305 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000306#endif
307}
308
Victor Stinner910337b2011-10-03 03:20:16 +0200309#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200310int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100311_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200312{
313 PyASCIIObject *ascii;
314 unsigned int kind;
315
316 assert(PyUnicode_Check(op));
317
318 ascii = (PyASCIIObject *)op;
319 kind = ascii->state.kind;
320
Victor Stinnera3b334d2011-10-03 13:53:37 +0200321 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200322 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(ascii->state.ready == 1);
324 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200325 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200326 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200327 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200328
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 if (ascii->state.compact == 1) {
330 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(kind == PyUnicode_1BYTE_KIND
332 || kind == PyUnicode_2BYTE_KIND
333 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200335 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 }
338 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
340
341 data = unicode->data.any;
342 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100343 assert(ascii->length == 0);
344 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200345 assert(ascii->state.compact == 0);
346 assert(ascii->state.ascii == 0);
347 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100348 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200349 assert(ascii->wstr != NULL);
350 assert(data == NULL);
351 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200352 }
353 else {
354 assert(kind == PyUnicode_1BYTE_KIND
355 || kind == PyUnicode_2BYTE_KIND
356 || kind == PyUnicode_4BYTE_KIND);
357 assert(ascii->state.compact == 0);
358 assert(ascii->state.ready == 1);
359 assert(data != NULL);
360 if (ascii->state.ascii) {
361 assert (compact->utf8 == data);
362 assert (compact->utf8_length == ascii->length);
363 }
364 else
365 assert (compact->utf8 != data);
366 }
367 }
368 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200369 if (
370#if SIZEOF_WCHAR_T == 2
371 kind == PyUnicode_2BYTE_KIND
372#else
373 kind == PyUnicode_4BYTE_KIND
374#endif
375 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200376 {
377 assert(ascii->wstr == data);
378 assert(compact->wstr_length == ascii->length);
379 } else
380 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200382
383 if (compact->utf8 == NULL)
384 assert(compact->utf8_length == 0);
385 if (ascii->wstr == NULL)
386 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200387 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200388 /* check that the best kind is used */
389 if (check_content && kind != PyUnicode_WCHAR_KIND)
390 {
391 Py_ssize_t i;
392 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200393 void *data;
394 Py_UCS4 ch;
395
396 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200397 for (i=0; i < ascii->length; i++)
398 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200399 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 if (ch > maxchar)
401 maxchar = ch;
402 }
403 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100404 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200405 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100406 assert(maxchar <= 255);
407 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200408 else
409 assert(maxchar < 128);
410 }
Victor Stinner77faf692011-11-20 18:56:05 +0100411 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200412 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100413 assert(maxchar <= 0xFFFF);
414 }
415 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200416 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100417 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100418 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200419 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200420 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400421 return 1;
422}
Victor Stinner910337b2011-10-03 03:20:16 +0200423#endif
424
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100425static PyObject*
426unicode_result_wchar(PyObject *unicode)
427{
428#ifndef Py_DEBUG
429 Py_ssize_t len;
430
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 len = _PyUnicode_WSTR_LENGTH(unicode);
432 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200434 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100435 }
436
437 if (len == 1) {
438 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100439 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100440 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
441 Py_DECREF(unicode);
442 return latin1_char;
443 }
444 }
445
446 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200447 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100448 return NULL;
449 }
450#else
Victor Stinneraa771272012-10-04 02:32:58 +0200451 assert(Py_REFCNT(unicode) == 1);
452
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100453 /* don't make the result ready in debug mode to ensure that the caller
454 makes the string ready before using it */
455 assert(_PyUnicode_CheckConsistency(unicode, 1));
456#endif
457 return unicode;
458}
459
460static PyObject*
461unicode_result_ready(PyObject *unicode)
462{
463 Py_ssize_t length;
464
465 length = PyUnicode_GET_LENGTH(unicode);
466 if (length == 0) {
467 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200469 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100470 }
471 return unicode_empty;
472 }
473
474 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200475 void *data = PyUnicode_DATA(unicode);
476 int kind = PyUnicode_KIND(unicode);
477 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100478 if (ch < 256) {
479 PyObject *latin1_char = unicode_latin1[ch];
480 if (latin1_char != NULL) {
481 if (unicode != latin1_char) {
482 Py_INCREF(latin1_char);
483 Py_DECREF(unicode);
484 }
485 return latin1_char;
486 }
487 else {
488 assert(_PyUnicode_CheckConsistency(unicode, 1));
489 Py_INCREF(unicode);
490 unicode_latin1[ch] = unicode;
491 return unicode;
492 }
493 }
494 }
495
496 assert(_PyUnicode_CheckConsistency(unicode, 1));
497 return unicode;
498}
499
500static PyObject*
501unicode_result(PyObject *unicode)
502{
503 assert(_PyUnicode_CHECK(unicode));
504 if (PyUnicode_IS_READY(unicode))
505 return unicode_result_ready(unicode);
506 else
507 return unicode_result_wchar(unicode);
508}
509
Victor Stinnerc4b49542011-12-11 22:44:26 +0100510static PyObject*
511unicode_result_unchanged(PyObject *unicode)
512{
513 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500514 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100515 return NULL;
516 Py_INCREF(unicode);
517 return unicode;
518 }
519 else
520 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100521 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100522}
523
Victor Stinner3a50e702011-10-18 21:21:00 +0200524#ifdef HAVE_MBCS
525static OSVERSIONINFOEX winver;
526#endif
527
Thomas Wouters477c8d52006-05-27 19:21:47 +0000528/* --- Bloom Filters ----------------------------------------------------- */
529
530/* stuff to implement simple "bloom filters" for Unicode characters.
531 to keep things simple, we use a single bitmask, using the least 5
532 bits from each unicode characters as the bit index. */
533
534/* the linebreak mask is set up by Unicode_Init below */
535
Antoine Pitrouf068f942010-01-13 14:19:12 +0000536#if LONG_BIT >= 128
537#define BLOOM_WIDTH 128
538#elif LONG_BIT >= 64
539#define BLOOM_WIDTH 64
540#elif LONG_BIT >= 32
541#define BLOOM_WIDTH 32
542#else
543#error "LONG_BIT is smaller than 32"
544#endif
545
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546#define BLOOM_MASK unsigned long
547
Serhiy Storchaka05997252013-01-26 12:14:02 +0200548static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Antoine Pitrouf068f942010-01-13 14:19:12 +0000550#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
Benjamin Peterson29060642009-01-31 22:14:21 +0000552#define BLOOM_LINEBREAK(ch) \
553 ((ch) < 128U ? ascii_linebreak[(ch)] : \
554 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
Alexander Belopolsky40018472011-02-26 01:02:56 +0000556Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200557make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558{
Victor Stinnera85af502013-04-09 21:53:54 +0200559#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
560 do { \
561 TYPE *data = (TYPE *)PTR; \
562 TYPE *end = data + LEN; \
563 Py_UCS4 ch; \
564 for (; data != end; data++) { \
565 ch = *data; \
566 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
567 } \
568 break; \
569 } while (0)
570
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571 /* calculate simple bloom-style bitmask for a given unicode string */
572
Antoine Pitrouf068f942010-01-13 14:19:12 +0000573 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574
575 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200576 switch (kind) {
577 case PyUnicode_1BYTE_KIND:
578 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
579 break;
580 case PyUnicode_2BYTE_KIND:
581 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
582 break;
583 case PyUnicode_4BYTE_KIND:
584 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
585 break;
586 default:
587 assert(0);
588 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000589 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200590
591#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000592}
593
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200594/* Compilation of templated routines */
595
596#include "stringlib/asciilib.h"
597#include "stringlib/fastsearch.h"
598#include "stringlib/partition.h"
599#include "stringlib/split.h"
600#include "stringlib/count.h"
601#include "stringlib/find.h"
602#include "stringlib/find_max_char.h"
603#include "stringlib/localeutil.h"
604#include "stringlib/undef.h"
605
606#include "stringlib/ucs1lib.h"
607#include "stringlib/fastsearch.h"
608#include "stringlib/partition.h"
609#include "stringlib/split.h"
610#include "stringlib/count.h"
611#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300612#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200613#include "stringlib/find_max_char.h"
614#include "stringlib/localeutil.h"
615#include "stringlib/undef.h"
616
617#include "stringlib/ucs2lib.h"
618#include "stringlib/fastsearch.h"
619#include "stringlib/partition.h"
620#include "stringlib/split.h"
621#include "stringlib/count.h"
622#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300623#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200624#include "stringlib/find_max_char.h"
625#include "stringlib/localeutil.h"
626#include "stringlib/undef.h"
627
628#include "stringlib/ucs4lib.h"
629#include "stringlib/fastsearch.h"
630#include "stringlib/partition.h"
631#include "stringlib/split.h"
632#include "stringlib/count.h"
633#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300634#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200635#include "stringlib/find_max_char.h"
636#include "stringlib/localeutil.h"
637#include "stringlib/undef.h"
638
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200639#include "stringlib/unicodedefs.h"
640#include "stringlib/fastsearch.h"
641#include "stringlib/count.h"
642#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100643#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200644
Guido van Rossumd57fd912000-03-10 22:53:23 +0000645/* --- Unicode Object ----------------------------------------------------- */
646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200648fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200649
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200650Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
651 Py_ssize_t size, Py_UCS4 ch,
652 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200653{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200654 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
655
656 switch (kind) {
657 case PyUnicode_1BYTE_KIND:
658 {
659 Py_UCS1 ch1 = (Py_UCS1) ch;
660 if (ch1 == ch)
661 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
662 else
663 return -1;
664 }
665 case PyUnicode_2BYTE_KIND:
666 {
667 Py_UCS2 ch2 = (Py_UCS2) ch;
668 if (ch2 == ch)
669 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
670 else
671 return -1;
672 }
673 case PyUnicode_4BYTE_KIND:
674 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
675 default:
676 assert(0);
677 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200679}
680
Victor Stinnerafffce42012-10-03 23:03:17 +0200681#ifdef Py_DEBUG
682/* Fill the data of an Unicode string with invalid characters to detect bugs
683 earlier.
684
685 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
686 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
687 invalid character in Unicode 6.0. */
688static void
689unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
690{
691 int kind = PyUnicode_KIND(unicode);
692 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
693 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
694 if (length <= old_length)
695 return;
696 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
697}
698#endif
699
Victor Stinnerfe226c02011-10-03 03:52:20 +0200700static PyObject*
701resize_compact(PyObject *unicode, Py_ssize_t length)
702{
703 Py_ssize_t char_size;
704 Py_ssize_t struct_size;
705 Py_ssize_t new_size;
706 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100707 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200708#ifdef Py_DEBUG
709 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
710#endif
711
Victor Stinner79891572012-05-03 13:43:07 +0200712 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200713 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100714 assert(PyUnicode_IS_COMPACT(unicode));
715
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200716 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100717 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718 struct_size = sizeof(PyASCIIObject);
719 else
720 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200721 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200722
Victor Stinnerfe226c02011-10-03 03:52:20 +0200723 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
724 PyErr_NoMemory();
725 return NULL;
726 }
727 new_size = (struct_size + (length + 1) * char_size);
728
Victor Stinner84def372011-12-11 20:04:56 +0100729 _Py_DEC_REFTOTAL;
730 _Py_ForgetReference(unicode);
731
732 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
733 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100734 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200735 PyErr_NoMemory();
736 return NULL;
737 }
Victor Stinner84def372011-12-11 20:04:56 +0100738 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200739 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100740
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200742 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200743 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100744 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200745 _PyUnicode_WSTR_LENGTH(unicode) = length;
746 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100747 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
748 PyObject_DEL(_PyUnicode_WSTR(unicode));
749 _PyUnicode_WSTR(unicode) = NULL;
750 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200751#ifdef Py_DEBUG
752 unicode_fill_invalid(unicode, old_length);
753#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200754 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
755 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200756 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200757 return unicode;
758}
759
Alexander Belopolsky40018472011-02-26 01:02:56 +0000760static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200761resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000762{
Victor Stinner95663112011-10-04 01:03:50 +0200763 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100764 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200765 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000767
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768 if (PyUnicode_IS_READY(unicode)) {
769 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200770 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200771 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200772#ifdef Py_DEBUG
773 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
774#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200775
776 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200777 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200778 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
779 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200780
781 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
782 PyErr_NoMemory();
783 return -1;
784 }
785 new_size = (length + 1) * char_size;
786
Victor Stinner7a9105a2011-12-12 00:13:42 +0100787 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
788 {
789 PyObject_DEL(_PyUnicode_UTF8(unicode));
790 _PyUnicode_UTF8(unicode) = NULL;
791 _PyUnicode_UTF8_LENGTH(unicode) = 0;
792 }
793
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 data = (PyObject *)PyObject_REALLOC(data, new_size);
795 if (data == NULL) {
796 PyErr_NoMemory();
797 return -1;
798 }
799 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200801 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200802 _PyUnicode_WSTR_LENGTH(unicode) = length;
803 }
804 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200805 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200806 _PyUnicode_UTF8_LENGTH(unicode) = length;
807 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200808 _PyUnicode_LENGTH(unicode) = length;
809 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200810#ifdef Py_DEBUG
811 unicode_fill_invalid(unicode, old_length);
812#endif
Victor Stinner95663112011-10-04 01:03:50 +0200813 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200814 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200815 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200816 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200817 }
Victor Stinner95663112011-10-04 01:03:50 +0200818 assert(_PyUnicode_WSTR(unicode) != NULL);
819
820 /* check for integer overflow */
821 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
822 PyErr_NoMemory();
823 return -1;
824 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100825 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200826 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100827 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200828 if (!wstr) {
829 PyErr_NoMemory();
830 return -1;
831 }
832 _PyUnicode_WSTR(unicode) = wstr;
833 _PyUnicode_WSTR(unicode)[length] = 0;
834 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200835 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000836 return 0;
837}
838
Victor Stinnerfe226c02011-10-03 03:52:20 +0200839static PyObject*
840resize_copy(PyObject *unicode, Py_ssize_t length)
841{
842 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100843 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200844 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100845
Benjamin Petersonbac79492012-01-14 13:34:47 -0500846 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100847 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200848
849 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
850 if (copy == NULL)
851 return NULL;
852
853 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200854 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200855 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200856 }
857 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200858 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100859
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200860 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200861 if (w == NULL)
862 return NULL;
863 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
864 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200865 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
866 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200867 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200868 }
869}
870
Guido van Rossumd57fd912000-03-10 22:53:23 +0000871/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000872 Ux0000 terminated; some code (e.g. new_identifier)
873 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000874
875 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000876 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000877
878*/
879
Alexander Belopolsky40018472011-02-26 01:02:56 +0000880static PyUnicodeObject *
881_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000882{
883 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885
Thomas Wouters477c8d52006-05-27 19:21:47 +0000886 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000887 if (length == 0 && unicode_empty != NULL) {
888 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200889 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000890 }
891
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000892 /* Ensure we won't overflow the size. */
893 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
894 return (PyUnicodeObject *)PyErr_NoMemory();
895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 if (length < 0) {
897 PyErr_SetString(PyExc_SystemError,
898 "Negative size passed to _PyUnicode_New");
899 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000900 }
901
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200902 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
903 if (unicode == NULL)
904 return NULL;
905 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
906 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
907 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100908 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000909 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100910 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000911 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912
Jeremy Hyltond8082792003-09-16 19:41:39 +0000913 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000914 * the caller fails before initializing str -- unicode_resize()
915 * reads str[0], and the Keep-Alive optimization can keep memory
916 * allocated for str alive across a call to unicode_dealloc(unicode).
917 * We don't want unicode_resize to read uninitialized memory in
918 * that case.
919 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200920 _PyUnicode_WSTR(unicode)[0] = 0;
921 _PyUnicode_WSTR(unicode)[length] = 0;
922 _PyUnicode_WSTR_LENGTH(unicode) = length;
923 _PyUnicode_HASH(unicode) = -1;
924 _PyUnicode_STATE(unicode).interned = 0;
925 _PyUnicode_STATE(unicode).kind = 0;
926 _PyUnicode_STATE(unicode).compact = 0;
927 _PyUnicode_STATE(unicode).ready = 0;
928 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200929 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200930 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200931 _PyUnicode_UTF8(unicode) = NULL;
932 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100933 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000934 return unicode;
935}
936
Victor Stinnerf42dc442011-10-02 23:33:16 +0200937static const char*
938unicode_kind_name(PyObject *unicode)
939{
Victor Stinner42dfd712011-10-03 14:41:45 +0200940 /* don't check consistency: unicode_kind_name() is called from
941 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200942 if (!PyUnicode_IS_COMPACT(unicode))
943 {
944 if (!PyUnicode_IS_READY(unicode))
945 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600946 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200947 {
948 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200949 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200950 return "legacy ascii";
951 else
952 return "legacy latin1";
953 case PyUnicode_2BYTE_KIND:
954 return "legacy UCS2";
955 case PyUnicode_4BYTE_KIND:
956 return "legacy UCS4";
957 default:
958 return "<legacy invalid kind>";
959 }
960 }
961 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600962 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200963 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965 return "ascii";
966 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200967 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200968 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200969 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200970 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200971 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200972 default:
973 return "<invalid compact kind>";
974 }
975}
976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978/* Functions wrapping macros for use in debugger */
979char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200980 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200981}
982
983void *_PyUnicode_compact_data(void *unicode) {
984 return _PyUnicode_COMPACT_DATA(unicode);
985}
986void *_PyUnicode_data(void *unicode){
987 printf("obj %p\n", unicode);
988 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
989 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
990 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
991 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
992 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
993 return PyUnicode_DATA(unicode);
994}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200995
996void
997_PyUnicode_Dump(PyObject *op)
998{
999 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001000 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1001 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1002 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001003
Victor Stinnera849a4b2011-10-03 12:12:11 +02001004 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001005 {
1006 if (ascii->state.ascii)
1007 data = (ascii + 1);
1008 else
1009 data = (compact + 1);
1010 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001011 else
1012 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +02001013 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
1014
Victor Stinnera849a4b2011-10-03 12:12:11 +02001015 if (ascii->wstr == data)
1016 printf("shared ");
1017 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001018
Victor Stinnera3b334d2011-10-03 13:53:37 +02001019 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +02001020 printf(" (%zu), ", compact->wstr_length);
1021 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1022 printf("shared ");
1023 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001024 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001025 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001026}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001027#endif
1028
1029PyObject *
1030PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1031{
1032 PyObject *obj;
1033 PyCompactUnicodeObject *unicode;
1034 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001035 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001036 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001037 Py_ssize_t char_size;
1038 Py_ssize_t struct_size;
1039
1040 /* Optimization for empty strings */
1041 if (size == 0 && unicode_empty != NULL) {
1042 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001043 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 }
1045
Victor Stinner9e9d6892011-10-04 01:02:02 +02001046 is_ascii = 0;
1047 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 struct_size = sizeof(PyCompactUnicodeObject);
1049 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001050 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051 char_size = 1;
1052 is_ascii = 1;
1053 struct_size = sizeof(PyASCIIObject);
1054 }
1055 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001056 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057 char_size = 1;
1058 }
1059 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001060 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001061 char_size = 2;
1062 if (sizeof(wchar_t) == 2)
1063 is_sharing = 1;
1064 }
1065 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001066 if (maxchar > MAX_UNICODE) {
1067 PyErr_SetString(PyExc_SystemError,
1068 "invalid maximum character passed to PyUnicode_New");
1069 return NULL;
1070 }
Victor Stinner8f825062012-04-27 13:55:39 +02001071 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 char_size = 4;
1073 if (sizeof(wchar_t) == 4)
1074 is_sharing = 1;
1075 }
1076
1077 /* Ensure we won't overflow the size. */
1078 if (size < 0) {
1079 PyErr_SetString(PyExc_SystemError,
1080 "Negative size passed to PyUnicode_New");
1081 return NULL;
1082 }
1083 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1084 return PyErr_NoMemory();
1085
1086 /* Duplicated allocation code from _PyObject_New() instead of a call to
1087 * PyObject_New() so we are able to allocate space for the object and
1088 * it's data buffer.
1089 */
1090 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1091 if (obj == NULL)
1092 return PyErr_NoMemory();
1093 obj = PyObject_INIT(obj, &PyUnicode_Type);
1094 if (obj == NULL)
1095 return NULL;
1096
1097 unicode = (PyCompactUnicodeObject *)obj;
1098 if (is_ascii)
1099 data = ((PyASCIIObject*)obj) + 1;
1100 else
1101 data = unicode + 1;
1102 _PyUnicode_LENGTH(unicode) = size;
1103 _PyUnicode_HASH(unicode) = -1;
1104 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001105 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001106 _PyUnicode_STATE(unicode).compact = 1;
1107 _PyUnicode_STATE(unicode).ready = 1;
1108 _PyUnicode_STATE(unicode).ascii = is_ascii;
1109 if (is_ascii) {
1110 ((char*)data)[size] = 0;
1111 _PyUnicode_WSTR(unicode) = NULL;
1112 }
Victor Stinner8f825062012-04-27 13:55:39 +02001113 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001114 ((char*)data)[size] = 0;
1115 _PyUnicode_WSTR(unicode) = NULL;
1116 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001118 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001119 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 else {
1121 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001122 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001123 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001124 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001125 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126 ((Py_UCS4*)data)[size] = 0;
1127 if (is_sharing) {
1128 _PyUnicode_WSTR_LENGTH(unicode) = size;
1129 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1130 }
1131 else {
1132 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1133 _PyUnicode_WSTR(unicode) = NULL;
1134 }
1135 }
Victor Stinner8f825062012-04-27 13:55:39 +02001136#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001137 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001138#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001139 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001140 return obj;
1141}
1142
1143#if SIZEOF_WCHAR_T == 2
1144/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1145 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001146 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147
1148 This function assumes that unicode can hold one more code point than wstr
1149 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001150static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001151unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001152 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153{
1154 const wchar_t *iter;
1155 Py_UCS4 *ucs4_out;
1156
Victor Stinner910337b2011-10-03 03:20:16 +02001157 assert(unicode != NULL);
1158 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1160 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1161
1162 for (iter = begin; iter < end; ) {
1163 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1164 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001165 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1166 && (iter+1) < end
1167 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001168 {
Victor Stinner551ac952011-11-29 22:58:13 +01001169 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170 iter += 2;
1171 }
1172 else {
1173 *ucs4_out++ = *iter;
1174 iter++;
1175 }
1176 }
1177 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1178 _PyUnicode_GET_LENGTH(unicode)));
1179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001180}
1181#endif
1182
Victor Stinnercd9950f2011-10-02 00:34:53 +02001183static int
Victor Stinner488fa492011-12-12 00:01:39 +01001184unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001185{
Victor Stinner488fa492011-12-12 00:01:39 +01001186 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001187 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001188 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001189 return -1;
1190 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001191 return 0;
1192}
1193
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001194static int
1195_copy_characters(PyObject *to, Py_ssize_t to_start,
1196 PyObject *from, Py_ssize_t from_start,
1197 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001199 unsigned int from_kind, to_kind;
1200 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201
Victor Stinneree4544c2012-05-09 22:24:08 +02001202 assert(0 <= how_many);
1203 assert(0 <= from_start);
1204 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001205 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001206 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001207 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208
Victor Stinnerd3f08822012-05-29 12:57:52 +02001209 assert(PyUnicode_Check(to));
1210 assert(PyUnicode_IS_READY(to));
1211 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1212
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001213 if (how_many == 0)
1214 return 0;
1215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001217 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001219 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220
Victor Stinnerf1852262012-06-16 16:38:26 +02001221#ifdef Py_DEBUG
1222 if (!check_maxchar
1223 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1224 {
1225 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1226 Py_UCS4 ch;
1227 Py_ssize_t i;
1228 for (i=0; i < how_many; i++) {
1229 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1230 assert(ch <= to_maxchar);
1231 }
1232 }
1233#endif
1234
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001235 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001236 if (check_maxchar
1237 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1238 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001239 /* Writing Latin-1 characters into an ASCII string requires to
1240 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001241 Py_UCS4 max_char;
1242 max_char = ucs1lib_find_max_char(from_data,
1243 (Py_UCS1*)from_data + how_many);
1244 if (max_char >= 128)
1245 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001246 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001247 Py_MEMCPY((char*)to_data + to_kind * to_start,
1248 (char*)from_data + from_kind * from_start,
1249 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001250 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001251 else if (from_kind == PyUnicode_1BYTE_KIND
1252 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001253 {
1254 _PyUnicode_CONVERT_BYTES(
1255 Py_UCS1, Py_UCS2,
1256 PyUnicode_1BYTE_DATA(from) + from_start,
1257 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1258 PyUnicode_2BYTE_DATA(to) + to_start
1259 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001260 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001261 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001262 && to_kind == PyUnicode_4BYTE_KIND)
1263 {
1264 _PyUnicode_CONVERT_BYTES(
1265 Py_UCS1, Py_UCS4,
1266 PyUnicode_1BYTE_DATA(from) + from_start,
1267 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1268 PyUnicode_4BYTE_DATA(to) + to_start
1269 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001270 }
1271 else if (from_kind == PyUnicode_2BYTE_KIND
1272 && to_kind == PyUnicode_4BYTE_KIND)
1273 {
1274 _PyUnicode_CONVERT_BYTES(
1275 Py_UCS2, Py_UCS4,
1276 PyUnicode_2BYTE_DATA(from) + from_start,
1277 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1278 PyUnicode_4BYTE_DATA(to) + to_start
1279 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001280 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001281 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001282 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1283
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001284 if (!check_maxchar) {
1285 if (from_kind == PyUnicode_2BYTE_KIND
1286 && to_kind == PyUnicode_1BYTE_KIND)
1287 {
1288 _PyUnicode_CONVERT_BYTES(
1289 Py_UCS2, Py_UCS1,
1290 PyUnicode_2BYTE_DATA(from) + from_start,
1291 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1292 PyUnicode_1BYTE_DATA(to) + to_start
1293 );
1294 }
1295 else if (from_kind == PyUnicode_4BYTE_KIND
1296 && to_kind == PyUnicode_1BYTE_KIND)
1297 {
1298 _PyUnicode_CONVERT_BYTES(
1299 Py_UCS4, Py_UCS1,
1300 PyUnicode_4BYTE_DATA(from) + from_start,
1301 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1302 PyUnicode_1BYTE_DATA(to) + to_start
1303 );
1304 }
1305 else if (from_kind == PyUnicode_4BYTE_KIND
1306 && to_kind == PyUnicode_2BYTE_KIND)
1307 {
1308 _PyUnicode_CONVERT_BYTES(
1309 Py_UCS4, Py_UCS2,
1310 PyUnicode_4BYTE_DATA(from) + from_start,
1311 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1312 PyUnicode_2BYTE_DATA(to) + to_start
1313 );
1314 }
1315 else {
1316 assert(0);
1317 return -1;
1318 }
1319 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001320 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001321 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001322 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001323 Py_ssize_t i;
1324
Victor Stinnera0702ab2011-09-29 14:14:38 +02001325 for (i=0; i < how_many; i++) {
1326 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001327 if (ch > to_maxchar)
1328 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001329 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1330 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001331 }
1332 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001333 return 0;
1334}
1335
Victor Stinnerd3f08822012-05-29 12:57:52 +02001336void
1337_PyUnicode_FastCopyCharacters(
1338 PyObject *to, Py_ssize_t to_start,
1339 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001340{
1341 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1342}
1343
1344Py_ssize_t
1345PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1346 PyObject *from, Py_ssize_t from_start,
1347 Py_ssize_t how_many)
1348{
1349 int err;
1350
1351 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1352 PyErr_BadInternalCall();
1353 return -1;
1354 }
1355
Benjamin Petersonbac79492012-01-14 13:34:47 -05001356 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001357 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001358 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001359 return -1;
1360
Victor Stinnerd3f08822012-05-29 12:57:52 +02001361 if (from_start < 0) {
1362 PyErr_SetString(PyExc_IndexError, "string index out of range");
1363 return -1;
1364 }
1365 if (to_start < 0) {
1366 PyErr_SetString(PyExc_IndexError, "string index out of range");
1367 return -1;
1368 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001369 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1370 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1371 PyErr_Format(PyExc_SystemError,
1372 "Cannot write %zi characters at %zi "
1373 "in a string of %zi characters",
1374 how_many, to_start, PyUnicode_GET_LENGTH(to));
1375 return -1;
1376 }
1377
1378 if (how_many == 0)
1379 return 0;
1380
Victor Stinner488fa492011-12-12 00:01:39 +01001381 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001382 return -1;
1383
1384 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1385 if (err) {
1386 PyErr_Format(PyExc_SystemError,
1387 "Cannot copy %s characters "
1388 "into a string of %s characters",
1389 unicode_kind_name(from),
1390 unicode_kind_name(to));
1391 return -1;
1392 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001393 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394}
1395
Victor Stinner17222162011-09-28 22:15:37 +02001396/* Find the maximum code point and count the number of surrogate pairs so a
1397 correct string length can be computed before converting a string to UCS4.
1398 This function counts single surrogates as a character and not as a pair.
1399
1400 Return 0 on success, or -1 on error. */
1401static int
1402find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1403 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404{
1405 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001406 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407
Victor Stinnerc53be962011-10-02 21:33:54 +02001408 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 *num_surrogates = 0;
1410 *maxchar = 0;
1411
1412 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001413#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001414 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1415 && (iter+1) < end
1416 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1417 {
1418 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1419 ++(*num_surrogates);
1420 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 }
1422 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001424 {
1425 ch = *iter;
1426 iter++;
1427 }
1428 if (ch > *maxchar) {
1429 *maxchar = ch;
1430 if (*maxchar > MAX_UNICODE) {
1431 PyErr_Format(PyExc_ValueError,
1432 "character U+%x is not in range [U+0000; U+10ffff]",
1433 ch);
1434 return -1;
1435 }
1436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437 }
1438 return 0;
1439}
1440
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001441int
1442_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443{
1444 wchar_t *end;
1445 Py_UCS4 maxchar = 0;
1446 Py_ssize_t num_surrogates;
1447#if SIZEOF_WCHAR_T == 2
1448 Py_ssize_t length_wo_surrogates;
1449#endif
1450
Georg Brandl7597add2011-10-05 16:36:47 +02001451 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001452 strings were created using _PyObject_New() and where no canonical
1453 representation (the str field) has been set yet aka strings
1454 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001455 assert(_PyUnicode_CHECK(unicode));
1456 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001457 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001459 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001460 /* Actually, it should neither be interned nor be anything else: */
1461 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001464 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001465 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467
1468 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001469 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1470 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001471 PyErr_NoMemory();
1472 return -1;
1473 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001474 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001475 _PyUnicode_WSTR(unicode), end,
1476 PyUnicode_1BYTE_DATA(unicode));
1477 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1478 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1479 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1480 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001481 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001482 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001483 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001484 }
1485 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001486 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001487 _PyUnicode_UTF8(unicode) = NULL;
1488 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001489 }
1490 PyObject_FREE(_PyUnicode_WSTR(unicode));
1491 _PyUnicode_WSTR(unicode) = NULL;
1492 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1493 }
1494 /* In this case we might have to convert down from 4-byte native
1495 wchar_t to 2-byte unicode. */
1496 else if (maxchar < 65536) {
1497 assert(num_surrogates == 0 &&
1498 "FindMaxCharAndNumSurrogatePairs() messed up");
1499
Victor Stinner506f5922011-09-28 22:34:18 +02001500#if SIZEOF_WCHAR_T == 2
1501 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001502 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001503 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1504 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1505 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001506 _PyUnicode_UTF8(unicode) = NULL;
1507 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001508#else
1509 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001510 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001511 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001512 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001513 PyErr_NoMemory();
1514 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001515 }
Victor Stinner506f5922011-09-28 22:34:18 +02001516 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1517 _PyUnicode_WSTR(unicode), end,
1518 PyUnicode_2BYTE_DATA(unicode));
1519 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1520 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1521 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001522 _PyUnicode_UTF8(unicode) = NULL;
1523 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001524 PyObject_FREE(_PyUnicode_WSTR(unicode));
1525 _PyUnicode_WSTR(unicode) = NULL;
1526 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1527#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001528 }
1529 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1530 else {
1531#if SIZEOF_WCHAR_T == 2
1532 /* in case the native representation is 2-bytes, we need to allocate a
1533 new normalized 4-byte version. */
1534 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001535 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1536 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001537 PyErr_NoMemory();
1538 return -1;
1539 }
1540 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1541 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001542 _PyUnicode_UTF8(unicode) = NULL;
1543 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001544 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1545 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001546 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001547 PyObject_FREE(_PyUnicode_WSTR(unicode));
1548 _PyUnicode_WSTR(unicode) = NULL;
1549 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1550#else
1551 assert(num_surrogates == 0);
1552
Victor Stinnerc3c74152011-10-02 20:39:55 +02001553 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001554 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001555 _PyUnicode_UTF8(unicode) = NULL;
1556 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1558#endif
1559 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1560 }
1561 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001562 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001563 return 0;
1564}
1565
Alexander Belopolsky40018472011-02-26 01:02:56 +00001566static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001567unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001568{
Walter Dörwald16807132007-05-25 13:52:07 +00001569 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001570 case SSTATE_NOT_INTERNED:
1571 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001572
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 case SSTATE_INTERNED_MORTAL:
1574 /* revive dead object temporarily for DelItem */
1575 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001576 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 Py_FatalError(
1578 "deletion of interned string failed");
1579 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001580
Benjamin Peterson29060642009-01-31 22:14:21 +00001581 case SSTATE_INTERNED_IMMORTAL:
1582 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001583
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 default:
1585 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001586 }
1587
Victor Stinner03490912011-10-03 23:45:12 +02001588 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001589 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001590 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001591 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001592 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1593 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001595 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001596}
1597
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001598#ifdef Py_DEBUG
1599static int
1600unicode_is_singleton(PyObject *unicode)
1601{
1602 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1603 if (unicode == unicode_empty)
1604 return 1;
1605 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1606 {
1607 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1608 if (ch < 256 && unicode_latin1[ch] == unicode)
1609 return 1;
1610 }
1611 return 0;
1612}
1613#endif
1614
Alexander Belopolsky40018472011-02-26 01:02:56 +00001615static int
Victor Stinner488fa492011-12-12 00:01:39 +01001616unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001617{
Victor Stinner488fa492011-12-12 00:01:39 +01001618 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001619 if (Py_REFCNT(unicode) != 1)
1620 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001621 if (_PyUnicode_HASH(unicode) != -1)
1622 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001623 if (PyUnicode_CHECK_INTERNED(unicode))
1624 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001625 if (!PyUnicode_CheckExact(unicode))
1626 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001627#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001628 /* singleton refcount is greater than 1 */
1629 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001630#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001631 return 1;
1632}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001633
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634static int
1635unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1636{
1637 PyObject *unicode;
1638 Py_ssize_t old_length;
1639
1640 assert(p_unicode != NULL);
1641 unicode = *p_unicode;
1642
1643 assert(unicode != NULL);
1644 assert(PyUnicode_Check(unicode));
1645 assert(0 <= length);
1646
Victor Stinner910337b2011-10-03 03:20:16 +02001647 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001648 old_length = PyUnicode_WSTR_LENGTH(unicode);
1649 else
1650 old_length = PyUnicode_GET_LENGTH(unicode);
1651 if (old_length == length)
1652 return 0;
1653
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001654 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001655 _Py_INCREF_UNICODE_EMPTY();
1656 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001657 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001658 Py_DECREF(*p_unicode);
1659 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001660 return 0;
1661 }
1662
Victor Stinner488fa492011-12-12 00:01:39 +01001663 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001664 PyObject *copy = resize_copy(unicode, length);
1665 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001666 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001667 Py_DECREF(*p_unicode);
1668 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001670 }
1671
Victor Stinnerfe226c02011-10-03 03:52:20 +02001672 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001673 PyObject *new_unicode = resize_compact(unicode, length);
1674 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001675 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001676 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001677 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001678 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001679 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001680}
1681
Alexander Belopolsky40018472011-02-26 01:02:56 +00001682int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001683PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001684{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001685 PyObject *unicode;
1686 if (p_unicode == NULL) {
1687 PyErr_BadInternalCall();
1688 return -1;
1689 }
1690 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001691 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001692 {
1693 PyErr_BadInternalCall();
1694 return -1;
1695 }
1696 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001697}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001698
Victor Stinnerc5166102012-02-22 13:55:02 +01001699/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001700
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001701 WARNING: The function doesn't copy the terminating null character and
1702 doesn't check the maximum character (may write a latin1 character in an
1703 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001704static void
1705unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1706 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001707{
1708 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1709 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001710 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001711
1712 switch (kind) {
1713 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001714 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001715#ifdef Py_DEBUG
1716 if (PyUnicode_IS_ASCII(unicode)) {
1717 Py_UCS4 maxchar = ucs1lib_find_max_char(
1718 (const Py_UCS1*)str,
1719 (const Py_UCS1*)str + len);
1720 assert(maxchar < 128);
1721 }
1722#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001723 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001724 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001725 }
1726 case PyUnicode_2BYTE_KIND: {
1727 Py_UCS2 *start = (Py_UCS2 *)data + index;
1728 Py_UCS2 *ucs2 = start;
1729 assert(index <= PyUnicode_GET_LENGTH(unicode));
1730
Victor Stinner184252a2012-06-16 02:57:41 +02001731 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001732 *ucs2 = (Py_UCS2)*str;
1733
1734 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001735 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001736 }
1737 default: {
1738 Py_UCS4 *start = (Py_UCS4 *)data + index;
1739 Py_UCS4 *ucs4 = start;
1740 assert(kind == PyUnicode_4BYTE_KIND);
1741 assert(index <= PyUnicode_GET_LENGTH(unicode));
1742
Victor Stinner184252a2012-06-16 02:57:41 +02001743 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001744 *ucs4 = (Py_UCS4)*str;
1745
1746 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001747 }
1748 }
1749}
1750
1751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752static PyObject*
1753get_latin1_char(unsigned char ch)
1754{
Victor Stinnera464fc12011-10-02 20:39:30 +02001755 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode)
1759 return NULL;
1760 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001761 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 unicode_latin1[ch] = unicode;
1763 }
1764 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001765 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766}
1767
Alexander Belopolsky40018472011-02-26 01:02:56 +00001768PyObject *
1769PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001770{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001771 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772 Py_UCS4 maxchar = 0;
1773 Py_ssize_t num_surrogates;
1774
1775 if (u == NULL)
1776 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001777
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001778 /* If the Unicode data is known at construction time, we can apply
1779 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001781 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001782 if (size == 0)
1783 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001785 /* Single character Unicode objects in the Latin-1 range are
1786 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001787 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788 return get_latin1_char((unsigned char)*u);
1789
1790 /* If not empty and not single character, copy the Unicode data
1791 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001792 if (find_maxchar_surrogates(u, u + size,
1793 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001794 return NULL;
1795
Victor Stinner8faf8212011-12-08 22:14:11 +01001796 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001797 if (!unicode)
1798 return NULL;
1799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 switch (PyUnicode_KIND(unicode)) {
1801 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001802 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001803 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1804 break;
1805 case PyUnicode_2BYTE_KIND:
1806#if Py_UNICODE_SIZE == 2
1807 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1808#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001809 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001810 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1811#endif
1812 break;
1813 case PyUnicode_4BYTE_KIND:
1814#if SIZEOF_WCHAR_T == 2
1815 /* This is the only case which has to process surrogates, thus
1816 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001817 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818#else
1819 assert(num_surrogates == 0);
1820 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1821#endif
1822 break;
1823 default:
1824 assert(0 && "Impossible state");
1825 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001826
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001827 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001828}
1829
Alexander Belopolsky40018472011-02-26 01:02:56 +00001830PyObject *
1831PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001832{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001833 if (size < 0) {
1834 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001835 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001836 return NULL;
1837 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001838 if (u != NULL)
1839 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1840 else
1841 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001842}
1843
Alexander Belopolsky40018472011-02-26 01:02:56 +00001844PyObject *
1845PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001846{
1847 size_t size = strlen(u);
1848 if (size > PY_SSIZE_T_MAX) {
1849 PyErr_SetString(PyExc_OverflowError, "input too long");
1850 return NULL;
1851 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001852 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001853}
1854
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001855PyObject *
1856_PyUnicode_FromId(_Py_Identifier *id)
1857{
1858 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001859 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1860 strlen(id->string),
1861 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001862 if (!id->object)
1863 return NULL;
1864 PyUnicode_InternInPlace(&id->object);
1865 assert(!id->next);
1866 id->next = static_strings;
1867 static_strings = id;
1868 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001869 return id->object;
1870}
1871
1872void
1873_PyUnicode_ClearStaticStrings()
1874{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001875 _Py_Identifier *tmp, *s = static_strings;
1876 while (s) {
1877 Py_DECREF(s->object);
1878 s->object = NULL;
1879 tmp = s->next;
1880 s->next = NULL;
1881 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001882 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001883 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001884}
1885
Benjamin Peterson0df54292012-03-26 14:50:32 -04001886/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001887
Victor Stinnerd3f08822012-05-29 12:57:52 +02001888PyObject*
1889_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001890{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001891 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001892 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001893 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001894#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001895 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001896#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001897 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001898 }
Victor Stinner785938e2011-12-11 20:09:03 +01001899 unicode = PyUnicode_New(size, 127);
1900 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001901 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001902 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1903 assert(_PyUnicode_CheckConsistency(unicode, 1));
1904 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001905}
1906
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001907static Py_UCS4
1908kind_maxchar_limit(unsigned int kind)
1909{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001910 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001911 case PyUnicode_1BYTE_KIND:
1912 return 0x80;
1913 case PyUnicode_2BYTE_KIND:
1914 return 0x100;
1915 case PyUnicode_4BYTE_KIND:
1916 return 0x10000;
1917 default:
1918 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001919 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001920 }
1921}
1922
Victor Stinnere6abb482012-05-02 01:15:40 +02001923Py_LOCAL_INLINE(Py_UCS4)
1924align_maxchar(Py_UCS4 maxchar)
1925{
1926 if (maxchar <= 127)
1927 return 127;
1928 else if (maxchar <= 255)
1929 return 255;
1930 else if (maxchar <= 65535)
1931 return 65535;
1932 else
1933 return MAX_UNICODE;
1934}
1935
Victor Stinner702c7342011-10-05 13:50:52 +02001936static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001937_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001938{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001940 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001941
Serhiy Storchaka678db842013-01-26 12:16:36 +02001942 if (size == 0)
1943 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001944 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001945 if (size == 1)
1946 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001947
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001948 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001949 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 if (!res)
1951 return NULL;
1952 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001953 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001955}
1956
Victor Stinnere57b1c02011-09-28 22:20:48 +02001957static PyObject*
1958_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001959{
1960 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001961 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001962
Serhiy Storchaka678db842013-01-26 12:16:36 +02001963 if (size == 0)
1964 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001965 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001966 if (size == 1) {
1967 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001968 int kind;
1969 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001970 if (ch < 256)
1971 return get_latin1_char((unsigned char)ch);
1972
1973 res = PyUnicode_New(1, ch);
1974 if (res == NULL)
1975 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001976 kind = PyUnicode_KIND(res);
1977 data = PyUnicode_DATA(res);
1978 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001979 assert(_PyUnicode_CheckConsistency(res, 1));
1980 return res;
1981 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001982
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001983 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001984 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 if (!res)
1986 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001987 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001989 else {
1990 _PyUnicode_CONVERT_BYTES(
1991 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1992 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001993 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return res;
1995}
1996
Victor Stinnere57b1c02011-09-28 22:20:48 +02001997static PyObject*
1998_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999{
2000 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002001 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002
Serhiy Storchaka678db842013-01-26 12:16:36 +02002003 if (size == 0)
2004 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002005 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002006 if (size == 1) {
2007 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002008 int kind;
2009 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002010 if (ch < 256)
2011 return get_latin1_char((unsigned char)ch);
2012
2013 res = PyUnicode_New(1, ch);
2014 if (res == NULL)
2015 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002016 kind = PyUnicode_KIND(res);
2017 data = PyUnicode_DATA(res);
2018 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002019 assert(_PyUnicode_CheckConsistency(res, 1));
2020 return res;
2021 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002022
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002023 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002024 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025 if (!res)
2026 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002027 if (max_char < 256)
2028 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2029 PyUnicode_1BYTE_DATA(res));
2030 else if (max_char < 0x10000)
2031 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2032 PyUnicode_2BYTE_DATA(res));
2033 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002035 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002036 return res;
2037}
2038
2039PyObject*
2040PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2041{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002042 if (size < 0) {
2043 PyErr_SetString(PyExc_ValueError, "size must be positive");
2044 return NULL;
2045 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002046 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002048 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002050 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002051 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002052 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002053 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 PyErr_SetString(PyExc_SystemError, "invalid kind");
2055 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057}
2058
Victor Stinnerece58de2012-04-23 23:36:38 +02002059Py_UCS4
2060_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2061{
2062 enum PyUnicode_Kind kind;
2063 void *startptr, *endptr;
2064
2065 assert(PyUnicode_IS_READY(unicode));
2066 assert(0 <= start);
2067 assert(end <= PyUnicode_GET_LENGTH(unicode));
2068 assert(start <= end);
2069
2070 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2071 return PyUnicode_MAX_CHAR_VALUE(unicode);
2072
2073 if (start == end)
2074 return 127;
2075
Victor Stinner94d558b2012-04-27 22:26:58 +02002076 if (PyUnicode_IS_ASCII(unicode))
2077 return 127;
2078
Victor Stinnerece58de2012-04-23 23:36:38 +02002079 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002080 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002081 endptr = (char *)startptr + end * kind;
2082 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002083 switch(kind) {
2084 case PyUnicode_1BYTE_KIND:
2085 return ucs1lib_find_max_char(startptr, endptr);
2086 case PyUnicode_2BYTE_KIND:
2087 return ucs2lib_find_max_char(startptr, endptr);
2088 case PyUnicode_4BYTE_KIND:
2089 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002090 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002091 assert(0);
2092 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002093 }
2094}
2095
Victor Stinner25a4b292011-10-06 12:31:55 +02002096/* Ensure that a string uses the most efficient storage, if it is not the
2097 case: create a new string with of the right kind. Write NULL into *p_unicode
2098 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002099static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002100unicode_adjust_maxchar(PyObject **p_unicode)
2101{
2102 PyObject *unicode, *copy;
2103 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002104 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002105 unsigned int kind;
2106
2107 assert(p_unicode != NULL);
2108 unicode = *p_unicode;
2109 assert(PyUnicode_IS_READY(unicode));
2110 if (PyUnicode_IS_ASCII(unicode))
2111 return;
2112
2113 len = PyUnicode_GET_LENGTH(unicode);
2114 kind = PyUnicode_KIND(unicode);
2115 if (kind == PyUnicode_1BYTE_KIND) {
2116 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002117 max_char = ucs1lib_find_max_char(u, u + len);
2118 if (max_char >= 128)
2119 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002120 }
2121 else if (kind == PyUnicode_2BYTE_KIND) {
2122 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002123 max_char = ucs2lib_find_max_char(u, u + len);
2124 if (max_char >= 256)
2125 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002126 }
2127 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002128 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002129 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002130 max_char = ucs4lib_find_max_char(u, u + len);
2131 if (max_char >= 0x10000)
2132 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002133 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002135 if (copy != NULL)
2136 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002137 Py_DECREF(unicode);
2138 *p_unicode = copy;
2139}
2140
Victor Stinner034f6cf2011-09-30 02:26:44 +02002141PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002142_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002143{
Victor Stinner87af4f22011-11-21 23:03:47 +01002144 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002145 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146
Victor Stinner034f6cf2011-09-30 02:26:44 +02002147 if (!PyUnicode_Check(unicode)) {
2148 PyErr_BadInternalCall();
2149 return NULL;
2150 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002151 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002152 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002153
Victor Stinner87af4f22011-11-21 23:03:47 +01002154 length = PyUnicode_GET_LENGTH(unicode);
2155 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002156 if (!copy)
2157 return NULL;
2158 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2159
Victor Stinner87af4f22011-11-21 23:03:47 +01002160 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2161 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002162 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002163 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002164}
2165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002166
Victor Stinnerbc603d12011-10-02 01:00:40 +02002167/* Widen Unicode objects to larger buffers. Don't write terminating null
2168 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169
2170void*
2171_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2172{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002173 Py_ssize_t len;
2174 void *result;
2175 unsigned int skind;
2176
Benjamin Petersonbac79492012-01-14 13:34:47 -05002177 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002178 return NULL;
2179
2180 len = PyUnicode_GET_LENGTH(s);
2181 skind = PyUnicode_KIND(s);
2182 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002183 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184 return NULL;
2185 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002186 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002187 case PyUnicode_2BYTE_KIND:
2188 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2189 if (!result)
2190 return PyErr_NoMemory();
2191 assert(skind == PyUnicode_1BYTE_KIND);
2192 _PyUnicode_CONVERT_BYTES(
2193 Py_UCS1, Py_UCS2,
2194 PyUnicode_1BYTE_DATA(s),
2195 PyUnicode_1BYTE_DATA(s) + len,
2196 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002198 case PyUnicode_4BYTE_KIND:
2199 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2200 if (!result)
2201 return PyErr_NoMemory();
2202 if (skind == PyUnicode_2BYTE_KIND) {
2203 _PyUnicode_CONVERT_BYTES(
2204 Py_UCS2, Py_UCS4,
2205 PyUnicode_2BYTE_DATA(s),
2206 PyUnicode_2BYTE_DATA(s) + len,
2207 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002209 else {
2210 assert(skind == PyUnicode_1BYTE_KIND);
2211 _PyUnicode_CONVERT_BYTES(
2212 Py_UCS1, Py_UCS4,
2213 PyUnicode_1BYTE_DATA(s),
2214 PyUnicode_1BYTE_DATA(s) + len,
2215 result);
2216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002218 default:
2219 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 }
Victor Stinner01698042011-10-04 00:04:26 +02002221 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 return NULL;
2223}
2224
2225static Py_UCS4*
2226as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2227 int copy_null)
2228{
2229 int kind;
2230 void *data;
2231 Py_ssize_t len, targetlen;
2232 if (PyUnicode_READY(string) == -1)
2233 return NULL;
2234 kind = PyUnicode_KIND(string);
2235 data = PyUnicode_DATA(string);
2236 len = PyUnicode_GET_LENGTH(string);
2237 targetlen = len;
2238 if (copy_null)
2239 targetlen++;
2240 if (!target) {
2241 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2242 PyErr_NoMemory();
2243 return NULL;
2244 }
2245 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2246 if (!target) {
2247 PyErr_NoMemory();
2248 return NULL;
2249 }
2250 }
2251 else {
2252 if (targetsize < targetlen) {
2253 PyErr_Format(PyExc_SystemError,
2254 "string is longer than the buffer");
2255 if (copy_null && 0 < targetsize)
2256 target[0] = 0;
2257 return NULL;
2258 }
2259 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002260 if (kind == PyUnicode_1BYTE_KIND) {
2261 Py_UCS1 *start = (Py_UCS1 *) data;
2262 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002263 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002264 else if (kind == PyUnicode_2BYTE_KIND) {
2265 Py_UCS2 *start = (Py_UCS2 *) data;
2266 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2267 }
2268 else {
2269 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002270 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 if (copy_null)
2273 target[len] = 0;
2274 return target;
2275}
2276
2277Py_UCS4*
2278PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2279 int copy_null)
2280{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002281 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002282 PyErr_BadInternalCall();
2283 return NULL;
2284 }
2285 return as_ucs4(string, target, targetsize, copy_null);
2286}
2287
2288Py_UCS4*
2289PyUnicode_AsUCS4Copy(PyObject *string)
2290{
2291 return as_ucs4(string, NULL, 0, 1);
2292}
2293
2294#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002295
Alexander Belopolsky40018472011-02-26 01:02:56 +00002296PyObject *
2297PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002298{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002299 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002301 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002302 PyErr_BadInternalCall();
2303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304 }
2305
Martin v. Löwis790465f2008-04-05 20:41:37 +00002306 if (size == -1) {
2307 size = wcslen(w);
2308 }
2309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002311}
2312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002314
Walter Dörwald346737f2007-05-31 10:44:43 +00002315static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002316makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002317 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002318{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002319 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002320 if (longflag)
2321 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002322 else if (longlongflag) {
2323 /* longlongflag should only ever be nonzero on machines with
2324 HAVE_LONG_LONG defined */
2325#ifdef HAVE_LONG_LONG
2326 char *f = PY_FORMAT_LONG_LONG;
2327 while (*f)
2328 *fmt++ = *f++;
2329#else
2330 /* we shouldn't ever get here */
2331 assert(0);
2332 *fmt++ = 'l';
2333#endif
2334 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002335 else if (size_tflag) {
2336 char *f = PY_FORMAT_SIZE_T;
2337 while (*f)
2338 *fmt++ = *f++;
2339 }
2340 *fmt++ = c;
2341 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002342}
2343
Victor Stinner15a11362012-10-06 23:48:20 +02002344/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002345 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2346 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2347#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002348
2349static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002350unicode_fromformat_arg(_PyUnicodeWriter *writer,
2351 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002352{
Victor Stinnere215d962012-10-06 23:03:36 +02002353 const char *p;
2354 Py_ssize_t len;
2355 int zeropad;
2356 int width;
2357 int precision;
2358 int longflag;
2359 int longlongflag;
2360 int size_tflag;
2361 int fill;
2362
2363 p = f;
2364 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002365 zeropad = 0;
2366 if (*f == '0') {
2367 zeropad = 1;
2368 f++;
2369 }
Victor Stinner96865452011-03-01 23:44:09 +00002370
2371 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner96865452011-03-01 23:44:09 +00002372 width = 0;
Victor Stinnere215d962012-10-06 23:03:36 +02002373 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner3921e902012-10-06 23:05:00 +02002374 if (width > (INT_MAX - ((int)*f - '0')) / 10) {
2375 PyErr_SetString(PyExc_ValueError,
2376 "width too big");
2377 return NULL;
2378 }
Victor Stinnere215d962012-10-06 23:03:36 +02002379 width = (width*10) + (*f - '0');
2380 f++;
2381 }
Victor Stinner96865452011-03-01 23:44:09 +00002382 precision = 0;
2383 if (*f == '.') {
2384 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002385 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner3921e902012-10-06 23:05:00 +02002386 if (precision > (INT_MAX - ((int)*f - '0')) / 10) {
2387 PyErr_SetString(PyExc_ValueError,
2388 "precision too big");
2389 return NULL;
2390 }
Victor Stinnere215d962012-10-06 23:03:36 +02002391 precision = (precision*10) + (*f - '0');
2392 f++;
2393 }
Victor Stinner96865452011-03-01 23:44:09 +00002394 if (*f == '%') {
2395 /* "%.3%s" => f points to "3" */
2396 f--;
2397 }
2398 }
2399 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002400 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002401 f--;
2402 }
Victor Stinner96865452011-03-01 23:44:09 +00002403
2404 /* Handle %ld, %lu, %lld and %llu. */
2405 longflag = 0;
2406 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002407 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002408 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002409 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002410 longflag = 1;
2411 ++f;
2412 }
2413#ifdef HAVE_LONG_LONG
2414 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002415 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002416 longlongflag = 1;
2417 f += 2;
2418 }
2419#endif
2420 }
2421 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002422 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002423 size_tflag = 1;
2424 ++f;
2425 }
Victor Stinnere215d962012-10-06 23:03:36 +02002426
2427 if (f[1] == '\0')
2428 writer->overallocate = 0;
2429
2430 switch (*f) {
2431 case 'c':
2432 {
2433 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002434 if (ordinal < 0 || ordinal > MAX_UNICODE) {
2435 PyErr_SetString(PyExc_ValueError,
2436 "character argument not in range(0x110000)");
2437 return NULL;
2438 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002439 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002440 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002441 break;
2442 }
2443
2444 case 'i':
2445 case 'd':
2446 case 'u':
2447 case 'x':
2448 {
2449 /* used by sprintf */
2450 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002451 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinnere215d962012-10-06 23:03:36 +02002452
2453 if (*f == 'u') {
2454 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2455
2456 if (longflag)
2457 len = sprintf(buffer, fmt,
2458 va_arg(*vargs, unsigned long));
2459#ifdef HAVE_LONG_LONG
2460 else if (longlongflag)
2461 len = sprintf(buffer, fmt,
2462 va_arg(*vargs, unsigned PY_LONG_LONG));
2463#endif
2464 else if (size_tflag)
2465 len = sprintf(buffer, fmt,
2466 va_arg(*vargs, size_t));
2467 else
2468 len = sprintf(buffer, fmt,
2469 va_arg(*vargs, unsigned int));
2470 }
2471 else if (*f == 'x') {
2472 makefmt(fmt, 0, 0, 0, 'x');
2473 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2474 }
2475 else {
2476 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2477
2478 if (longflag)
2479 len = sprintf(buffer, fmt,
2480 va_arg(*vargs, long));
2481#ifdef HAVE_LONG_LONG
2482 else if (longlongflag)
2483 len = sprintf(buffer, fmt,
2484 va_arg(*vargs, PY_LONG_LONG));
2485#endif
2486 else if (size_tflag)
2487 len = sprintf(buffer, fmt,
2488 va_arg(*vargs, Py_ssize_t));
2489 else
2490 len = sprintf(buffer, fmt,
2491 va_arg(*vargs, int));
2492 }
2493 assert(len >= 0);
2494
Victor Stinnere215d962012-10-06 23:03:36 +02002495 if (precision < len)
2496 precision = len;
2497 if (width > precision) {
2498 Py_UCS4 fillchar;
2499 fill = width - precision;
2500 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002501 if (_PyUnicodeWriter_Prepare(writer, fill, fillchar) == -1)
2502 return NULL;
2503 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2504 return NULL;
2505 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002506 }
Victor Stinner15a11362012-10-06 23:48:20 +02002507 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002508 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002509 if (_PyUnicodeWriter_Prepare(writer, fill, '0') == -1)
2510 return NULL;
2511 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2512 return NULL;
2513 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002514 }
Victor Stinner15a11362012-10-06 23:48:20 +02002515 if (_PyUnicodeWriter_WriteCstr(writer, buffer, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002516 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002517 break;
2518 }
2519
2520 case 'p':
2521 {
2522 char number[MAX_LONG_LONG_CHARS];
2523
2524 len = sprintf(number, "%p", va_arg(*vargs, void*));
2525 assert(len >= 0);
2526
2527 /* %p is ill-defined: ensure leading 0x. */
2528 if (number[1] == 'X')
2529 number[1] = 'x';
2530 else if (number[1] != 'x') {
2531 memmove(number + 2, number,
2532 strlen(number) + 1);
2533 number[0] = '0';
2534 number[1] = 'x';
2535 len += 2;
2536 }
2537
2538 if (_PyUnicodeWriter_WriteCstr(writer, number, len) == -1)
2539 return NULL;
2540 break;
2541 }
2542
2543 case 's':
2544 {
2545 /* UTF-8 */
2546 const char *s = va_arg(*vargs, const char*);
2547 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
2548 if (!str)
2549 return NULL;
2550 if (_PyUnicodeWriter_WriteStr(writer, str) == -1) {
2551 Py_DECREF(str);
2552 return NULL;
2553 }
2554 Py_DECREF(str);
2555 break;
2556 }
2557
2558 case 'U':
2559 {
2560 PyObject *obj = va_arg(*vargs, PyObject *);
2561 assert(obj && _PyUnicode_CHECK(obj));
2562
2563 if (_PyUnicodeWriter_WriteStr(writer, obj) == -1)
2564 return NULL;
2565 break;
2566 }
2567
2568 case 'V':
2569 {
2570 PyObject *obj = va_arg(*vargs, PyObject *);
2571 const char *str = va_arg(*vargs, const char *);
2572 PyObject *str_obj;
2573 assert(obj || str);
2574 if (obj) {
2575 assert(_PyUnicode_CHECK(obj));
2576 if (_PyUnicodeWriter_WriteStr(writer, obj) == -1)
2577 return NULL;
2578 }
2579 else {
2580 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
2581 if (!str_obj)
2582 return NULL;
2583 if (_PyUnicodeWriter_WriteStr(writer, str_obj) == -1) {
2584 Py_DECREF(str_obj);
2585 return NULL;
2586 }
2587 Py_DECREF(str_obj);
2588 }
2589 break;
2590 }
2591
2592 case 'S':
2593 {
2594 PyObject *obj = va_arg(*vargs, PyObject *);
2595 PyObject *str;
2596 assert(obj);
2597 str = PyObject_Str(obj);
2598 if (!str)
2599 return NULL;
2600 if (_PyUnicodeWriter_WriteStr(writer, str) == -1) {
2601 Py_DECREF(str);
2602 return NULL;
2603 }
2604 Py_DECREF(str);
2605 break;
2606 }
2607
2608 case 'R':
2609 {
2610 PyObject *obj = va_arg(*vargs, PyObject *);
2611 PyObject *repr;
2612 assert(obj);
2613 repr = PyObject_Repr(obj);
2614 if (!repr)
2615 return NULL;
2616 if (_PyUnicodeWriter_WriteStr(writer, repr) == -1) {
2617 Py_DECREF(repr);
2618 return NULL;
2619 }
2620 Py_DECREF(repr);
2621 break;
2622 }
2623
2624 case 'A':
2625 {
2626 PyObject *obj = va_arg(*vargs, PyObject *);
2627 PyObject *ascii;
2628 assert(obj);
2629 ascii = PyObject_ASCII(obj);
2630 if (!ascii)
2631 return NULL;
2632 if (_PyUnicodeWriter_WriteStr(writer, ascii) == -1) {
2633 Py_DECREF(ascii);
2634 return NULL;
2635 }
2636 Py_DECREF(ascii);
2637 break;
2638 }
2639
2640 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002641 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002642 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002643 break;
2644
2645 default:
2646 /* if we stumble upon an unknown formatting code, copy the rest
2647 of the format string to the output string. (we cannot just
2648 skip the code, since there's no way to know what's in the
2649 argument list) */
2650 len = strlen(p);
2651 if (_PyUnicodeWriter_WriteCstr(writer, p, len) == -1)
2652 return NULL;
2653 f = p+len;
2654 return f;
2655 }
2656
2657 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002658 return f;
2659}
2660
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661PyObject *
2662PyUnicode_FromFormatV(const char *format, va_list vargs)
2663{
Victor Stinnere215d962012-10-06 23:03:36 +02002664 va_list vargs2;
2665 const char *f;
2666 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002667
Victor Stinner8f674cc2013-04-17 23:02:17 +02002668 _PyUnicodeWriter_Init(&writer);
2669 writer.min_length = strlen(format) + 100;
2670 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002671
2672 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2673 Copy it to be able to pass a reference to a subfunction. */
2674 Py_VA_COPY(vargs2, vargs);
2675
2676 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002677 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002678 f = unicode_fromformat_arg(&writer, f, &vargs2);
2679 if (f == NULL)
2680 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002682 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002683 const char *p;
2684 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002685
Victor Stinnere215d962012-10-06 23:03:36 +02002686 p = f;
2687 do
2688 {
2689 if ((unsigned char)*p > 127) {
2690 PyErr_Format(PyExc_ValueError,
2691 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2692 "string, got a non-ASCII byte: 0x%02x",
2693 (unsigned char)*p);
2694 return NULL;
2695 }
2696 p++;
2697 }
2698 while (*p != '\0' && *p != '%');
2699 len = p - f;
2700
2701 if (*p == '\0')
2702 writer.overallocate = 0;
2703 if (_PyUnicodeWriter_Prepare(&writer, len, 127) == -1)
2704 goto fail;
2705 unicode_write_cstr(writer.buffer, writer.pos, f, len);
2706 writer.pos += len;
2707
2708 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002709 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002710 }
Victor Stinnere215d962012-10-06 23:03:36 +02002711 return _PyUnicodeWriter_Finish(&writer);
2712
2713 fail:
2714 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002715 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002716}
2717
Walter Dörwaldd2034312007-05-18 16:29:38 +00002718PyObject *
2719PyUnicode_FromFormat(const char *format, ...)
2720{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002721 PyObject* ret;
2722 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002723
2724#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002725 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002726#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002727 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002728#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002729 ret = PyUnicode_FromFormatV(format, vargs);
2730 va_end(vargs);
2731 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002732}
2733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734#ifdef HAVE_WCHAR_H
2735
Victor Stinner5593d8a2010-10-02 11:11:27 +00002736/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2737 convert a Unicode object to a wide character string.
2738
Victor Stinnerd88d9832011-09-06 02:00:05 +02002739 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002740 character) required to convert the unicode object. Ignore size argument.
2741
Victor Stinnerd88d9832011-09-06 02:00:05 +02002742 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002743 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002744 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002745static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002746unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002747 wchar_t *w,
2748 Py_ssize_t size)
2749{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002750 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002751 const wchar_t *wstr;
2752
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002753 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002754 if (wstr == NULL)
2755 return -1;
2756
Victor Stinner5593d8a2010-10-02 11:11:27 +00002757 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002758 if (size > res)
2759 size = res + 1;
2760 else
2761 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002762 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002763 return res;
2764 }
2765 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002766 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002767}
2768
2769Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002770PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002771 wchar_t *w,
2772 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002773{
2774 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002775 PyErr_BadInternalCall();
2776 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002778 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002779}
2780
Victor Stinner137c34c2010-09-29 10:25:54 +00002781wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002782PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002783 Py_ssize_t *size)
2784{
2785 wchar_t* buffer;
2786 Py_ssize_t buflen;
2787
2788 if (unicode == NULL) {
2789 PyErr_BadInternalCall();
2790 return NULL;
2791 }
2792
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002793 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002794 if (buflen == -1)
2795 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002796 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002797 PyErr_NoMemory();
2798 return NULL;
2799 }
2800
Victor Stinner137c34c2010-09-29 10:25:54 +00002801 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2802 if (buffer == NULL) {
2803 PyErr_NoMemory();
2804 return NULL;
2805 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002806 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002807 if (buflen == -1) {
2808 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002809 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002810 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002811 if (size != NULL)
2812 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002813 return buffer;
2814}
2815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002816#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002817
Alexander Belopolsky40018472011-02-26 01:02:56 +00002818PyObject *
2819PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002820{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 PyObject *v;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002822 void *data;
2823 int kind;
2824
Victor Stinner8faf8212011-12-08 22:14:11 +01002825 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002826 PyErr_SetString(PyExc_ValueError,
2827 "chr() arg not in range(0x110000)");
2828 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002829 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002830
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002831 if ((Py_UCS4)ordinal < 256)
2832 return get_latin1_char((unsigned char)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002834 v = PyUnicode_New(1, ordinal);
2835 if (v == NULL)
2836 return NULL;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002837 kind = PyUnicode_KIND(v);
2838 data = PyUnicode_DATA(v);
2839 PyUnicode_WRITE(kind, data, 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002840 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002842}
2843
Alexander Belopolsky40018472011-02-26 01:02:56 +00002844PyObject *
2845PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002846{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002847 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002848 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002849 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002850 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002851 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002852 Py_INCREF(obj);
2853 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002854 }
2855 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002856 /* For a Unicode subtype that's not a Unicode object,
2857 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002858 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002859 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002860 PyErr_Format(PyExc_TypeError,
2861 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002862 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002863 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002864}
2865
Alexander Belopolsky40018472011-02-26 01:02:56 +00002866PyObject *
2867PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002868 const char *encoding,
2869 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002870{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002871 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002872 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002873
Guido van Rossumd57fd912000-03-10 22:53:23 +00002874 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002875 PyErr_BadInternalCall();
2876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002877 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002878
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002879 /* Decoding bytes objects is the most common case and should be fast */
2880 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002881 if (PyBytes_GET_SIZE(obj) == 0)
2882 _Py_RETURN_UNICODE_EMPTY();
2883 v = PyUnicode_Decode(
2884 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2885 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002886 return v;
2887 }
2888
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002889 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002890 PyErr_SetString(PyExc_TypeError,
2891 "decoding str is not supported");
2892 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002893 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002895 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2896 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2897 PyErr_Format(PyExc_TypeError,
2898 "coercing to str: need bytes, bytearray "
2899 "or buffer-like object, %.80s found",
2900 Py_TYPE(obj)->tp_name);
2901 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002902 }
Tim Petersced69f82003-09-16 20:30:58 +00002903
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002904 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002905 PyBuffer_Release(&buffer);
2906 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002908
Serhiy Storchaka05997252013-01-26 12:14:02 +02002909 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002910 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002911 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002912}
2913
Victor Stinner600d3be2010-06-10 12:00:55 +00002914/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002915 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2916 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002917int
2918_Py_normalize_encoding(const char *encoding,
2919 char *lower,
2920 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002922 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002923 char *l;
2924 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002925
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002926 if (encoding == NULL) {
2927 strcpy(lower, "utf-8");
2928 return 1;
2929 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002930 e = encoding;
2931 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002932 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002933 while (*e) {
2934 if (l == l_end)
2935 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002936 if (Py_ISUPPER(*e)) {
2937 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002938 }
2939 else if (*e == '_') {
2940 *l++ = '-';
2941 e++;
2942 }
2943 else {
2944 *l++ = *e++;
2945 }
2946 }
2947 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002948 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002949}
2950
Alexander Belopolsky40018472011-02-26 01:02:56 +00002951PyObject *
2952PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002953 Py_ssize_t size,
2954 const char *encoding,
2955 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002956{
2957 PyObject *buffer = NULL, *unicode;
2958 Py_buffer info;
2959 char lower[11]; /* Enough for any encoding shortcut */
2960
Fred Drakee4315f52000-05-09 19:53:39 +00002961 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002962 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002963 if ((strcmp(lower, "utf-8") == 0) ||
2964 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002965 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002966 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002967 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002968 (strcmp(lower, "iso-8859-1") == 0))
2969 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002970#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002971 else if (strcmp(lower, "mbcs") == 0)
2972 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002973#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002974 else if (strcmp(lower, "ascii") == 0)
2975 return PyUnicode_DecodeASCII(s, size, errors);
2976 else if (strcmp(lower, "utf-16") == 0)
2977 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2978 else if (strcmp(lower, "utf-32") == 0)
2979 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2980 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002981
2982 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002983 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002984 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002985 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002986 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002987 if (buffer == NULL)
2988 goto onError;
2989 unicode = PyCodec_Decode(buffer, encoding, errors);
2990 if (unicode == NULL)
2991 goto onError;
2992 if (!PyUnicode_Check(unicode)) {
2993 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002994 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002995 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002996 Py_DECREF(unicode);
2997 goto onError;
2998 }
2999 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003000 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003001
Benjamin Peterson29060642009-01-31 22:14:21 +00003002 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003003 Py_XDECREF(buffer);
3004 return NULL;
3005}
3006
Alexander Belopolsky40018472011-02-26 01:02:56 +00003007PyObject *
3008PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003009 const char *encoding,
3010 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003011{
3012 PyObject *v;
3013
3014 if (!PyUnicode_Check(unicode)) {
3015 PyErr_BadArgument();
3016 goto onError;
3017 }
3018
3019 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003021
3022 /* Decode via the codec registry */
3023 v = PyCodec_Decode(unicode, encoding, errors);
3024 if (v == NULL)
3025 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003026 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003027
Benjamin Peterson29060642009-01-31 22:14:21 +00003028 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003029 return NULL;
3030}
3031
Alexander Belopolsky40018472011-02-26 01:02:56 +00003032PyObject *
3033PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003034 const char *encoding,
3035 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003036{
3037 PyObject *v;
3038
3039 if (!PyUnicode_Check(unicode)) {
3040 PyErr_BadArgument();
3041 goto onError;
3042 }
3043
3044 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003045 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003046
3047 /* Decode via the codec registry */
3048 v = PyCodec_Decode(unicode, encoding, errors);
3049 if (v == NULL)
3050 goto onError;
3051 if (!PyUnicode_Check(v)) {
3052 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003053 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003054 Py_TYPE(v)->tp_name);
3055 Py_DECREF(v);
3056 goto onError;
3057 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003058 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003059
Benjamin Peterson29060642009-01-31 22:14:21 +00003060 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003061 return NULL;
3062}
3063
Alexander Belopolsky40018472011-02-26 01:02:56 +00003064PyObject *
3065PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003066 Py_ssize_t size,
3067 const char *encoding,
3068 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003069{
3070 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003071
Guido van Rossumd57fd912000-03-10 22:53:23 +00003072 unicode = PyUnicode_FromUnicode(s, size);
3073 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003074 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003075 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3076 Py_DECREF(unicode);
3077 return v;
3078}
3079
Alexander Belopolsky40018472011-02-26 01:02:56 +00003080PyObject *
3081PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003082 const char *encoding,
3083 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003084{
3085 PyObject *v;
3086
3087 if (!PyUnicode_Check(unicode)) {
3088 PyErr_BadArgument();
3089 goto onError;
3090 }
3091
3092 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003093 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003094
3095 /* Encode via the codec registry */
3096 v = PyCodec_Encode(unicode, encoding, errors);
3097 if (v == NULL)
3098 goto onError;
3099 return v;
3100
Benjamin Peterson29060642009-01-31 22:14:21 +00003101 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003102 return NULL;
3103}
3104
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003105static size_t
3106wcstombs_errorpos(const wchar_t *wstr)
3107{
3108 size_t len;
3109#if SIZEOF_WCHAR_T == 2
3110 wchar_t buf[3];
3111#else
3112 wchar_t buf[2];
3113#endif
3114 char outbuf[MB_LEN_MAX];
3115 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003116
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003117#if SIZEOF_WCHAR_T == 2
3118 buf[2] = 0;
3119#else
3120 buf[1] = 0;
3121#endif
3122 start = wstr;
3123 while (*wstr != L'\0')
3124 {
3125 previous = wstr;
3126#if SIZEOF_WCHAR_T == 2
3127 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3128 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3129 {
3130 buf[0] = wstr[0];
3131 buf[1] = wstr[1];
3132 wstr += 2;
3133 }
3134 else {
3135 buf[0] = *wstr;
3136 buf[1] = 0;
3137 wstr++;
3138 }
3139#else
3140 buf[0] = *wstr;
3141 wstr++;
3142#endif
3143 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003144 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003145 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003146 }
3147
3148 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003149 return 0;
3150}
3151
Victor Stinner1b579672011-12-17 05:47:23 +01003152static int
3153locale_error_handler(const char *errors, int *surrogateescape)
3154{
3155 if (errors == NULL) {
3156 *surrogateescape = 0;
3157 return 0;
3158 }
3159
3160 if (strcmp(errors, "strict") == 0) {
3161 *surrogateescape = 0;
3162 return 0;
3163 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003164 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003165 *surrogateescape = 1;
3166 return 0;
3167 }
3168 PyErr_Format(PyExc_ValueError,
3169 "only 'strict' and 'surrogateescape' error handlers "
3170 "are supported, not '%s'",
3171 errors);
3172 return -1;
3173}
3174
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003175PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003176PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003177{
3178 Py_ssize_t wlen, wlen2;
3179 wchar_t *wstr;
3180 PyObject *bytes = NULL;
3181 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003182 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183 PyObject *exc;
3184 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003185 int surrogateescape;
3186
3187 if (locale_error_handler(errors, &surrogateescape) < 0)
3188 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003189
3190 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3191 if (wstr == NULL)
3192 return NULL;
3193
3194 wlen2 = wcslen(wstr);
3195 if (wlen2 != wlen) {
3196 PyMem_Free(wstr);
3197 PyErr_SetString(PyExc_TypeError, "embedded null character");
3198 return NULL;
3199 }
3200
3201 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003202 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003203 char *str;
3204
3205 str = _Py_wchar2char(wstr, &error_pos);
3206 if (str == NULL) {
3207 if (error_pos == (size_t)-1) {
3208 PyErr_NoMemory();
3209 PyMem_Free(wstr);
3210 return NULL;
3211 }
3212 else {
3213 goto encode_error;
3214 }
3215 }
3216 PyMem_Free(wstr);
3217
3218 bytes = PyBytes_FromString(str);
3219 PyMem_Free(str);
3220 }
3221 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003222 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223 size_t len, len2;
3224
3225 len = wcstombs(NULL, wstr, 0);
3226 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003227 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003228 goto encode_error;
3229 }
3230
3231 bytes = PyBytes_FromStringAndSize(NULL, len);
3232 if (bytes == NULL) {
3233 PyMem_Free(wstr);
3234 return NULL;
3235 }
3236
3237 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3238 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003239 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003240 goto encode_error;
3241 }
3242 PyMem_Free(wstr);
3243 }
3244 return bytes;
3245
3246encode_error:
3247 errmsg = strerror(errno);
3248 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003249
3250 if (error_pos == (size_t)-1)
3251 error_pos = wcstombs_errorpos(wstr);
3252
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003253 PyMem_Free(wstr);
3254 Py_XDECREF(bytes);
3255
Victor Stinner2f197072011-12-17 07:08:30 +01003256 if (errmsg != NULL) {
3257 size_t errlen;
3258 wstr = _Py_char2wchar(errmsg, &errlen);
3259 if (wstr != NULL) {
3260 reason = PyUnicode_FromWideChar(wstr, errlen);
3261 PyMem_Free(wstr);
3262 } else
3263 errmsg = NULL;
3264 }
3265 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003266 reason = PyUnicode_FromString(
3267 "wcstombs() encountered an unencodable "
3268 "wide character");
3269 if (reason == NULL)
3270 return NULL;
3271
3272 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3273 "locale", unicode,
3274 (Py_ssize_t)error_pos,
3275 (Py_ssize_t)(error_pos+1),
3276 reason);
3277 Py_DECREF(reason);
3278 if (exc != NULL) {
3279 PyCodec_StrictErrors(exc);
3280 Py_XDECREF(exc);
3281 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003282 return NULL;
3283}
3284
Victor Stinnerad158722010-10-27 00:25:46 +00003285PyObject *
3286PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003287{
Victor Stinner99b95382011-07-04 14:23:54 +02003288#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003289 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003290#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003291 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003292#else
Victor Stinner793b5312011-04-27 00:24:21 +02003293 PyInterpreterState *interp = PyThreadState_GET()->interp;
3294 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3295 cannot use it to encode and decode filenames before it is loaded. Load
3296 the Python codec requires to encode at least its own filename. Use the C
3297 version of the locale codec until the codec registry is initialized and
3298 the Python codec is loaded.
3299
3300 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3301 cannot only rely on it: check also interp->fscodec_initialized for
3302 subinterpreters. */
3303 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003304 return PyUnicode_AsEncodedString(unicode,
3305 Py_FileSystemDefaultEncoding,
3306 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003307 }
3308 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003309 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003310 }
Victor Stinnerad158722010-10-27 00:25:46 +00003311#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003312}
3313
Alexander Belopolsky40018472011-02-26 01:02:56 +00003314PyObject *
3315PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003316 const char *encoding,
3317 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003318{
3319 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003320 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003321
Guido van Rossumd57fd912000-03-10 22:53:23 +00003322 if (!PyUnicode_Check(unicode)) {
3323 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003324 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003325 }
Fred Drakee4315f52000-05-09 19:53:39 +00003326
Fred Drakee4315f52000-05-09 19:53:39 +00003327 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003328 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003329 if ((strcmp(lower, "utf-8") == 0) ||
3330 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003331 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003332 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003333 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003334 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003335 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003336 }
Victor Stinner37296e82010-06-10 13:36:23 +00003337 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003338 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003339 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003340 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003341#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003342 else if (strcmp(lower, "mbcs") == 0)
3343 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003344#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003345 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003346 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003347 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003348
3349 /* Encode via the codec registry */
3350 v = PyCodec_Encode(unicode, encoding, errors);
3351 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003352 return NULL;
3353
3354 /* The normal path */
3355 if (PyBytes_Check(v))
3356 return v;
3357
3358 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003359 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003360 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003361 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003362
3363 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3364 "encoder %s returned bytearray instead of bytes",
3365 encoding);
3366 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003367 Py_DECREF(v);
3368 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003369 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003370
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003371 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3372 Py_DECREF(v);
3373 return b;
3374 }
3375
3376 PyErr_Format(PyExc_TypeError,
3377 "encoder did not return a bytes object (type=%.400s)",
3378 Py_TYPE(v)->tp_name);
3379 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003380 return NULL;
3381}
3382
Alexander Belopolsky40018472011-02-26 01:02:56 +00003383PyObject *
3384PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003385 const char *encoding,
3386 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003387{
3388 PyObject *v;
3389
3390 if (!PyUnicode_Check(unicode)) {
3391 PyErr_BadArgument();
3392 goto onError;
3393 }
3394
3395 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003396 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003397
3398 /* Encode via the codec registry */
3399 v = PyCodec_Encode(unicode, encoding, errors);
3400 if (v == NULL)
3401 goto onError;
3402 if (!PyUnicode_Check(v)) {
3403 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003404 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003405 Py_TYPE(v)->tp_name);
3406 Py_DECREF(v);
3407 goto onError;
3408 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003409 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003410
Benjamin Peterson29060642009-01-31 22:14:21 +00003411 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003412 return NULL;
3413}
3414
Victor Stinner2f197072011-12-17 07:08:30 +01003415static size_t
3416mbstowcs_errorpos(const char *str, size_t len)
3417{
3418#ifdef HAVE_MBRTOWC
3419 const char *start = str;
3420 mbstate_t mbs;
3421 size_t converted;
3422 wchar_t ch;
3423
3424 memset(&mbs, 0, sizeof mbs);
3425 while (len)
3426 {
3427 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3428 if (converted == 0)
3429 /* Reached end of string */
3430 break;
3431 if (converted == (size_t)-1 || converted == (size_t)-2) {
3432 /* Conversion error or incomplete character */
3433 return str - start;
3434 }
3435 else {
3436 str += converted;
3437 len -= converted;
3438 }
3439 }
3440 /* failed to find the undecodable byte sequence */
3441 return 0;
3442#endif
3443 return 0;
3444}
3445
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003446PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003447PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003448 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003449{
3450 wchar_t smallbuf[256];
3451 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3452 wchar_t *wstr;
3453 size_t wlen, wlen2;
3454 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003455 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003456 size_t error_pos;
3457 char *errmsg;
3458 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003459
3460 if (locale_error_handler(errors, &surrogateescape) < 0)
3461 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003462
3463 if (str[len] != '\0' || len != strlen(str)) {
3464 PyErr_SetString(PyExc_TypeError, "embedded null character");
3465 return NULL;
3466 }
3467
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003468 if (surrogateescape) {
3469 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003470 wstr = _Py_char2wchar(str, &wlen);
3471 if (wstr == NULL) {
3472 if (wlen == (size_t)-1)
3473 PyErr_NoMemory();
3474 else
3475 PyErr_SetFromErrno(PyExc_OSError);
3476 return NULL;
3477 }
3478
3479 unicode = PyUnicode_FromWideChar(wstr, wlen);
3480 PyMem_Free(wstr);
3481 }
3482 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003483 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003484#ifndef HAVE_BROKEN_MBSTOWCS
3485 wlen = mbstowcs(NULL, str, 0);
3486#else
3487 wlen = len;
3488#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003489 if (wlen == (size_t)-1)
3490 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003491 if (wlen+1 <= smallbuf_len) {
3492 wstr = smallbuf;
3493 }
3494 else {
3495 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3496 return PyErr_NoMemory();
3497
3498 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3499 if (!wstr)
3500 return PyErr_NoMemory();
3501 }
3502
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003503 wlen2 = mbstowcs(wstr, str, wlen+1);
3504 if (wlen2 == (size_t)-1) {
3505 if (wstr != smallbuf)
3506 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003507 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003508 }
3509#ifdef HAVE_BROKEN_MBSTOWCS
3510 assert(wlen2 == wlen);
3511#endif
3512 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3513 if (wstr != smallbuf)
3514 PyMem_Free(wstr);
3515 }
3516 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003517
3518decode_error:
3519 errmsg = strerror(errno);
3520 assert(errmsg != NULL);
3521
3522 error_pos = mbstowcs_errorpos(str, len);
3523 if (errmsg != NULL) {
3524 size_t errlen;
3525 wstr = _Py_char2wchar(errmsg, &errlen);
3526 if (wstr != NULL) {
3527 reason = PyUnicode_FromWideChar(wstr, errlen);
3528 PyMem_Free(wstr);
3529 } else
3530 errmsg = NULL;
3531 }
3532 if (errmsg == NULL)
3533 reason = PyUnicode_FromString(
3534 "mbstowcs() encountered an invalid multibyte sequence");
3535 if (reason == NULL)
3536 return NULL;
3537
3538 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3539 "locale", str, len,
3540 (Py_ssize_t)error_pos,
3541 (Py_ssize_t)(error_pos+1),
3542 reason);
3543 Py_DECREF(reason);
3544 if (exc != NULL) {
3545 PyCodec_StrictErrors(exc);
3546 Py_XDECREF(exc);
3547 }
3548 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549}
3550
3551PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003552PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003553{
3554 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003555 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003556}
3557
3558
3559PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003560PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003561 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003562 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3563}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003564
Christian Heimes5894ba72007-11-04 11:43:14 +00003565PyObject*
3566PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3567{
Victor Stinner99b95382011-07-04 14:23:54 +02003568#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003569 return PyUnicode_DecodeMBCS(s, size, NULL);
3570#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003571 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003572#else
Victor Stinner793b5312011-04-27 00:24:21 +02003573 PyInterpreterState *interp = PyThreadState_GET()->interp;
3574 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3575 cannot use it to encode and decode filenames before it is loaded. Load
3576 the Python codec requires to encode at least its own filename. Use the C
3577 version of the locale codec until the codec registry is initialized and
3578 the Python codec is loaded.
3579
3580 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3581 cannot only rely on it: check also interp->fscodec_initialized for
3582 subinterpreters. */
3583 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003584 return PyUnicode_Decode(s, size,
3585 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003586 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003587 }
3588 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003589 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003590 }
Victor Stinnerad158722010-10-27 00:25:46 +00003591#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003592}
3593
Martin v. Löwis011e8422009-05-05 04:43:17 +00003594
3595int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003596_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003597{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003598 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003599
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003600 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003601 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003602 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3603 PyUnicode_GET_LENGTH(str), '\0', 1);
3604 if (pos == -1)
3605 return 0;
3606 else
3607 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003608}
3609
Antoine Pitrou13348842012-01-29 18:36:34 +01003610int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003611PyUnicode_FSConverter(PyObject* arg, void* addr)
3612{
3613 PyObject *output = NULL;
3614 Py_ssize_t size;
3615 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003616 if (arg == NULL) {
3617 Py_DECREF(*(PyObject**)addr);
3618 return 1;
3619 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003620 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003621 output = arg;
3622 Py_INCREF(output);
3623 }
3624 else {
3625 arg = PyUnicode_FromObject(arg);
3626 if (!arg)
3627 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003628 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003629 Py_DECREF(arg);
3630 if (!output)
3631 return 0;
3632 if (!PyBytes_Check(output)) {
3633 Py_DECREF(output);
3634 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3635 return 0;
3636 }
3637 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003638 size = PyBytes_GET_SIZE(output);
3639 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003640 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003641 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003642 Py_DECREF(output);
3643 return 0;
3644 }
3645 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003646 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003647}
3648
3649
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003650int
3651PyUnicode_FSDecoder(PyObject* arg, void* addr)
3652{
3653 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003654 if (arg == NULL) {
3655 Py_DECREF(*(PyObject**)addr);
3656 return 1;
3657 }
3658 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003659 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003660 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003661 output = arg;
3662 Py_INCREF(output);
3663 }
3664 else {
3665 arg = PyBytes_FromObject(arg);
3666 if (!arg)
3667 return 0;
3668 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3669 PyBytes_GET_SIZE(arg));
3670 Py_DECREF(arg);
3671 if (!output)
3672 return 0;
3673 if (!PyUnicode_Check(output)) {
3674 Py_DECREF(output);
3675 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3676 return 0;
3677 }
3678 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003679 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003680 Py_DECREF(output);
3681 return 0;
3682 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003683 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003684 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003685 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3686 Py_DECREF(output);
3687 return 0;
3688 }
3689 *(PyObject**)addr = output;
3690 return Py_CLEANUP_SUPPORTED;
3691}
3692
3693
Martin v. Löwis5b222132007-06-10 09:51:05 +00003694char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003696{
Christian Heimesf3863112007-11-22 07:46:41 +00003697 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003698
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003699 if (!PyUnicode_Check(unicode)) {
3700 PyErr_BadArgument();
3701 return NULL;
3702 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003703 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003704 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003705
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003706 if (PyUnicode_UTF8(unicode) == NULL) {
3707 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003708 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3709 if (bytes == NULL)
3710 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003711 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3712 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003713 Py_DECREF(bytes);
3714 return NULL;
3715 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003716 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3717 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3718 PyBytes_AS_STRING(bytes),
3719 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003720 Py_DECREF(bytes);
3721 }
3722
3723 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003724 *psize = PyUnicode_UTF8_LENGTH(unicode);
3725 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003726}
3727
3728char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003729PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003730{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003731 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3732}
3733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003734Py_UNICODE *
3735PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3736{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003737 const unsigned char *one_byte;
3738#if SIZEOF_WCHAR_T == 4
3739 const Py_UCS2 *two_bytes;
3740#else
3741 const Py_UCS4 *four_bytes;
3742 const Py_UCS4 *ucs4_end;
3743 Py_ssize_t num_surrogates;
3744#endif
3745 wchar_t *w;
3746 wchar_t *wchar_end;
3747
3748 if (!PyUnicode_Check(unicode)) {
3749 PyErr_BadArgument();
3750 return NULL;
3751 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003752 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003753 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003754 assert(_PyUnicode_KIND(unicode) != 0);
3755 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003757 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003758#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003759 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3760 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761 num_surrogates = 0;
3762
3763 for (; four_bytes < ucs4_end; ++four_bytes) {
3764 if (*four_bytes > 0xFFFF)
3765 ++num_surrogates;
3766 }
3767
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003768 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3769 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3770 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771 PyErr_NoMemory();
3772 return NULL;
3773 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003774 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003775
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 w = _PyUnicode_WSTR(unicode);
3777 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3778 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3780 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003781 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003782 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003783 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3784 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785 }
3786 else
3787 *w = *four_bytes;
3788
3789 if (w > wchar_end) {
3790 assert(0 && "Miscalculated string end");
3791 }
3792 }
3793 *w = 0;
3794#else
3795 /* sizeof(wchar_t) == 4 */
3796 Py_FatalError("Impossible unicode object state, wstr and str "
3797 "should share memory already.");
3798 return NULL;
3799#endif
3800 }
3801 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003802 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3803 (_PyUnicode_LENGTH(unicode) + 1));
3804 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805 PyErr_NoMemory();
3806 return NULL;
3807 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3809 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3810 w = _PyUnicode_WSTR(unicode);
3811 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003813 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3814 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815 for (; w < wchar_end; ++one_byte, ++w)
3816 *w = *one_byte;
3817 /* null-terminate the wstr */
3818 *w = 0;
3819 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003820 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003821#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003822 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823 for (; w < wchar_end; ++two_bytes, ++w)
3824 *w = *two_bytes;
3825 /* null-terminate the wstr */
3826 *w = 0;
3827#else
3828 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003829 PyObject_FREE(_PyUnicode_WSTR(unicode));
3830 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003831 Py_FatalError("Impossible unicode object state, wstr "
3832 "and str should share memory already.");
3833 return NULL;
3834#endif
3835 }
3836 else {
3837 assert(0 && "This should never happen.");
3838 }
3839 }
3840 }
3841 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 *size = PyUnicode_WSTR_LENGTH(unicode);
3843 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003844}
3845
Alexander Belopolsky40018472011-02-26 01:02:56 +00003846Py_UNICODE *
3847PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003848{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003850}
3851
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003852
Alexander Belopolsky40018472011-02-26 01:02:56 +00003853Py_ssize_t
3854PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003855{
3856 if (!PyUnicode_Check(unicode)) {
3857 PyErr_BadArgument();
3858 goto onError;
3859 }
3860 return PyUnicode_GET_SIZE(unicode);
3861
Benjamin Peterson29060642009-01-31 22:14:21 +00003862 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003863 return -1;
3864}
3865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866Py_ssize_t
3867PyUnicode_GetLength(PyObject *unicode)
3868{
Victor Stinner07621332012-06-16 04:53:46 +02003869 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003870 PyErr_BadArgument();
3871 return -1;
3872 }
Victor Stinner07621332012-06-16 04:53:46 +02003873 if (PyUnicode_READY(unicode) == -1)
3874 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 return PyUnicode_GET_LENGTH(unicode);
3876}
3877
3878Py_UCS4
3879PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3880{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003881 void *data;
3882 int kind;
3883
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003884 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3885 PyErr_BadArgument();
3886 return (Py_UCS4)-1;
3887 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003888 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003889 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 return (Py_UCS4)-1;
3891 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003892 data = PyUnicode_DATA(unicode);
3893 kind = PyUnicode_KIND(unicode);
3894 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003895}
3896
3897int
3898PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3899{
3900 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003901 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 return -1;
3903 }
Victor Stinner488fa492011-12-12 00:01:39 +01003904 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003905 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003906 PyErr_SetString(PyExc_IndexError, "string index out of range");
3907 return -1;
3908 }
Victor Stinner488fa492011-12-12 00:01:39 +01003909 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003910 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003911 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3912 PyErr_SetString(PyExc_ValueError, "character out of range");
3913 return -1;
3914 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003915 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3916 index, ch);
3917 return 0;
3918}
3919
Alexander Belopolsky40018472011-02-26 01:02:56 +00003920const char *
3921PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003922{
Victor Stinner42cb4622010-09-01 19:39:01 +00003923 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003924}
3925
Victor Stinner554f3f02010-06-16 23:33:54 +00003926/* create or adjust a UnicodeDecodeError */
3927static void
3928make_decode_exception(PyObject **exceptionObject,
3929 const char *encoding,
3930 const char *input, Py_ssize_t length,
3931 Py_ssize_t startpos, Py_ssize_t endpos,
3932 const char *reason)
3933{
3934 if (*exceptionObject == NULL) {
3935 *exceptionObject = PyUnicodeDecodeError_Create(
3936 encoding, input, length, startpos, endpos, reason);
3937 }
3938 else {
3939 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3940 goto onError;
3941 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3942 goto onError;
3943 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3944 goto onError;
3945 }
3946 return;
3947
3948onError:
3949 Py_DECREF(*exceptionObject);
3950 *exceptionObject = NULL;
3951}
3952
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003953#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003954/* error handling callback helper:
3955 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003956 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003957 and adjust various state variables.
3958 return 0 on success, -1 on error
3959*/
3960
Alexander Belopolsky40018472011-02-26 01:02:56 +00003961static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003962unicode_decode_call_errorhandler_wchar(
3963 const char *errors, PyObject **errorHandler,
3964 const char *encoding, const char *reason,
3965 const char **input, const char **inend, Py_ssize_t *startinpos,
3966 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3967 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003968{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003969 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003970
3971 PyObject *restuple = NULL;
3972 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003973 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003974 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003975 Py_ssize_t requiredsize;
3976 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003977 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003978 wchar_t *repwstr;
3979 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003980
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003981 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3982 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01003983
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003984 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003985 *errorHandler = PyCodec_LookupError(errors);
3986 if (*errorHandler == NULL)
3987 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003988 }
3989
Victor Stinner554f3f02010-06-16 23:33:54 +00003990 make_decode_exception(exceptionObject,
3991 encoding,
3992 *input, *inend - *input,
3993 *startinpos, *endinpos,
3994 reason);
3995 if (*exceptionObject == NULL)
3996 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003997
3998 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3999 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004000 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004001 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004002 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004003 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004004 }
4005 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004006 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004007
4008 /* Copy back the bytes variables, which might have been modified by the
4009 callback */
4010 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4011 if (!inputobj)
4012 goto onError;
4013 if (!PyBytes_Check(inputobj)) {
4014 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4015 }
4016 *input = PyBytes_AS_STRING(inputobj);
4017 insize = PyBytes_GET_SIZE(inputobj);
4018 *inend = *input + insize;
4019 /* we can DECREF safely, as the exception has another reference,
4020 so the object won't go away. */
4021 Py_DECREF(inputobj);
4022
4023 if (newpos<0)
4024 newpos = insize+newpos;
4025 if (newpos<0 || newpos>insize) {
4026 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4027 goto onError;
4028 }
4029
4030 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4031 if (repwstr == NULL)
4032 goto onError;
4033 /* need more space? (at least enough for what we
4034 have+the replacement+the rest of the string (starting
4035 at the new input position), so we won't have to check space
4036 when there are no errors in the rest of the string) */
4037 requiredsize = *outpos + repwlen + insize-newpos;
4038 if (requiredsize > outsize) {
4039 if (requiredsize < 2*outsize)
4040 requiredsize = 2*outsize;
4041 if (unicode_resize(output, requiredsize) < 0)
4042 goto onError;
4043 }
4044 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4045 *outpos += repwlen;
4046
4047 *endinpos = newpos;
4048 *inptr = *input + newpos;
4049
4050 /* we made it! */
4051 Py_XDECREF(restuple);
4052 return 0;
4053
4054 onError:
4055 Py_XDECREF(restuple);
4056 return -1;
4057}
4058#endif /* HAVE_MBCS */
4059
4060static int
4061unicode_decode_call_errorhandler_writer(
4062 const char *errors, PyObject **errorHandler,
4063 const char *encoding, const char *reason,
4064 const char **input, const char **inend, Py_ssize_t *startinpos,
4065 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4066 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4067{
4068 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4069
4070 PyObject *restuple = NULL;
4071 PyObject *repunicode = NULL;
4072 Py_ssize_t insize;
4073 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004074 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004075 PyObject *inputobj = NULL;
4076
4077 if (*errorHandler == NULL) {
4078 *errorHandler = PyCodec_LookupError(errors);
4079 if (*errorHandler == NULL)
4080 goto onError;
4081 }
4082
4083 make_decode_exception(exceptionObject,
4084 encoding,
4085 *input, *inend - *input,
4086 *startinpos, *endinpos,
4087 reason);
4088 if (*exceptionObject == NULL)
4089 goto onError;
4090
4091 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4092 if (restuple == NULL)
4093 goto onError;
4094 if (!PyTuple_Check(restuple)) {
4095 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4096 goto onError;
4097 }
4098 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004099 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004100
4101 /* Copy back the bytes variables, which might have been modified by the
4102 callback */
4103 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4104 if (!inputobj)
4105 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004106 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004107 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004108 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004109 *input = PyBytes_AS_STRING(inputobj);
4110 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004111 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004112 /* we can DECREF safely, as the exception has another reference,
4113 so the object won't go away. */
4114 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004115
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004116 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004117 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004118 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004119 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4120 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004121 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004122
Victor Stinner8f674cc2013-04-17 23:02:17 +02004123 if (PyUnicode_READY(repunicode) < 0)
4124 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004125 replen = PyUnicode_GET_LENGTH(repunicode);
4126 writer->min_length += replen;
4127 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004128 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004129 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004130 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004131
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004132 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004133 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004134
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004136 Py_XDECREF(restuple);
4137 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004138
Benjamin Peterson29060642009-01-31 22:14:21 +00004139 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004140 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004141 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004142}
4143
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004144/* --- UTF-7 Codec -------------------------------------------------------- */
4145
Antoine Pitrou244651a2009-05-04 18:56:13 +00004146/* See RFC2152 for details. We encode conservatively and decode liberally. */
4147
4148/* Three simple macros defining base-64. */
4149
4150/* Is c a base-64 character? */
4151
4152#define IS_BASE64(c) \
4153 (((c) >= 'A' && (c) <= 'Z') || \
4154 ((c) >= 'a' && (c) <= 'z') || \
4155 ((c) >= '0' && (c) <= '9') || \
4156 (c) == '+' || (c) == '/')
4157
4158/* given that c is a base-64 character, what is its base-64 value? */
4159
4160#define FROM_BASE64(c) \
4161 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4162 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4163 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4164 (c) == '+' ? 62 : 63)
4165
4166/* What is the base-64 character of the bottom 6 bits of n? */
4167
4168#define TO_BASE64(n) \
4169 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4170
4171/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4172 * decoded as itself. We are permissive on decoding; the only ASCII
4173 * byte not decoding to itself is the + which begins a base64
4174 * string. */
4175
4176#define DECODE_DIRECT(c) \
4177 ((c) <= 127 && (c) != '+')
4178
4179/* The UTF-7 encoder treats ASCII characters differently according to
4180 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4181 * the above). See RFC2152. This array identifies these different
4182 * sets:
4183 * 0 : "Set D"
4184 * alphanumeric and '(),-./:?
4185 * 1 : "Set O"
4186 * !"#$%&*;<=>@[]^_`{|}
4187 * 2 : "whitespace"
4188 * ht nl cr sp
4189 * 3 : special (must be base64 encoded)
4190 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4191 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004192
Tim Petersced69f82003-09-16 20:30:58 +00004193static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004194char utf7_category[128] = {
4195/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4196 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4197/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4198 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4199/* sp ! " # $ % & ' ( ) * + , - . / */
4200 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4201/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4202 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4203/* @ A B C D E F G H I J K L M N O */
4204 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4205/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4206 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4207/* ` a b c d e f g h i j k l m n o */
4208 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4209/* p q r s t u v w x y z { | } ~ del */
4210 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004211};
4212
Antoine Pitrou244651a2009-05-04 18:56:13 +00004213/* ENCODE_DIRECT: this character should be encoded as itself. The
4214 * answer depends on whether we are encoding set O as itself, and also
4215 * on whether we are encoding whitespace as itself. RFC2152 makes it
4216 * clear that the answers to these questions vary between
4217 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004218
Antoine Pitrou244651a2009-05-04 18:56:13 +00004219#define ENCODE_DIRECT(c, directO, directWS) \
4220 ((c) < 128 && (c) > 0 && \
4221 ((utf7_category[(c)] == 0) || \
4222 (directWS && (utf7_category[(c)] == 2)) || \
4223 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004224
Alexander Belopolsky40018472011-02-26 01:02:56 +00004225PyObject *
4226PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004227 Py_ssize_t size,
4228 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004229{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004230 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4231}
4232
Antoine Pitrou244651a2009-05-04 18:56:13 +00004233/* The decoder. The only state we preserve is our read position,
4234 * i.e. how many characters we have consumed. So if we end in the
4235 * middle of a shift sequence we have to back off the read position
4236 * and the output to the beginning of the sequence, otherwise we lose
4237 * all the shift state (seen bits, number of bits seen, high
4238 * surrogate). */
4239
Alexander Belopolsky40018472011-02-26 01:02:56 +00004240PyObject *
4241PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004242 Py_ssize_t size,
4243 const char *errors,
4244 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004245{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004246 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004247 Py_ssize_t startinpos;
4248 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004249 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004250 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251 const char *errmsg = "";
4252 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004253 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004254 unsigned int base64bits = 0;
4255 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004256 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004257 PyObject *errorHandler = NULL;
4258 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004259
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004260 if (size == 0) {
4261 if (consumed)
4262 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004263 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004264 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004265
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004266 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004267 _PyUnicodeWriter_Init(&writer);
4268 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004269
4270 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004271 e = s + size;
4272
4273 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004274 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004275 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004276 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004277
Antoine Pitrou244651a2009-05-04 18:56:13 +00004278 if (inShift) { /* in a base-64 section */
4279 if (IS_BASE64(ch)) { /* consume a base-64 character */
4280 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4281 base64bits += 6;
4282 s++;
4283 if (base64bits >= 16) {
4284 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004285 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286 base64bits -= 16;
4287 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4288 if (surrogate) {
4289 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004290 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4291 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004292 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004293 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004295 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004296 }
4297 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004298 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004299 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004300 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301 }
4302 }
Victor Stinner551ac952011-11-29 22:58:13 +01004303 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004304 /* first surrogate */
4305 surrogate = outCh;
4306 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004307 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004308 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004309 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004310 }
4311 }
4312 }
4313 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 inShift = 0;
4315 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004316 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004317 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004318 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004319 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 if (base64bits > 0) { /* left-over bits */
4322 if (base64bits >= 6) {
4323 /* We've seen at least one base-64 character */
4324 errmsg = "partial character in shift sequence";
4325 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 else {
4328 /* Some bits remain; they should be zero */
4329 if (base64buffer != 0) {
4330 errmsg = "non-zero padding bits in shift sequence";
4331 goto utf7Error;
4332 }
4333 }
4334 }
4335 if (ch != '-') {
4336 /* '-' is absorbed; other terminating
4337 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004338 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004339 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004340 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341 }
4342 }
4343 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004344 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 s++; /* consume '+' */
4346 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004348 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004349 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004350 }
4351 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004352 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004353 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004355 }
4356 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004357 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004358 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004359 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004360 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004361 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 else {
4363 startinpos = s-starts;
4364 s++;
4365 errmsg = "unexpected special character";
4366 goto utf7Error;
4367 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004368 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004370 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004371 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004372 errors, &errorHandler,
4373 "utf7", errmsg,
4374 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004375 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004376 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004377 }
4378
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 /* end of string */
4380
4381 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4382 /* if we're in an inconsistent state, that's an error */
4383 if (surrogate ||
4384 (base64bits >= 6) ||
4385 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004386 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004387 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 errors, &errorHandler,
4389 "utf7", "unterminated shift sequence",
4390 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004391 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004392 goto onError;
4393 if (s < e)
4394 goto restart;
4395 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397
4398 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004399 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004400 if (inShift) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004401 writer.pos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004402 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 }
4404 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004405 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004407 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004409 Py_XDECREF(errorHandler);
4410 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004411 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412
Benjamin Peterson29060642009-01-31 22:14:21 +00004413 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414 Py_XDECREF(errorHandler);
4415 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004416 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 return NULL;
4418}
4419
4420
Alexander Belopolsky40018472011-02-26 01:02:56 +00004421PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004422_PyUnicode_EncodeUTF7(PyObject *str,
4423 int base64SetO,
4424 int base64WhiteSpace,
4425 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004427 int kind;
4428 void *data;
4429 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004430 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004431 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004432 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433 unsigned int base64bits = 0;
4434 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435 char * out;
4436 char * start;
4437
Benjamin Petersonbac79492012-01-14 13:34:47 -05004438 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004439 return NULL;
4440 kind = PyUnicode_KIND(str);
4441 data = PyUnicode_DATA(str);
4442 len = PyUnicode_GET_LENGTH(str);
4443
4444 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004445 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004446
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004447 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004448 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004449 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004450 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004451 if (v == NULL)
4452 return NULL;
4453
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004454 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004455 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004456 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458 if (inShift) {
4459 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4460 /* shifting out */
4461 if (base64bits) { /* output remaining bits */
4462 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4463 base64buffer = 0;
4464 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004465 }
4466 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 /* Characters not in the BASE64 set implicitly unshift the sequence
4468 so no '-' is required, except if the character is itself a '-' */
4469 if (IS_BASE64(ch) || ch == '-') {
4470 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 *out++ = (char) ch;
4473 }
4474 else {
4475 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004476 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004478 else { /* not in a shift sequence */
4479 if (ch == '+') {
4480 *out++ = '+';
4481 *out++ = '-';
4482 }
4483 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4484 *out++ = (char) ch;
4485 }
4486 else {
4487 *out++ = '+';
4488 inShift = 1;
4489 goto encode_char;
4490 }
4491 }
4492 continue;
4493encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004494 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004495 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004496
Antoine Pitrou244651a2009-05-04 18:56:13 +00004497 /* code first surrogate */
4498 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004499 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 while (base64bits >= 6) {
4501 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4502 base64bits -= 6;
4503 }
4504 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004505 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 base64bits += 16;
4508 base64buffer = (base64buffer << 16) | ch;
4509 while (base64bits >= 6) {
4510 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4511 base64bits -= 6;
4512 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004513 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004514 if (base64bits)
4515 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4516 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004518 if (_PyBytes_Resize(&v, out - start) < 0)
4519 return NULL;
4520 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004521}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004522PyObject *
4523PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4524 Py_ssize_t size,
4525 int base64SetO,
4526 int base64WhiteSpace,
4527 const char *errors)
4528{
4529 PyObject *result;
4530 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4531 if (tmp == NULL)
4532 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004533 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004534 base64WhiteSpace, errors);
4535 Py_DECREF(tmp);
4536 return result;
4537}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539#undef IS_BASE64
4540#undef FROM_BASE64
4541#undef TO_BASE64
4542#undef DECODE_DIRECT
4543#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544
Guido van Rossumd57fd912000-03-10 22:53:23 +00004545/* --- UTF-8 Codec -------------------------------------------------------- */
4546
Alexander Belopolsky40018472011-02-26 01:02:56 +00004547PyObject *
4548PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004549 Py_ssize_t size,
4550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004551{
Walter Dörwald69652032004-09-07 20:24:22 +00004552 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4553}
4554
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004555#include "stringlib/asciilib.h"
4556#include "stringlib/codecs.h"
4557#include "stringlib/undef.h"
4558
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004559#include "stringlib/ucs1lib.h"
4560#include "stringlib/codecs.h"
4561#include "stringlib/undef.h"
4562
4563#include "stringlib/ucs2lib.h"
4564#include "stringlib/codecs.h"
4565#include "stringlib/undef.h"
4566
4567#include "stringlib/ucs4lib.h"
4568#include "stringlib/codecs.h"
4569#include "stringlib/undef.h"
4570
Antoine Pitrouab868312009-01-10 15:40:25 +00004571/* Mask to quickly check whether a C 'long' contains a
4572 non-ASCII, UTF8-encoded char. */
4573#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004574# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004575#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004576# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004577#else
4578# error C 'long' size should be either 4 or 8!
4579#endif
4580
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004581static Py_ssize_t
4582ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004583{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004584 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004585 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004586
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004587#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004588 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4589 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004590 /* Fast path, see in STRINGLIB(utf8_decode) for
4591 an explanation. */
4592 /* Help register allocation */
4593 register const char *_p = p;
4594 register Py_UCS1 * q = dest;
4595 while (_p < aligned_end) {
4596 unsigned long value = *(const unsigned long *) _p;
4597 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004598 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004599 *((unsigned long *)q) = value;
4600 _p += SIZEOF_LONG;
4601 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004602 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004603 p = _p;
4604 while (p < end) {
4605 if ((unsigned char)*p & 0x80)
4606 break;
4607 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004608 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004609 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004610 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004611#endif
4612 while (p < end) {
4613 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4614 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004615 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004616 /* Help register allocation */
4617 register const char *_p = p;
4618 while (_p < aligned_end) {
4619 unsigned long value = *(unsigned long *) _p;
4620 if (value & ASCII_CHAR_MASK)
4621 break;
4622 _p += SIZEOF_LONG;
4623 }
4624 p = _p;
4625 if (_p == end)
4626 break;
4627 }
4628 if ((unsigned char)*p & 0x80)
4629 break;
4630 ++p;
4631 }
4632 memcpy(dest, start, p - start);
4633 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004634}
Antoine Pitrouab868312009-01-10 15:40:25 +00004635
Victor Stinner785938e2011-12-11 20:09:03 +01004636PyObject *
4637PyUnicode_DecodeUTF8Stateful(const char *s,
4638 Py_ssize_t size,
4639 const char *errors,
4640 Py_ssize_t *consumed)
4641{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004642 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004643 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004644 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004645
4646 Py_ssize_t startinpos;
4647 Py_ssize_t endinpos;
4648 const char *errmsg = "";
4649 PyObject *errorHandler = NULL;
4650 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004651
4652 if (size == 0) {
4653 if (consumed)
4654 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004655 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004656 }
4657
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004658 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4659 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004660 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661 *consumed = 1;
4662 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004663 }
4664
Victor Stinner8f674cc2013-04-17 23:02:17 +02004665 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004666 writer.min_length = size;
4667 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004668 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004669
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004670 writer.pos = ascii_decode(s, end, writer.data);
4671 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672 while (s < end) {
4673 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004674 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004676 if (PyUnicode_IS_ASCII(writer.buffer))
4677 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004679 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004681 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682 } else {
4683 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004684 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004685 }
4686
4687 switch (ch) {
4688 case 0:
4689 if (s == end || consumed)
4690 goto End;
4691 errmsg = "unexpected end of data";
4692 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004693 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694 break;
4695 case 1:
4696 errmsg = "invalid start byte";
4697 startinpos = s - starts;
4698 endinpos = startinpos + 1;
4699 break;
4700 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004701 case 3:
4702 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004703 errmsg = "invalid continuation byte";
4704 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004705 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004706 break;
4707 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004708 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004709 goto onError;
4710 continue;
4711 }
4712
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004713 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004714 errors, &errorHandler,
4715 "utf-8", errmsg,
4716 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004717 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004718 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004719 }
4720
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004721End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004722 if (consumed)
4723 *consumed = s - starts;
4724
4725 Py_XDECREF(errorHandler);
4726 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004727 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004728
4729onError:
4730 Py_XDECREF(errorHandler);
4731 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004732 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004733 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004734}
4735
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004736#ifdef __APPLE__
4737
4738/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004739 used to decode the command line arguments on Mac OS X.
4740
4741 Return a pointer to a newly allocated wide character string (use
4742 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004743
4744wchar_t*
4745_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4746{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004747 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748 wchar_t *unicode;
4749 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004750
4751 /* Note: size will always be longer than the resulting Unicode
4752 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004753 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004754 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004755 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4756 if (!unicode)
4757 return NULL;
4758
4759 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004760 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004761 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004762 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004764#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004766#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004768#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004769 if (ch > 0xFF) {
4770#if SIZEOF_WCHAR_T == 4
4771 assert(0);
4772#else
4773 assert(Py_UNICODE_IS_SURROGATE(ch));
4774 /* compute and append the two surrogates: */
4775 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4776 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4777#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004778 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004779 else {
4780 if (!ch && s == e)
4781 break;
4782 /* surrogateescape */
4783 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4784 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004785 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004786 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004787 return unicode;
4788}
4789
4790#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004792/* Primary internal function which creates utf8 encoded bytes objects.
4793
4794 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004795 and allocate exactly as much space needed at the end. Else allocate the
4796 maximum possible needed (4 result bytes per Unicode character), and return
4797 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004798*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004799PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004800_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004801{
Victor Stinner6099a032011-12-18 14:22:26 +01004802 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004803 void *data;
4804 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004806 if (!PyUnicode_Check(unicode)) {
4807 PyErr_BadArgument();
4808 return NULL;
4809 }
4810
4811 if (PyUnicode_READY(unicode) == -1)
4812 return NULL;
4813
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004814 if (PyUnicode_UTF8(unicode))
4815 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4816 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004817
4818 kind = PyUnicode_KIND(unicode);
4819 data = PyUnicode_DATA(unicode);
4820 size = PyUnicode_GET_LENGTH(unicode);
4821
Benjamin Petersonead6b532011-12-20 17:23:42 -06004822 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004823 default:
4824 assert(0);
4825 case PyUnicode_1BYTE_KIND:
4826 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4827 assert(!PyUnicode_IS_ASCII(unicode));
4828 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4829 case PyUnicode_2BYTE_KIND:
4830 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4831 case PyUnicode_4BYTE_KIND:
4832 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004833 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004834}
4835
Alexander Belopolsky40018472011-02-26 01:02:56 +00004836PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004837PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4838 Py_ssize_t size,
4839 const char *errors)
4840{
4841 PyObject *v, *unicode;
4842
4843 unicode = PyUnicode_FromUnicode(s, size);
4844 if (unicode == NULL)
4845 return NULL;
4846 v = _PyUnicode_AsUTF8String(unicode, errors);
4847 Py_DECREF(unicode);
4848 return v;
4849}
4850
4851PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004852PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004853{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004854 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855}
4856
Walter Dörwald41980ca2007-08-16 21:55:45 +00004857/* --- UTF-32 Codec ------------------------------------------------------- */
4858
4859PyObject *
4860PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004861 Py_ssize_t size,
4862 const char *errors,
4863 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004864{
4865 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4866}
4867
4868PyObject *
4869PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004870 Py_ssize_t size,
4871 const char *errors,
4872 int *byteorder,
4873 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004874{
4875 const char *starts = s;
4876 Py_ssize_t startinpos;
4877 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004878 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004879 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004880 int le, bo = 0; /* assume native ordering by default */
Walter Dörwald41980ca2007-08-16 21:55:45 +00004881 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004882 PyObject *errorHandler = NULL;
4883 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004884
Walter Dörwald41980ca2007-08-16 21:55:45 +00004885 q = (unsigned char *)s;
4886 e = q + size;
4887
4888 if (byteorder)
4889 bo = *byteorder;
4890
4891 /* Check for BOM marks (U+FEFF) in the input and adjust current
4892 byte order setting accordingly. In native mode, the leading BOM
4893 mark is skipped, in all other modes, it is copied to the output
4894 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004895 if (bo == 0 && size >= 4) {
4896 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4897 if (bom == 0x0000FEFF) {
4898 bo = -1;
4899 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004900 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004901 else if (bom == 0xFFFE0000) {
4902 bo = 1;
4903 q += 4;
4904 }
4905 if (byteorder)
4906 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004907 }
4908
Victor Stinnere64322e2012-10-30 23:12:47 +01004909 if (q == e) {
4910 if (consumed)
4911 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004912 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004913 }
4914
Victor Stinnere64322e2012-10-30 23:12:47 +01004915#ifdef WORDS_BIGENDIAN
4916 le = bo < 0;
4917#else
4918 le = bo <= 0;
4919#endif
4920
Victor Stinner8f674cc2013-04-17 23:02:17 +02004921 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004922 writer.min_length = (e - q + 3) / 4;
4923 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004924 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004925
Victor Stinnere64322e2012-10-30 23:12:47 +01004926 while (1) {
4927 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004928 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004929
Victor Stinnere64322e2012-10-30 23:12:47 +01004930 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004931 enum PyUnicode_Kind kind = writer.kind;
4932 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004933 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004934 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004935 if (le) {
4936 do {
4937 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4938 if (ch > maxch)
4939 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004940 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004941 q += 4;
4942 } while (q <= last);
4943 }
4944 else {
4945 do {
4946 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
4947 if (ch > maxch)
4948 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004949 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004950 q += 4;
4951 } while (q <= last);
4952 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004953 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004954 }
4955
4956 if (ch <= maxch) {
4957 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004958 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01004959 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00004960 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01004961 startinpos = ((const char *)q) - starts;
4962 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00004963 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004964 else {
4965 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004966 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01004967 goto onError;
4968 q += 4;
4969 continue;
4970 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004971 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01004972 startinpos = ((const char *)q) - starts;
4973 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004974 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004975
4976 /* The remaining input chars are ignored if the callback
4977 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004978 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 errors, &errorHandler,
4980 "utf32", errmsg,
4981 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004982 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004983 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004984 }
4985
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004988
Walter Dörwald41980ca2007-08-16 21:55:45 +00004989 Py_XDECREF(errorHandler);
4990 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004991 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992
Benjamin Peterson29060642009-01-31 22:14:21 +00004993 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004994 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995 Py_XDECREF(errorHandler);
4996 Py_XDECREF(exc);
4997 return NULL;
4998}
4999
5000PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005001_PyUnicode_EncodeUTF32(PyObject *str,
5002 const char *errors,
5003 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005004{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005005 int kind;
5006 void *data;
5007 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005008 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005009 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005010 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005011 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005012#if PY_LITTLE_ENDIAN
Walter Dörwald41980ca2007-08-16 21:55:45 +00005013 int iorder[] = {0, 1, 2, 3};
5014#else
5015 int iorder[] = {3, 2, 1, 0};
5016#endif
5017
Benjamin Peterson29060642009-01-31 22:14:21 +00005018#define STORECHAR(CH) \
5019 do { \
5020 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5021 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5022 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5023 p[iorder[0]] = (CH) & 0xff; \
5024 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005025 } while(0)
5026
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005027 if (!PyUnicode_Check(str)) {
5028 PyErr_BadArgument();
5029 return NULL;
5030 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005031 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005032 return NULL;
5033 kind = PyUnicode_KIND(str);
5034 data = PyUnicode_DATA(str);
5035 len = PyUnicode_GET_LENGTH(str);
5036
5037 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005038 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005040 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005041 if (v == NULL)
5042 return NULL;
5043
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005044 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005046 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005047 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005048 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005049
5050 if (byteorder == -1) {
5051 /* force LE */
5052 iorder[0] = 0;
5053 iorder[1] = 1;
5054 iorder[2] = 2;
5055 iorder[3] = 3;
5056 }
5057 else if (byteorder == 1) {
5058 /* force BE */
5059 iorder[0] = 3;
5060 iorder[1] = 2;
5061 iorder[2] = 1;
5062 iorder[3] = 0;
5063 }
5064
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005065 for (i = 0; i < len; i++)
5066 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005067
5068 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005069 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070#undef STORECHAR
5071}
5072
Alexander Belopolsky40018472011-02-26 01:02:56 +00005073PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005074PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5075 Py_ssize_t size,
5076 const char *errors,
5077 int byteorder)
5078{
5079 PyObject *result;
5080 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5081 if (tmp == NULL)
5082 return NULL;
5083 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5084 Py_DECREF(tmp);
5085 return result;
5086}
5087
5088PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005089PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005090{
Victor Stinnerb960b342011-11-20 19:12:52 +01005091 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092}
5093
Guido van Rossumd57fd912000-03-10 22:53:23 +00005094/* --- UTF-16 Codec ------------------------------------------------------- */
5095
Tim Peters772747b2001-08-09 22:21:55 +00005096PyObject *
5097PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 Py_ssize_t size,
5099 const char *errors,
5100 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005101{
Walter Dörwald69652032004-09-07 20:24:22 +00005102 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5103}
5104
5105PyObject *
5106PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005107 Py_ssize_t size,
5108 const char *errors,
5109 int *byteorder,
5110 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005111{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005112 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005113 Py_ssize_t startinpos;
5114 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005115 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005116 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005117 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005118 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005119 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005120 PyObject *errorHandler = NULL;
5121 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005122
Tim Peters772747b2001-08-09 22:21:55 +00005123 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005124 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005125
5126 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005127 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005128
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005129 /* Check for BOM marks (U+FEFF) in the input and adjust current
5130 byte order setting accordingly. In native mode, the leading BOM
5131 mark is skipped, in all other modes, it is copied to the output
5132 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005133 if (bo == 0 && size >= 2) {
5134 const Py_UCS4 bom = (q[1] << 8) | q[0];
5135 if (bom == 0xFEFF) {
5136 q += 2;
5137 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005138 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005139 else if (bom == 0xFFFE) {
5140 q += 2;
5141 bo = 1;
5142 }
5143 if (byteorder)
5144 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005145 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005146
Antoine Pitrou63065d72012-05-15 23:48:04 +02005147 if (q == e) {
5148 if (consumed)
5149 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005150 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005151 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005152
Christian Heimes743e0cd2012-10-17 23:52:17 +02005153#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005154 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005155#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005156 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005157#endif
Tim Peters772747b2001-08-09 22:21:55 +00005158
Antoine Pitrou63065d72012-05-15 23:48:04 +02005159 /* Note: size will always be longer than the resulting Unicode
5160 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005161 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005162 writer.min_length = (e - q + 1) / 2;
5163 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005164 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005165
Antoine Pitrou63065d72012-05-15 23:48:04 +02005166 while (1) {
5167 Py_UCS4 ch = 0;
5168 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005169 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005170 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005171 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005172 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005173 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005174 native_ordering);
5175 else
5176 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005177 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005178 native_ordering);
5179 } else if (kind == PyUnicode_2BYTE_KIND) {
5180 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005181 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005182 native_ordering);
5183 } else {
5184 assert(kind == PyUnicode_4BYTE_KIND);
5185 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005186 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005187 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005188 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005189 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005190
Antoine Pitrou63065d72012-05-15 23:48:04 +02005191 switch (ch)
5192 {
5193 case 0:
5194 /* remaining byte at the end? (size should be even) */
5195 if (q == e || consumed)
5196 goto End;
5197 errmsg = "truncated data";
5198 startinpos = ((const char *)q) - starts;
5199 endinpos = ((const char *)e) - starts;
5200 break;
5201 /* The remaining input chars are ignored if the callback
5202 chooses to skip the input */
5203 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005204 q -= 2;
5205 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005206 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005207 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005208 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005209 endinpos = ((const char *)e) - starts;
5210 break;
5211 case 2:
5212 errmsg = "illegal encoding";
5213 startinpos = ((const char *)q) - 2 - starts;
5214 endinpos = startinpos + 2;
5215 break;
5216 case 3:
5217 errmsg = "illegal UTF-16 surrogate";
5218 startinpos = ((const char *)q) - 4 - starts;
5219 endinpos = startinpos + 2;
5220 break;
5221 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005222 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005223 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 continue;
5225 }
5226
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005227 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005228 errors,
5229 &errorHandler,
5230 "utf16", errmsg,
5231 &starts,
5232 (const char **)&e,
5233 &startinpos,
5234 &endinpos,
5235 &exc,
5236 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005237 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005238 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005239 }
5240
Antoine Pitrou63065d72012-05-15 23:48:04 +02005241End:
Walter Dörwald69652032004-09-07 20:24:22 +00005242 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005244
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005245 Py_XDECREF(errorHandler);
5246 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005247 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005248
Benjamin Peterson29060642009-01-31 22:14:21 +00005249 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005250 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005251 Py_XDECREF(errorHandler);
5252 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005253 return NULL;
5254}
5255
Tim Peters772747b2001-08-09 22:21:55 +00005256PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005257_PyUnicode_EncodeUTF16(PyObject *str,
5258 const char *errors,
5259 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005260{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005261 enum PyUnicode_Kind kind;
5262 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005263 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005264 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005265 unsigned short *out;
5266 Py_ssize_t bytesize;
5267 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005268#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005269 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005270#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005271 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005272#endif
5273
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005274 if (!PyUnicode_Check(str)) {
5275 PyErr_BadArgument();
5276 return NULL;
5277 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005278 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005279 return NULL;
5280 kind = PyUnicode_KIND(str);
5281 data = PyUnicode_DATA(str);
5282 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005283
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005284 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005285 if (kind == PyUnicode_4BYTE_KIND) {
5286 const Py_UCS4 *in = (const Py_UCS4 *)data;
5287 const Py_UCS4 *end = in + len;
5288 while (in < end)
5289 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005290 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005291 }
5292 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005293 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005294 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005295 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005296 if (v == NULL)
5297 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005298
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005299 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005300 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005301 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005302 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005303 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005304 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005305 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005306
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005307 switch (kind) {
5308 case PyUnicode_1BYTE_KIND: {
5309 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5310 break;
Tim Peters772747b2001-08-09 22:21:55 +00005311 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005312 case PyUnicode_2BYTE_KIND: {
5313 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5314 break;
Tim Peters772747b2001-08-09 22:21:55 +00005315 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005316 case PyUnicode_4BYTE_KIND: {
5317 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5318 break;
5319 }
5320 default:
5321 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005322 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005323
5324 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005325 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005326}
5327
Alexander Belopolsky40018472011-02-26 01:02:56 +00005328PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005329PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5330 Py_ssize_t size,
5331 const char *errors,
5332 int byteorder)
5333{
5334 PyObject *result;
5335 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5336 if (tmp == NULL)
5337 return NULL;
5338 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5339 Py_DECREF(tmp);
5340 return result;
5341}
5342
5343PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005344PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005345{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005346 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005347}
5348
5349/* --- Unicode Escape Codec ----------------------------------------------- */
5350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005351/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5352 if all the escapes in the string make it still a valid ASCII string.
5353 Returns -1 if any escapes were found which cause the string to
5354 pop out of ASCII range. Otherwise returns the length of the
5355 required buffer to hold the string.
5356 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005357static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005358length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5359{
5360 const unsigned char *p = (const unsigned char *)s;
5361 const unsigned char *end = p + size;
5362 Py_ssize_t length = 0;
5363
5364 if (size < 0)
5365 return -1;
5366
5367 for (; p < end; ++p) {
5368 if (*p > 127) {
5369 /* Non-ASCII */
5370 return -1;
5371 }
5372 else if (*p != '\\') {
5373 /* Normal character */
5374 ++length;
5375 }
5376 else {
5377 /* Backslash-escape, check next char */
5378 ++p;
5379 /* Escape sequence reaches till end of string or
5380 non-ASCII follow-up. */
5381 if (p >= end || *p > 127)
5382 return -1;
5383 switch (*p) {
5384 case '\n':
5385 /* backslash + \n result in zero characters */
5386 break;
5387 case '\\': case '\'': case '\"':
5388 case 'b': case 'f': case 't':
5389 case 'n': case 'r': case 'v': case 'a':
5390 ++length;
5391 break;
5392 case '0': case '1': case '2': case '3':
5393 case '4': case '5': case '6': case '7':
5394 case 'x': case 'u': case 'U': case 'N':
5395 /* these do not guarantee ASCII characters */
5396 return -1;
5397 default:
5398 /* count the backslash + the other character */
5399 length += 2;
5400 }
5401 }
5402 }
5403 return length;
5404}
5405
Fredrik Lundh06d12682001-01-24 07:59:11 +00005406static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005407
Alexander Belopolsky40018472011-02-26 01:02:56 +00005408PyObject *
5409PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005410 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005411 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005412{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005413 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005414 Py_ssize_t startinpos;
5415 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005416 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005418 char* message;
5419 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005420 PyObject *errorHandler = NULL;
5421 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005422 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005423
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005424 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005425 if (len == 0)
5426 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005427
5428 /* After length_of_escaped_ascii_string() there are two alternatives,
5429 either the string is pure ASCII with named escapes like \n, etc.
5430 and we determined it's exact size (common case)
5431 or it contains \x, \u, ... escape sequences. then we create a
5432 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005433 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005434 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005435 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005436 }
5437 else {
5438 /* Escaped strings will always be longer than the resulting
5439 Unicode string, so we start with size here and then reduce the
5440 length after conversion to the true value.
5441 (but if the error callback returns a long replacement string
5442 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005443 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005444 }
5445
Guido van Rossumd57fd912000-03-10 22:53:23 +00005446 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005447 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005448 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005449
Guido van Rossumd57fd912000-03-10 22:53:23 +00005450 while (s < end) {
5451 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005452 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005453 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005454
5455 /* Non-escape characters are interpreted as Unicode ordinals */
5456 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005457 x = (unsigned char)*s;
5458 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005459 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005460 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005461 continue;
5462 }
5463
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005464 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005465 /* \ - Escapes */
5466 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005467 c = *s++;
5468 if (s > end)
5469 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005470
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005471 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005472
Benjamin Peterson29060642009-01-31 22:14:21 +00005473 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005474#define WRITECHAR(ch) \
5475 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005476 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005477 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005478 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005479
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005481 case '\\': WRITECHAR('\\'); break;
5482 case '\'': WRITECHAR('\''); break;
5483 case '\"': WRITECHAR('\"'); break;
5484 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005485 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005486 case 'f': WRITECHAR('\014'); break;
5487 case 't': WRITECHAR('\t'); break;
5488 case 'n': WRITECHAR('\n'); break;
5489 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005490 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005491 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005492 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005493 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005494
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005496 case '0': case '1': case '2': case '3':
5497 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005498 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005499 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005500 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005501 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005502 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005503 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005504 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005505 break;
5506
Benjamin Peterson29060642009-01-31 22:14:21 +00005507 /* hex escapes */
5508 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005509 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005510 digits = 2;
5511 message = "truncated \\xXX escape";
5512 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005513
Benjamin Peterson29060642009-01-31 22:14:21 +00005514 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005515 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005516 digits = 4;
5517 message = "truncated \\uXXXX escape";
5518 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005519
Benjamin Peterson29060642009-01-31 22:14:21 +00005520 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005521 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005522 digits = 8;
5523 message = "truncated \\UXXXXXXXX escape";
5524 hexescape:
5525 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005526 if (end - s < digits) {
5527 /* count only hex digits */
5528 for (; s < end; ++s) {
5529 c = (unsigned char)*s;
5530 if (!Py_ISXDIGIT(c))
5531 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005532 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005533 goto error;
5534 }
5535 for (; digits--; ++s) {
5536 c = (unsigned char)*s;
5537 if (!Py_ISXDIGIT(c))
5538 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005539 chr = (chr<<4) & ~0xF;
5540 if (c >= '0' && c <= '9')
5541 chr += c - '0';
5542 else if (c >= 'a' && c <= 'f')
5543 chr += 10 + c - 'a';
5544 else
5545 chr += 10 + c - 'A';
5546 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005547 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005548 /* _decoding_error will have already written into the
5549 target buffer. */
5550 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005551 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005552 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005553 message = "illegal Unicode character";
5554 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005555 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005556 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005557 break;
5558
Benjamin Peterson29060642009-01-31 22:14:21 +00005559 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005560 case 'N':
5561 message = "malformed \\N character escape";
5562 if (ucnhash_CAPI == NULL) {
5563 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005564 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5565 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005566 if (ucnhash_CAPI == NULL)
5567 goto ucnhashError;
5568 }
5569 if (*s == '{') {
5570 const char *start = s+1;
5571 /* look for the closing brace */
5572 while (*s != '}' && s < end)
5573 s++;
5574 if (s > start && s < end && *s == '}') {
5575 /* found a name. look it up in the unicode database */
5576 message = "unknown Unicode character name";
5577 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005578 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005579 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005580 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005581 goto store;
5582 }
5583 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005584 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005585
5586 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005587 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005588 message = "\\ at end of string";
5589 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005590 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005591 }
5592 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005593 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005594 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005595 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005596 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005597 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005598 continue;
5599
5600 error:
5601 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005602 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005603 errors, &errorHandler,
5604 "unicodeescape", message,
5605 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005606 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005607 goto onError;
5608 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005610#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005611
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005612 Py_XDECREF(errorHandler);
5613 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005614 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005615
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005617 PyErr_SetString(
5618 PyExc_UnicodeError,
5619 "\\N escapes not supported (can't load unicodedata module)"
5620 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005621 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005622 Py_XDECREF(errorHandler);
5623 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005624 return NULL;
5625
Benjamin Peterson29060642009-01-31 22:14:21 +00005626 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005627 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005628 Py_XDECREF(errorHandler);
5629 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 return NULL;
5631}
5632
5633/* Return a Unicode-Escape string version of the Unicode object.
5634
5635 If quotes is true, the string is enclosed in u"" or u'' quotes as
5636 appropriate.
5637
5638*/
5639
Alexander Belopolsky40018472011-02-26 01:02:56 +00005640PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005641PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005643 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005644 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005645 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005646 int kind;
5647 void *data;
5648 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649
Ezio Melottie7f90372012-10-05 03:33:31 +03005650 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005651 escape.
5652
Ezio Melottie7f90372012-10-05 03:33:31 +03005653 For UCS1 strings it's '\xxx', 4 bytes per source character.
5654 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5655 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005656 */
5657
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005658 if (!PyUnicode_Check(unicode)) {
5659 PyErr_BadArgument();
5660 return NULL;
5661 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005662 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005663 return NULL;
5664 len = PyUnicode_GET_LENGTH(unicode);
5665 kind = PyUnicode_KIND(unicode);
5666 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005667 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005668 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5669 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5670 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5671 }
5672
5673 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005674 return PyBytes_FromStringAndSize(NULL, 0);
5675
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005676 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005677 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005678
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005679 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005680 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005681 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005683 if (repr == NULL)
5684 return NULL;
5685
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005686 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005688 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005689 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005690
Walter Dörwald79e913e2007-05-12 11:08:06 +00005691 /* Escape backslashes */
5692 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 *p++ = '\\';
5694 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005695 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005696 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005697
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005698 /* Map 21-bit characters to '\U00xxxxxx' */
5699 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005700 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005701 *p++ = '\\';
5702 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005703 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5704 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5705 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5706 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5707 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5708 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5709 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5710 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005712 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005713
Guido van Rossumd57fd912000-03-10 22:53:23 +00005714 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005715 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 *p++ = '\\';
5717 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005718 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5719 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5720 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5721 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005723
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005724 /* Map special whitespace to '\t', \n', '\r' */
5725 else if (ch == '\t') {
5726 *p++ = '\\';
5727 *p++ = 't';
5728 }
5729 else if (ch == '\n') {
5730 *p++ = '\\';
5731 *p++ = 'n';
5732 }
5733 else if (ch == '\r') {
5734 *p++ = '\\';
5735 *p++ = 'r';
5736 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005737
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005738 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005739 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005741 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005742 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5743 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005744 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005745
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746 /* Copy everything else as-is */
5747 else
5748 *p++ = (char) ch;
5749 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005750
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005751 assert(p - PyBytes_AS_STRING(repr) > 0);
5752 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5753 return NULL;
5754 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755}
5756
Alexander Belopolsky40018472011-02-26 01:02:56 +00005757PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005758PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5759 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005760{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005761 PyObject *result;
5762 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5763 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005765 result = PyUnicode_AsUnicodeEscapeString(tmp);
5766 Py_DECREF(tmp);
5767 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005768}
5769
5770/* --- Raw Unicode Escape Codec ------------------------------------------- */
5771
Alexander Belopolsky40018472011-02-26 01:02:56 +00005772PyObject *
5773PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005774 Py_ssize_t size,
5775 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005776{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005777 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005778 Py_ssize_t startinpos;
5779 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005780 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005781 const char *end;
5782 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005783 PyObject *errorHandler = NULL;
5784 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005785
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005786 if (size == 0)
5787 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005788
Guido van Rossumd57fd912000-03-10 22:53:23 +00005789 /* Escaped strings will always be longer than the resulting
5790 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005791 length after conversion to the true value. (But decoding error
5792 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005793 _PyUnicodeWriter_Init(&writer);
5794 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005795
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796 end = s + size;
5797 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005798 unsigned char c;
5799 Py_UCS4 x;
5800 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005801 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005802
Benjamin Peterson29060642009-01-31 22:14:21 +00005803 /* Non-escape characters are interpreted as Unicode ordinals */
5804 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005805 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005806 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005807 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005808 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005809 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005810 startinpos = s-starts;
5811
5812 /* \u-escapes are only interpreted iff the number of leading
5813 backslashes if odd */
5814 bs = s;
5815 for (;s < end;) {
5816 if (*s != '\\')
5817 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005818 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005819 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005820 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005821 }
5822 if (((s - bs) & 1) == 0 ||
5823 s >= end ||
5824 (*s != 'u' && *s != 'U')) {
5825 continue;
5826 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005827 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 count = *s=='u' ? 4 : 8;
5829 s++;
5830
5831 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005832 for (x = 0, i = 0; i < count; ++i, ++s) {
5833 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005834 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005835 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005836 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005837 errors, &errorHandler,
5838 "rawunicodeescape", "truncated \\uXXXX",
5839 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005840 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005841 goto onError;
5842 goto nextByte;
5843 }
5844 x = (x<<4) & ~0xF;
5845 if (c >= '0' && c <= '9')
5846 x += c - '0';
5847 else if (c >= 'a' && c <= 'f')
5848 x += 10 + c - 'a';
5849 else
5850 x += 10 + c - 'A';
5851 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005852 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005853 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005854 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005855 }
5856 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00005857 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005858 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005859 errors, &errorHandler,
5860 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005861 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005862 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005863 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005864 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005865 nextByte:
5866 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005868 Py_XDECREF(errorHandler);
5869 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005870 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00005871
Benjamin Peterson29060642009-01-31 22:14:21 +00005872 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005873 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005874 Py_XDECREF(errorHandler);
5875 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 return NULL;
5877}
5878
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005879
Alexander Belopolsky40018472011-02-26 01:02:56 +00005880PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005881PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005883 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 char *p;
5885 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886 Py_ssize_t expandsize, pos;
5887 int kind;
5888 void *data;
5889 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005891 if (!PyUnicode_Check(unicode)) {
5892 PyErr_BadArgument();
5893 return NULL;
5894 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005895 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005896 return NULL;
5897 kind = PyUnicode_KIND(unicode);
5898 data = PyUnicode_DATA(unicode);
5899 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06005900 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
5901 bytes, and 1 byte characters 4. */
5902 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01005903
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005906
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005907 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908 if (repr == NULL)
5909 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005910 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005911 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005913 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005914 for (pos = 0; pos < len; pos++) {
5915 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 /* Map 32-bit characters to '\Uxxxxxxxx' */
5917 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005918 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005919 *p++ = '\\';
5920 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005921 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
5922 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
5923 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
5924 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
5925 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5926 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5927 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5928 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005929 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005931 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 *p++ = '\\';
5933 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005934 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5935 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5936 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5937 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 /* Copy everything else as-is */
5940 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 *p++ = (char) ch;
5942 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005943
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005944 assert(p > q);
5945 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005946 return NULL;
5947 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948}
5949
Alexander Belopolsky40018472011-02-26 01:02:56 +00005950PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
5952 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005954 PyObject *result;
5955 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5956 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00005957 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005958 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
5959 Py_DECREF(tmp);
5960 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961}
5962
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005963/* --- Unicode Internal Codec ------------------------------------------- */
5964
Alexander Belopolsky40018472011-02-26 01:02:56 +00005965PyObject *
5966_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005967 Py_ssize_t size,
5968 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005969{
5970 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005971 Py_ssize_t startinpos;
5972 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005973 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005974 const char *end;
5975 const char *reason;
5976 PyObject *errorHandler = NULL;
5977 PyObject *exc = NULL;
5978
Victor Stinner9f4b1e92011-11-10 20:56:30 +01005979 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02005980 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01005981 1))
5982 return NULL;
5983
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005984 if (size == 0)
5985 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005986
Victor Stinner8f674cc2013-04-17 23:02:17 +02005987 _PyUnicodeWriter_Init(&writer);
5988 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
5989 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02005991 }
5992 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005993
Victor Stinner8f674cc2013-04-17 23:02:17 +02005994 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005995 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01005996 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01005997 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02005998 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02005999 endinpos = end-starts;
6000 reason = "truncated input";
6001 goto error;
6002 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006003 /* We copy the raw representation one byte at a time because the
6004 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006005 ((char *) &uch)[0] = s[0];
6006 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006007#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006008 ((char *) &uch)[2] = s[2];
6009 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006010#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006011 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006012#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006013 /* We have to sanity check the raw data, otherwise doom looms for
6014 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006015 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006016 endinpos = s - starts + Py_UNICODE_SIZE;
6017 reason = "illegal code point (> 0x10FFFF)";
6018 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006019 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006020#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006021 s += Py_UNICODE_SIZE;
6022#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006023 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006024 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006025 Py_UNICODE uch2;
6026 ((char *) &uch2)[0] = s[0];
6027 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006028 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006029 {
Victor Stinner551ac952011-11-29 22:58:13 +01006030 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006031 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006032 }
6033 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006034#endif
6035
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006036 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006037 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006038 continue;
6039
6040 error:
6041 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006042 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006043 errors, &errorHandler,
6044 "unicode_internal", reason,
6045 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006046 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006047 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006048 }
6049
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006050 Py_XDECREF(errorHandler);
6051 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006052 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006053
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006055 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006056 Py_XDECREF(errorHandler);
6057 Py_XDECREF(exc);
6058 return NULL;
6059}
6060
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061/* --- Latin-1 Codec ------------------------------------------------------ */
6062
Alexander Belopolsky40018472011-02-26 01:02:56 +00006063PyObject *
6064PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006065 Py_ssize_t size,
6066 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006068 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006069 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070}
6071
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006072/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006073static void
6074make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006075 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006076 PyObject *unicode,
6077 Py_ssize_t startpos, Py_ssize_t endpos,
6078 const char *reason)
6079{
6080 if (*exceptionObject == NULL) {
6081 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006082 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006083 encoding, unicode, startpos, endpos, reason);
6084 }
6085 else {
6086 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6087 goto onError;
6088 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6089 goto onError;
6090 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6091 goto onError;
6092 return;
6093 onError:
6094 Py_DECREF(*exceptionObject);
6095 *exceptionObject = NULL;
6096 }
6097}
6098
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006099/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006100static void
6101raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006102 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006103 PyObject *unicode,
6104 Py_ssize_t startpos, Py_ssize_t endpos,
6105 const char *reason)
6106{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006107 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006108 encoding, unicode, startpos, endpos, reason);
6109 if (*exceptionObject != NULL)
6110 PyCodec_StrictErrors(*exceptionObject);
6111}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006112
6113/* error handling callback helper:
6114 build arguments, call the callback and check the arguments,
6115 put the result into newpos and return the replacement string, which
6116 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006117static PyObject *
6118unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006119 PyObject **errorHandler,
6120 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006121 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006122 Py_ssize_t startpos, Py_ssize_t endpos,
6123 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006124{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006125 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006126 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006127 PyObject *restuple;
6128 PyObject *resunicode;
6129
6130 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006131 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006132 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006133 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006134 }
6135
Benjamin Petersonbac79492012-01-14 13:34:47 -05006136 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006137 return NULL;
6138 len = PyUnicode_GET_LENGTH(unicode);
6139
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006140 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006141 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006142 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006143 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006144
6145 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006146 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006147 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006148 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006149 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006150 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 Py_DECREF(restuple);
6152 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006153 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006154 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 &resunicode, newpos)) {
6156 Py_DECREF(restuple);
6157 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006158 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006159 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6160 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6161 Py_DECREF(restuple);
6162 return NULL;
6163 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006164 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006165 *newpos = len + *newpos;
6166 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6168 Py_DECREF(restuple);
6169 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006170 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006171 Py_INCREF(resunicode);
6172 Py_DECREF(restuple);
6173 return resunicode;
6174}
6175
Alexander Belopolsky40018472011-02-26 01:02:56 +00006176static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006177unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006178 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006179 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006180{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006181 /* input state */
6182 Py_ssize_t pos=0, size;
6183 int kind;
6184 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006185 /* output object */
6186 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006187 /* pointer into the output */
6188 char *str;
6189 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006190 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006191 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6192 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006193 PyObject *errorHandler = NULL;
6194 PyObject *exc = NULL;
6195 /* the following variable is used for caching string comparisons
6196 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6197 int known_errorHandler = -1;
6198
Benjamin Petersonbac79492012-01-14 13:34:47 -05006199 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006200 return NULL;
6201 size = PyUnicode_GET_LENGTH(unicode);
6202 kind = PyUnicode_KIND(unicode);
6203 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006204 /* allocate enough for a simple encoding without
6205 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006206 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006207 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006208 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006209 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006210 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006211 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212 ressize = size;
6213
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006214 while (pos < size) {
6215 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006216
Benjamin Peterson29060642009-01-31 22:14:21 +00006217 /* can we encode this? */
6218 if (c<limit) {
6219 /* no overflow check, because we know that the space is enough */
6220 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006221 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006222 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006224 Py_ssize_t requiredsize;
6225 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006226 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006227 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006228 Py_ssize_t collstart = pos;
6229 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006231 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006232 ++collend;
6233 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6234 if (known_errorHandler==-1) {
6235 if ((errors==NULL) || (!strcmp(errors, "strict")))
6236 known_errorHandler = 1;
6237 else if (!strcmp(errors, "replace"))
6238 known_errorHandler = 2;
6239 else if (!strcmp(errors, "ignore"))
6240 known_errorHandler = 3;
6241 else if (!strcmp(errors, "xmlcharrefreplace"))
6242 known_errorHandler = 4;
6243 else
6244 known_errorHandler = 0;
6245 }
6246 switch (known_errorHandler) {
6247 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006248 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006249 goto onError;
6250 case 2: /* replace */
6251 while (collstart++<collend)
6252 *str++ = '?'; /* fall through */
6253 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006254 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 break;
6256 case 4: /* xmlcharrefreplace */
6257 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006258 /* determine replacement size */
6259 for (i = collstart, repsize = 0; i < collend; ++i) {
6260 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6261 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006263 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006265 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006267 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006268 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006269 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006271 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006273 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006274 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006275 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006276 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006277 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006278 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 if (requiredsize > ressize) {
6280 if (requiredsize<2*ressize)
6281 requiredsize = 2*ressize;
6282 if (_PyBytes_Resize(&res, requiredsize))
6283 goto onError;
6284 str = PyBytes_AS_STRING(res) + respos;
6285 ressize = requiredsize;
6286 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006287 /* generate replacement */
6288 for (i = collstart; i < collend; ++i) {
6289 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006290 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006291 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 break;
6293 default:
6294 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006295 encoding, reason, unicode, &exc,
6296 collstart, collend, &newpos);
6297 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006298 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006300 if (PyBytes_Check(repunicode)) {
6301 /* Directly copy bytes result to output. */
6302 repsize = PyBytes_Size(repunicode);
6303 if (repsize > 1) {
6304 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006305 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006306 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6307 Py_DECREF(repunicode);
6308 goto onError;
6309 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006310 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006311 ressize += repsize-1;
6312 }
6313 memcpy(str, PyBytes_AsString(repunicode), repsize);
6314 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006315 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006316 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006317 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006318 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 /* need more space? (at least enough for what we
6320 have+the replacement+the rest of the string, so
6321 we won't have to check space for encodable characters) */
6322 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006323 repsize = PyUnicode_GET_LENGTH(repunicode);
6324 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 if (requiredsize > ressize) {
6326 if (requiredsize<2*ressize)
6327 requiredsize = 2*ressize;
6328 if (_PyBytes_Resize(&res, requiredsize)) {
6329 Py_DECREF(repunicode);
6330 goto onError;
6331 }
6332 str = PyBytes_AS_STRING(res) + respos;
6333 ressize = requiredsize;
6334 }
6335 /* check if there is anything unencodable in the replacement
6336 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006337 for (i = 0; repsize-->0; ++i, ++str) {
6338 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006339 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006340 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006341 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 Py_DECREF(repunicode);
6343 goto onError;
6344 }
6345 *str = (char)c;
6346 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006347 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006348 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006349 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006350 }
6351 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006352 /* Resize if we allocated to much */
6353 size = str - PyBytes_AS_STRING(res);
6354 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006355 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006356 if (_PyBytes_Resize(&res, size) < 0)
6357 goto onError;
6358 }
6359
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006360 Py_XDECREF(errorHandler);
6361 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006362 return res;
6363
6364 onError:
6365 Py_XDECREF(res);
6366 Py_XDECREF(errorHandler);
6367 Py_XDECREF(exc);
6368 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369}
6370
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006371/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006372PyObject *
6373PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006374 Py_ssize_t size,
6375 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006377 PyObject *result;
6378 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6379 if (unicode == NULL)
6380 return NULL;
6381 result = unicode_encode_ucs1(unicode, errors, 256);
6382 Py_DECREF(unicode);
6383 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384}
6385
Alexander Belopolsky40018472011-02-26 01:02:56 +00006386PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006387_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006388{
6389 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 PyErr_BadArgument();
6391 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006392 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006393 if (PyUnicode_READY(unicode) == -1)
6394 return NULL;
6395 /* Fast path: if it is a one-byte string, construct
6396 bytes object directly. */
6397 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6398 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6399 PyUnicode_GET_LENGTH(unicode));
6400 /* Non-Latin-1 characters present. Defer to above function to
6401 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006403}
6404
6405PyObject*
6406PyUnicode_AsLatin1String(PyObject *unicode)
6407{
6408 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409}
6410
6411/* --- 7-bit ASCII Codec -------------------------------------------------- */
6412
Alexander Belopolsky40018472011-02-26 01:02:56 +00006413PyObject *
6414PyUnicode_DecodeASCII(const char *s,
6415 Py_ssize_t size,
6416 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006417{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006419 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006420 int kind;
6421 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006422 Py_ssize_t startinpos;
6423 Py_ssize_t endinpos;
6424 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 const char *e;
6426 PyObject *errorHandler = NULL;
6427 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006428
Guido van Rossumd57fd912000-03-10 22:53:23 +00006429 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006430 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006431
Guido van Rossumd57fd912000-03-10 22:53:23 +00006432 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006433 if (size == 1 && (unsigned char)s[0] < 128)
6434 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006435
Victor Stinner8f674cc2013-04-17 23:02:17 +02006436 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006437 writer.min_length = size;
6438 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006439 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006440
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006442 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006443 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006444 writer.pos = outpos;
6445 if (writer.pos == size)
6446 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006447
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006448 s += writer.pos;
6449 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006450 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006451 register unsigned char c = (unsigned char)*s;
6452 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006453 PyUnicode_WRITE(kind, data, writer.pos, c);
6454 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 ++s;
6456 }
6457 else {
6458 startinpos = s-starts;
6459 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006460 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 errors, &errorHandler,
6462 "ascii", "ordinal not in range(128)",
6463 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006464 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006466 kind = writer.kind;
6467 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006469 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470 Py_XDECREF(errorHandler);
6471 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006472 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006473
Benjamin Peterson29060642009-01-31 22:14:21 +00006474 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006475 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476 Py_XDECREF(errorHandler);
6477 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478 return NULL;
6479}
6480
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006482PyObject *
6483PyUnicode_EncodeASCII(const Py_UNICODE *p,
6484 Py_ssize_t size,
6485 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006486{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 PyObject *result;
6488 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6489 if (unicode == NULL)
6490 return NULL;
6491 result = unicode_encode_ucs1(unicode, errors, 128);
6492 Py_DECREF(unicode);
6493 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494}
6495
Alexander Belopolsky40018472011-02-26 01:02:56 +00006496PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006497_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006498{
6499 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 PyErr_BadArgument();
6501 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006503 if (PyUnicode_READY(unicode) == -1)
6504 return NULL;
6505 /* Fast path: if it is an ASCII-only string, construct bytes object
6506 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006507 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006508 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6509 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006511}
6512
6513PyObject *
6514PyUnicode_AsASCIIString(PyObject *unicode)
6515{
6516 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006517}
6518
Victor Stinner99b95382011-07-04 14:23:54 +02006519#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006520
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006521/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006522
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006523#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006524#define NEED_RETRY
6525#endif
6526
Victor Stinner3a50e702011-10-18 21:21:00 +02006527#ifndef WC_ERR_INVALID_CHARS
6528# define WC_ERR_INVALID_CHARS 0x0080
6529#endif
6530
6531static char*
6532code_page_name(UINT code_page, PyObject **obj)
6533{
6534 *obj = NULL;
6535 if (code_page == CP_ACP)
6536 return "mbcs";
6537 if (code_page == CP_UTF7)
6538 return "CP_UTF7";
6539 if (code_page == CP_UTF8)
6540 return "CP_UTF8";
6541
6542 *obj = PyBytes_FromFormat("cp%u", code_page);
6543 if (*obj == NULL)
6544 return NULL;
6545 return PyBytes_AS_STRING(*obj);
6546}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006547
Alexander Belopolsky40018472011-02-26 01:02:56 +00006548static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006549is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006550{
6551 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006552 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006553
Victor Stinner3a50e702011-10-18 21:21:00 +02006554 if (!IsDBCSLeadByteEx(code_page, *curr))
6555 return 0;
6556
6557 prev = CharPrevExA(code_page, s, curr, 0);
6558 if (prev == curr)
6559 return 1;
6560 /* FIXME: This code is limited to "true" double-byte encodings,
6561 as it assumes an incomplete character consists of a single
6562 byte. */
6563 if (curr - prev == 2)
6564 return 1;
6565 if (!IsDBCSLeadByteEx(code_page, *prev))
6566 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006567 return 0;
6568}
6569
Victor Stinner3a50e702011-10-18 21:21:00 +02006570static DWORD
6571decode_code_page_flags(UINT code_page)
6572{
6573 if (code_page == CP_UTF7) {
6574 /* The CP_UTF7 decoder only supports flags=0 */
6575 return 0;
6576 }
6577 else
6578 return MB_ERR_INVALID_CHARS;
6579}
6580
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006581/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006582 * Decode a byte string from a Windows code page into unicode object in strict
6583 * mode.
6584 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006585 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6586 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006587 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006588static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006589decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006590 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006591 const char *in,
6592 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006593{
Victor Stinner3a50e702011-10-18 21:21:00 +02006594 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006595 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006596 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006597
6598 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006599 assert(insize > 0);
6600 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6601 if (outsize <= 0)
6602 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006603
6604 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006606 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006607 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 if (*v == NULL)
6609 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006610 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006611 }
6612 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006614 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006615 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006617 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006618 }
6619
6620 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006621 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6622 if (outsize <= 0)
6623 goto error;
6624 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006625
Victor Stinner3a50e702011-10-18 21:21:00 +02006626error:
6627 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6628 return -2;
6629 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006630 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006631}
6632
Victor Stinner3a50e702011-10-18 21:21:00 +02006633/*
6634 * Decode a byte string from a code page into unicode object with an error
6635 * handler.
6636 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006637 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006638 * UnicodeDecodeError exception and returns -1 on error.
6639 */
6640static int
6641decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006642 PyObject **v,
6643 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006644 const char *errors)
6645{
6646 const char *startin = in;
6647 const char *endin = in + size;
6648 const DWORD flags = decode_code_page_flags(code_page);
6649 /* Ideally, we should get reason from FormatMessage. This is the Windows
6650 2000 English version of the message. */
6651 const char *reason = "No mapping for the Unicode character exists "
6652 "in the target code page.";
6653 /* each step cannot decode more than 1 character, but a character can be
6654 represented as a surrogate pair */
6655 wchar_t buffer[2], *startout, *out;
6656 int insize, outsize;
6657 PyObject *errorHandler = NULL;
6658 PyObject *exc = NULL;
6659 PyObject *encoding_obj = NULL;
6660 char *encoding;
6661 DWORD err;
6662 int ret = -1;
6663
6664 assert(size > 0);
6665
6666 encoding = code_page_name(code_page, &encoding_obj);
6667 if (encoding == NULL)
6668 return -1;
6669
6670 if (errors == NULL || strcmp(errors, "strict") == 0) {
6671 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6672 UnicodeDecodeError. */
6673 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6674 if (exc != NULL) {
6675 PyCodec_StrictErrors(exc);
6676 Py_CLEAR(exc);
6677 }
6678 goto error;
6679 }
6680
6681 if (*v == NULL) {
6682 /* Create unicode object */
6683 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6684 PyErr_NoMemory();
6685 goto error;
6686 }
Victor Stinnerab595942011-12-17 04:59:06 +01006687 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006688 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006689 if (*v == NULL)
6690 goto error;
6691 startout = PyUnicode_AS_UNICODE(*v);
6692 }
6693 else {
6694 /* Extend unicode object */
6695 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6696 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6697 PyErr_NoMemory();
6698 goto error;
6699 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006700 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006701 goto error;
6702 startout = PyUnicode_AS_UNICODE(*v) + n;
6703 }
6704
6705 /* Decode the byte string character per character */
6706 out = startout;
6707 while (in < endin)
6708 {
6709 /* Decode a character */
6710 insize = 1;
6711 do
6712 {
6713 outsize = MultiByteToWideChar(code_page, flags,
6714 in, insize,
6715 buffer, Py_ARRAY_LENGTH(buffer));
6716 if (outsize > 0)
6717 break;
6718 err = GetLastError();
6719 if (err != ERROR_NO_UNICODE_TRANSLATION
6720 && err != ERROR_INSUFFICIENT_BUFFER)
6721 {
6722 PyErr_SetFromWindowsErr(0);
6723 goto error;
6724 }
6725 insize++;
6726 }
6727 /* 4=maximum length of a UTF-8 sequence */
6728 while (insize <= 4 && (in + insize) <= endin);
6729
6730 if (outsize <= 0) {
6731 Py_ssize_t startinpos, endinpos, outpos;
6732
6733 startinpos = in - startin;
6734 endinpos = startinpos + 1;
6735 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006736 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006737 errors, &errorHandler,
6738 encoding, reason,
6739 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006740 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006741 {
6742 goto error;
6743 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006744 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006745 }
6746 else {
6747 in += insize;
6748 memcpy(out, buffer, outsize * sizeof(wchar_t));
6749 out += outsize;
6750 }
6751 }
6752
6753 /* write a NUL character at the end */
6754 *out = 0;
6755
6756 /* Extend unicode object */
6757 outsize = out - startout;
6758 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006759 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006760 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006761 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006762
6763error:
6764 Py_XDECREF(encoding_obj);
6765 Py_XDECREF(errorHandler);
6766 Py_XDECREF(exc);
6767 return ret;
6768}
6769
Victor Stinner3a50e702011-10-18 21:21:00 +02006770static PyObject *
6771decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006772 const char *s, Py_ssize_t size,
6773 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006774{
Victor Stinner76a31a62011-11-04 00:05:13 +01006775 PyObject *v = NULL;
6776 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006777
Victor Stinner3a50e702011-10-18 21:21:00 +02006778 if (code_page < 0) {
6779 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6780 return NULL;
6781 }
6782
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006783 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006784 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006785
Victor Stinner76a31a62011-11-04 00:05:13 +01006786 do
6787 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006788#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006789 if (size > INT_MAX) {
6790 chunk_size = INT_MAX;
6791 final = 0;
6792 done = 0;
6793 }
6794 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006795#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006796 {
6797 chunk_size = (int)size;
6798 final = (consumed == NULL);
6799 done = 1;
6800 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006801
Victor Stinner76a31a62011-11-04 00:05:13 +01006802 /* Skip trailing lead-byte unless 'final' is set */
6803 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6804 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006805
Victor Stinner76a31a62011-11-04 00:05:13 +01006806 if (chunk_size == 0 && done) {
6807 if (v != NULL)
6808 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006809 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006810 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006811
Victor Stinner76a31a62011-11-04 00:05:13 +01006812
6813 converted = decode_code_page_strict(code_page, &v,
6814 s, chunk_size);
6815 if (converted == -2)
6816 converted = decode_code_page_errors(code_page, &v,
6817 s, chunk_size,
6818 errors);
6819 assert(converted != 0);
6820
6821 if (converted < 0) {
6822 Py_XDECREF(v);
6823 return NULL;
6824 }
6825
6826 if (consumed)
6827 *consumed += converted;
6828
6829 s += converted;
6830 size -= converted;
6831 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006832
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006833 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006834}
6835
Alexander Belopolsky40018472011-02-26 01:02:56 +00006836PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006837PyUnicode_DecodeCodePageStateful(int code_page,
6838 const char *s,
6839 Py_ssize_t size,
6840 const char *errors,
6841 Py_ssize_t *consumed)
6842{
6843 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6844}
6845
6846PyObject *
6847PyUnicode_DecodeMBCSStateful(const char *s,
6848 Py_ssize_t size,
6849 const char *errors,
6850 Py_ssize_t *consumed)
6851{
6852 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6853}
6854
6855PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006856PyUnicode_DecodeMBCS(const char *s,
6857 Py_ssize_t size,
6858 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006859{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006860 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6861}
6862
Victor Stinner3a50e702011-10-18 21:21:00 +02006863static DWORD
6864encode_code_page_flags(UINT code_page, const char *errors)
6865{
6866 if (code_page == CP_UTF8) {
6867 if (winver.dwMajorVersion >= 6)
6868 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6869 and later */
6870 return WC_ERR_INVALID_CHARS;
6871 else
6872 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
6873 return 0;
6874 }
6875 else if (code_page == CP_UTF7) {
6876 /* CP_UTF7 only supports flags=0 */
6877 return 0;
6878 }
6879 else {
6880 if (errors != NULL && strcmp(errors, "replace") == 0)
6881 return 0;
6882 else
6883 return WC_NO_BEST_FIT_CHARS;
6884 }
6885}
6886
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006887/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006888 * Encode a Unicode string to a Windows code page into a byte string in strict
6889 * mode.
6890 *
6891 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006892 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006893 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006894static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006895encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01006896 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02006897 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006898{
Victor Stinner554f3f02010-06-16 23:33:54 +00006899 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02006900 BOOL *pusedDefaultChar = &usedDefaultChar;
6901 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006902 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01006903 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006904 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006905 const DWORD flags = encode_code_page_flags(code_page, NULL);
6906 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006907 /* Create a substring so that we can get the UTF-16 representation
6908 of just the slice under consideration. */
6909 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910
Martin v. Löwis3d325192011-11-04 18:23:06 +01006911 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006912
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00006914 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02006915 else
Victor Stinner554f3f02010-06-16 23:33:54 +00006916 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00006917
Victor Stinner2fc507f2011-11-04 20:06:39 +01006918 substring = PyUnicode_Substring(unicode, offset, offset+len);
6919 if (substring == NULL)
6920 return -1;
6921 p = PyUnicode_AsUnicodeAndSize(substring, &size);
6922 if (p == NULL) {
6923 Py_DECREF(substring);
6924 return -1;
6925 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01006926
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006927 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006928 outsize = WideCharToMultiByte(code_page, flags,
6929 p, size,
6930 NULL, 0,
6931 NULL, pusedDefaultChar);
6932 if (outsize <= 0)
6933 goto error;
6934 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01006935 if (pusedDefaultChar && *pusedDefaultChar) {
6936 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006937 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006938 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006939
Victor Stinner3a50e702011-10-18 21:21:00 +02006940 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006941 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006942 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006943 if (*outbytes == NULL) {
6944 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00006945 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006946 }
Victor Stinner3a50e702011-10-18 21:21:00 +02006947 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006948 }
6949 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006951 const Py_ssize_t n = PyBytes_Size(*outbytes);
6952 if (outsize > PY_SSIZE_T_MAX - n) {
6953 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01006954 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00006955 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006956 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01006957 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
6958 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006959 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006960 }
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006962 }
6963
6964 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006965 outsize = WideCharToMultiByte(code_page, flags,
6966 p, size,
6967 out, outsize,
6968 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006969 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006970 if (outsize <= 0)
6971 goto error;
6972 if (pusedDefaultChar && *pusedDefaultChar)
6973 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006974 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006975
Victor Stinner3a50e702011-10-18 21:21:00 +02006976error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01006977 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006978 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6979 return -2;
6980 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006981 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006982}
6983
Victor Stinner3a50e702011-10-18 21:21:00 +02006984/*
6985 * Encode a Unicode string to a Windows code page into a byte string using a
6986 * error handler.
6987 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006988 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02006989 * -1 on other error.
6990 */
6991static int
6992encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01006993 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01006994 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006995{
Victor Stinner3a50e702011-10-18 21:21:00 +02006996 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006997 Py_ssize_t pos = unicode_offset;
6998 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006999 /* Ideally, we should get reason from FormatMessage. This is the Windows
7000 2000 English version of the message. */
7001 const char *reason = "invalid character";
7002 /* 4=maximum length of a UTF-8 sequence */
7003 char buffer[4];
7004 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7005 Py_ssize_t outsize;
7006 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007007 PyObject *errorHandler = NULL;
7008 PyObject *exc = NULL;
7009 PyObject *encoding_obj = NULL;
7010 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007011 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007012 PyObject *rep;
7013 int ret = -1;
7014
7015 assert(insize > 0);
7016
7017 encoding = code_page_name(code_page, &encoding_obj);
7018 if (encoding == NULL)
7019 return -1;
7020
7021 if (errors == NULL || strcmp(errors, "strict") == 0) {
7022 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7023 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007024 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007025 if (exc != NULL) {
7026 PyCodec_StrictErrors(exc);
7027 Py_DECREF(exc);
7028 }
7029 Py_XDECREF(encoding_obj);
7030 return -1;
7031 }
7032
7033 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7034 pusedDefaultChar = &usedDefaultChar;
7035 else
7036 pusedDefaultChar = NULL;
7037
7038 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7039 PyErr_NoMemory();
7040 goto error;
7041 }
7042 outsize = insize * Py_ARRAY_LENGTH(buffer);
7043
7044 if (*outbytes == NULL) {
7045 /* Create string object */
7046 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7047 if (*outbytes == NULL)
7048 goto error;
7049 out = PyBytes_AS_STRING(*outbytes);
7050 }
7051 else {
7052 /* Extend string object */
7053 Py_ssize_t n = PyBytes_Size(*outbytes);
7054 if (n > PY_SSIZE_T_MAX - outsize) {
7055 PyErr_NoMemory();
7056 goto error;
7057 }
7058 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7059 goto error;
7060 out = PyBytes_AS_STRING(*outbytes) + n;
7061 }
7062
7063 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007064 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007066 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7067 wchar_t chars[2];
7068 int charsize;
7069 if (ch < 0x10000) {
7070 chars[0] = (wchar_t)ch;
7071 charsize = 1;
7072 }
7073 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007074 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7075 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007076 charsize = 2;
7077 }
7078
Victor Stinner3a50e702011-10-18 21:21:00 +02007079 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007080 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 buffer, Py_ARRAY_LENGTH(buffer),
7082 NULL, pusedDefaultChar);
7083 if (outsize > 0) {
7084 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7085 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007086 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007087 memcpy(out, buffer, outsize);
7088 out += outsize;
7089 continue;
7090 }
7091 }
7092 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7093 PyErr_SetFromWindowsErr(0);
7094 goto error;
7095 }
7096
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 rep = unicode_encode_call_errorhandler(
7098 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007099 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007100 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 if (rep == NULL)
7102 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007103 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007104
7105 if (PyBytes_Check(rep)) {
7106 outsize = PyBytes_GET_SIZE(rep);
7107 if (outsize != 1) {
7108 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7109 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7110 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7111 Py_DECREF(rep);
7112 goto error;
7113 }
7114 out = PyBytes_AS_STRING(*outbytes) + offset;
7115 }
7116 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7117 out += outsize;
7118 }
7119 else {
7120 Py_ssize_t i;
7121 enum PyUnicode_Kind kind;
7122 void *data;
7123
Benjamin Petersonbac79492012-01-14 13:34:47 -05007124 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007125 Py_DECREF(rep);
7126 goto error;
7127 }
7128
7129 outsize = PyUnicode_GET_LENGTH(rep);
7130 if (outsize != 1) {
7131 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7132 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7133 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7134 Py_DECREF(rep);
7135 goto error;
7136 }
7137 out = PyBytes_AS_STRING(*outbytes) + offset;
7138 }
7139 kind = PyUnicode_KIND(rep);
7140 data = PyUnicode_DATA(rep);
7141 for (i=0; i < outsize; i++) {
7142 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7143 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007144 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007145 encoding, unicode,
7146 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 "unable to encode error handler result to ASCII");
7148 Py_DECREF(rep);
7149 goto error;
7150 }
7151 *out = (unsigned char)ch;
7152 out++;
7153 }
7154 }
7155 Py_DECREF(rep);
7156 }
7157 /* write a NUL byte */
7158 *out = 0;
7159 outsize = out - PyBytes_AS_STRING(*outbytes);
7160 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7161 if (_PyBytes_Resize(outbytes, outsize) < 0)
7162 goto error;
7163 ret = 0;
7164
7165error:
7166 Py_XDECREF(encoding_obj);
7167 Py_XDECREF(errorHandler);
7168 Py_XDECREF(exc);
7169 return ret;
7170}
7171
Victor Stinner3a50e702011-10-18 21:21:00 +02007172static PyObject *
7173encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007174 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 const char *errors)
7176{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007177 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007179 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007180 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007181
Benjamin Petersonbac79492012-01-14 13:34:47 -05007182 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 return NULL;
7184 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007185
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 if (code_page < 0) {
7187 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7188 return NULL;
7189 }
7190
Martin v. Löwis3d325192011-11-04 18:23:06 +01007191 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007192 return PyBytes_FromStringAndSize(NULL, 0);
7193
Victor Stinner7581cef2011-11-03 22:32:33 +01007194 offset = 0;
7195 do
7196 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007198 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007199 chunks. */
7200 if (len > INT_MAX/2) {
7201 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007202 done = 0;
7203 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007204 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007205#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007206 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007207 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007208 done = 1;
7209 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007210
Victor Stinner76a31a62011-11-04 00:05:13 +01007211 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007212 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007213 errors);
7214 if (ret == -2)
7215 ret = encode_code_page_errors(code_page, &outbytes,
7216 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007217 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007218 if (ret < 0) {
7219 Py_XDECREF(outbytes);
7220 return NULL;
7221 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007222
Victor Stinner7581cef2011-11-03 22:32:33 +01007223 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007224 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007225 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007226
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 return outbytes;
7228}
7229
7230PyObject *
7231PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7232 Py_ssize_t size,
7233 const char *errors)
7234{
Victor Stinner7581cef2011-11-03 22:32:33 +01007235 PyObject *unicode, *res;
7236 unicode = PyUnicode_FromUnicode(p, size);
7237 if (unicode == NULL)
7238 return NULL;
7239 res = encode_code_page(CP_ACP, unicode, errors);
7240 Py_DECREF(unicode);
7241 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007242}
7243
7244PyObject *
7245PyUnicode_EncodeCodePage(int code_page,
7246 PyObject *unicode,
7247 const char *errors)
7248{
Victor Stinner7581cef2011-11-03 22:32:33 +01007249 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007250}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007251
Alexander Belopolsky40018472011-02-26 01:02:56 +00007252PyObject *
7253PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007254{
7255 if (!PyUnicode_Check(unicode)) {
7256 PyErr_BadArgument();
7257 return NULL;
7258 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007259 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007260}
7261
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007262#undef NEED_RETRY
7263
Victor Stinner99b95382011-07-04 14:23:54 +02007264#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007265
Guido van Rossumd57fd912000-03-10 22:53:23 +00007266/* --- Character Mapping Codec -------------------------------------------- */
7267
Victor Stinnerfb161b12013-04-18 01:44:27 +02007268static int
7269charmap_decode_string(const char *s,
7270 Py_ssize_t size,
7271 PyObject *mapping,
7272 const char *errors,
7273 _PyUnicodeWriter *writer)
7274{
7275 const char *starts = s;
7276 const char *e;
7277 Py_ssize_t startinpos, endinpos;
7278 PyObject *errorHandler = NULL, *exc = NULL;
7279 Py_ssize_t maplen;
7280 enum PyUnicode_Kind mapkind;
7281 void *mapdata;
7282 Py_UCS4 x;
7283 unsigned char ch;
7284
7285 if (PyUnicode_READY(mapping) == -1)
7286 return -1;
7287
7288 maplen = PyUnicode_GET_LENGTH(mapping);
7289 mapdata = PyUnicode_DATA(mapping);
7290 mapkind = PyUnicode_KIND(mapping);
7291
7292 e = s + size;
7293
7294 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7295 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7296 * is disabled in encoding aliases, latin1 is preferred because
7297 * its implementation is faster. */
7298 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7299 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7300 Py_UCS4 maxchar = writer->maxchar;
7301
7302 assert (writer->kind == PyUnicode_1BYTE_KIND);
7303 while (s < e) {
7304 ch = *s;
7305 x = mapdata_ucs1[ch];
7306 if (x > maxchar) {
7307 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7308 goto onError;
7309 maxchar = writer->maxchar;
7310 outdata = (Py_UCS1 *)writer->data;
7311 }
7312 outdata[writer->pos] = x;
7313 writer->pos++;
7314 ++s;
7315 }
7316 return 0;
7317 }
7318
7319 while (s < e) {
7320 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7321 enum PyUnicode_Kind outkind = writer->kind;
7322 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7323 if (outkind == PyUnicode_1BYTE_KIND) {
7324 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7325 Py_UCS4 maxchar = writer->maxchar;
7326 while (s < e) {
7327 ch = *s;
7328 x = mapdata_ucs2[ch];
7329 if (x > maxchar)
7330 goto Error;
7331 outdata[writer->pos] = x;
7332 writer->pos++;
7333 ++s;
7334 }
7335 break;
7336 }
7337 else if (outkind == PyUnicode_2BYTE_KIND) {
7338 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7339 while (s < e) {
7340 ch = *s;
7341 x = mapdata_ucs2[ch];
7342 if (x == 0xFFFE)
7343 goto Error;
7344 outdata[writer->pos] = x;
7345 writer->pos++;
7346 ++s;
7347 }
7348 break;
7349 }
7350 }
7351 ch = *s;
7352
7353 if (ch < maplen)
7354 x = PyUnicode_READ(mapkind, mapdata, ch);
7355 else
7356 x = 0xfffe; /* invalid value */
7357Error:
7358 if (x == 0xfffe)
7359 {
7360 /* undefined mapping */
7361 startinpos = s-starts;
7362 endinpos = startinpos+1;
7363 if (unicode_decode_call_errorhandler_writer(
7364 errors, &errorHandler,
7365 "charmap", "character maps to <undefined>",
7366 &starts, &e, &startinpos, &endinpos, &exc, &s,
7367 writer)) {
7368 goto onError;
7369 }
7370 continue;
7371 }
7372
7373 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7374 goto onError;
7375 ++s;
7376 }
7377 Py_XDECREF(errorHandler);
7378 Py_XDECREF(exc);
7379 return 0;
7380
7381onError:
7382 Py_XDECREF(errorHandler);
7383 Py_XDECREF(exc);
7384 return -1;
7385}
7386
7387static int
7388charmap_decode_mapping(const char *s,
7389 Py_ssize_t size,
7390 PyObject *mapping,
7391 const char *errors,
7392 _PyUnicodeWriter *writer)
7393{
7394 const char *starts = s;
7395 const char *e;
7396 Py_ssize_t startinpos, endinpos;
7397 PyObject *errorHandler = NULL, *exc = NULL;
7398 unsigned char ch;
7399 PyObject *key, *item;
7400
7401 e = s + size;
7402
7403 while (s < e) {
7404 ch = *s;
7405
7406 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7407 key = PyLong_FromLong((long)ch);
7408 if (key == NULL)
7409 goto onError;
7410
7411 item = PyObject_GetItem(mapping, key);
7412 Py_DECREF(key);
7413 if (item == NULL) {
7414 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7415 /* No mapping found means: mapping is undefined. */
7416 PyErr_Clear();
7417 goto Undefined;
7418 } else
7419 goto onError;
7420 }
7421
7422 /* Apply mapping */
7423 if (item == Py_None)
7424 goto Undefined;
7425 if (PyLong_Check(item)) {
7426 long value = PyLong_AS_LONG(item);
7427 if (value == 0xFFFE)
7428 goto Undefined;
7429 if (value < 0 || value > MAX_UNICODE) {
7430 PyErr_Format(PyExc_TypeError,
7431 "character mapping must be in range(0x%lx)",
7432 (unsigned long)MAX_UNICODE + 1);
7433 goto onError;
7434 }
7435
7436 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7437 goto onError;
7438 }
7439 else if (PyUnicode_Check(item)) {
7440 if (PyUnicode_READY(item) == -1)
7441 goto onError;
7442 if (PyUnicode_GET_LENGTH(item) == 1) {
7443 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7444 if (value == 0xFFFE)
7445 goto Undefined;
7446 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7447 goto onError;
7448 }
7449 else {
7450 writer->overallocate = 1;
7451 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7452 goto onError;
7453 }
7454 }
7455 else {
7456 /* wrong return value */
7457 PyErr_SetString(PyExc_TypeError,
7458 "character mapping must return integer, None or str");
7459 goto onError;
7460 }
7461 Py_CLEAR(item);
7462 ++s;
7463 continue;
7464
7465Undefined:
7466 /* undefined mapping */
7467 Py_CLEAR(item);
7468 startinpos = s-starts;
7469 endinpos = startinpos+1;
7470 if (unicode_decode_call_errorhandler_writer(
7471 errors, &errorHandler,
7472 "charmap", "character maps to <undefined>",
7473 &starts, &e, &startinpos, &endinpos, &exc, &s,
7474 writer)) {
7475 goto onError;
7476 }
7477 }
7478 Py_XDECREF(errorHandler);
7479 Py_XDECREF(exc);
7480 return 0;
7481
7482onError:
7483 Py_XDECREF(item);
7484 Py_XDECREF(errorHandler);
7485 Py_XDECREF(exc);
7486 return -1;
7487}
7488
Alexander Belopolsky40018472011-02-26 01:02:56 +00007489PyObject *
7490PyUnicode_DecodeCharmap(const char *s,
7491 Py_ssize_t size,
7492 PyObject *mapping,
7493 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007494{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007495 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007496
Guido van Rossumd57fd912000-03-10 22:53:23 +00007497 /* Default to Latin-1 */
7498 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007500
Guido van Rossumd57fd912000-03-10 22:53:23 +00007501 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007502 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007503 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007504 writer.min_length = size;
7505 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007506 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007507
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007508 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007509 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7510 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007511 }
7512 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007513 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7514 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007515 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007516 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007517
Benjamin Peterson29060642009-01-31 22:14:21 +00007518 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007519 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007520 return NULL;
7521}
7522
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007523/* Charmap encoding: the lookup table */
7524
Alexander Belopolsky40018472011-02-26 01:02:56 +00007525struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007526 PyObject_HEAD
7527 unsigned char level1[32];
7528 int count2, count3;
7529 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007530};
7531
7532static PyObject*
7533encoding_map_size(PyObject *obj, PyObject* args)
7534{
7535 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007536 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007538}
7539
7540static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007541 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007542 PyDoc_STR("Return the size (in bytes) of this object") },
7543 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007544};
7545
7546static void
7547encoding_map_dealloc(PyObject* o)
7548{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007549 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007550}
7551
7552static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007553 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007554 "EncodingMap", /*tp_name*/
7555 sizeof(struct encoding_map), /*tp_basicsize*/
7556 0, /*tp_itemsize*/
7557 /* methods */
7558 encoding_map_dealloc, /*tp_dealloc*/
7559 0, /*tp_print*/
7560 0, /*tp_getattr*/
7561 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007562 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007563 0, /*tp_repr*/
7564 0, /*tp_as_number*/
7565 0, /*tp_as_sequence*/
7566 0, /*tp_as_mapping*/
7567 0, /*tp_hash*/
7568 0, /*tp_call*/
7569 0, /*tp_str*/
7570 0, /*tp_getattro*/
7571 0, /*tp_setattro*/
7572 0, /*tp_as_buffer*/
7573 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7574 0, /*tp_doc*/
7575 0, /*tp_traverse*/
7576 0, /*tp_clear*/
7577 0, /*tp_richcompare*/
7578 0, /*tp_weaklistoffset*/
7579 0, /*tp_iter*/
7580 0, /*tp_iternext*/
7581 encoding_map_methods, /*tp_methods*/
7582 0, /*tp_members*/
7583 0, /*tp_getset*/
7584 0, /*tp_base*/
7585 0, /*tp_dict*/
7586 0, /*tp_descr_get*/
7587 0, /*tp_descr_set*/
7588 0, /*tp_dictoffset*/
7589 0, /*tp_init*/
7590 0, /*tp_alloc*/
7591 0, /*tp_new*/
7592 0, /*tp_free*/
7593 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007594};
7595
7596PyObject*
7597PyUnicode_BuildEncodingMap(PyObject* string)
7598{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007599 PyObject *result;
7600 struct encoding_map *mresult;
7601 int i;
7602 int need_dict = 0;
7603 unsigned char level1[32];
7604 unsigned char level2[512];
7605 unsigned char *mlevel1, *mlevel2, *mlevel3;
7606 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007607 int kind;
7608 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007609 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007610 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007611
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007612 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007613 PyErr_BadArgument();
7614 return NULL;
7615 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007616 kind = PyUnicode_KIND(string);
7617 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007618 length = PyUnicode_GET_LENGTH(string);
7619 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007620 memset(level1, 0xFF, sizeof level1);
7621 memset(level2, 0xFF, sizeof level2);
7622
7623 /* If there isn't a one-to-one mapping of NULL to \0,
7624 or if there are non-BMP characters, we need to use
7625 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007626 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007627 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007628 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007629 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007630 ch = PyUnicode_READ(kind, data, i);
7631 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007632 need_dict = 1;
7633 break;
7634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007635 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007636 /* unmapped character */
7637 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007638 l1 = ch >> 11;
7639 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007640 if (level1[l1] == 0xFF)
7641 level1[l1] = count2++;
7642 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007643 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007644 }
7645
7646 if (count2 >= 0xFF || count3 >= 0xFF)
7647 need_dict = 1;
7648
7649 if (need_dict) {
7650 PyObject *result = PyDict_New();
7651 PyObject *key, *value;
7652 if (!result)
7653 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007654 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007655 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007656 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007657 if (!key || !value)
7658 goto failed1;
7659 if (PyDict_SetItem(result, key, value) == -1)
7660 goto failed1;
7661 Py_DECREF(key);
7662 Py_DECREF(value);
7663 }
7664 return result;
7665 failed1:
7666 Py_XDECREF(key);
7667 Py_XDECREF(value);
7668 Py_DECREF(result);
7669 return NULL;
7670 }
7671
7672 /* Create a three-level trie */
7673 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7674 16*count2 + 128*count3 - 1);
7675 if (!result)
7676 return PyErr_NoMemory();
7677 PyObject_Init(result, &EncodingMapType);
7678 mresult = (struct encoding_map*)result;
7679 mresult->count2 = count2;
7680 mresult->count3 = count3;
7681 mlevel1 = mresult->level1;
7682 mlevel2 = mresult->level23;
7683 mlevel3 = mresult->level23 + 16*count2;
7684 memcpy(mlevel1, level1, 32);
7685 memset(mlevel2, 0xFF, 16*count2);
7686 memset(mlevel3, 0, 128*count3);
7687 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007688 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007689 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007690 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7691 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007692 /* unmapped character */
7693 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007694 o1 = ch>>11;
7695 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007696 i2 = 16*mlevel1[o1] + o2;
7697 if (mlevel2[i2] == 0xFF)
7698 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007699 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007700 i3 = 128*mlevel2[i2] + o3;
7701 mlevel3[i3] = i;
7702 }
7703 return result;
7704}
7705
7706static int
Victor Stinner22168992011-11-20 17:09:18 +01007707encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007708{
7709 struct encoding_map *map = (struct encoding_map*)mapping;
7710 int l1 = c>>11;
7711 int l2 = (c>>7) & 0xF;
7712 int l3 = c & 0x7F;
7713 int i;
7714
Victor Stinner22168992011-11-20 17:09:18 +01007715 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007716 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007717 if (c == 0)
7718 return 0;
7719 /* level 1*/
7720 i = map->level1[l1];
7721 if (i == 0xFF) {
7722 return -1;
7723 }
7724 /* level 2*/
7725 i = map->level23[16*i+l2];
7726 if (i == 0xFF) {
7727 return -1;
7728 }
7729 /* level 3 */
7730 i = map->level23[16*map->count2 + 128*i + l3];
7731 if (i == 0) {
7732 return -1;
7733 }
7734 return i;
7735}
7736
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007737/* Lookup the character ch in the mapping. If the character
7738 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007739 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007740static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007741charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742{
Christian Heimes217cfd12007-12-02 14:31:20 +00007743 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007744 PyObject *x;
7745
7746 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007747 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007748 x = PyObject_GetItem(mapping, w);
7749 Py_DECREF(w);
7750 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7752 /* No mapping found means: mapping is undefined. */
7753 PyErr_Clear();
7754 x = Py_None;
7755 Py_INCREF(x);
7756 return x;
7757 } else
7758 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007759 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007760 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007761 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007762 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007763 long value = PyLong_AS_LONG(x);
7764 if (value < 0 || value > 255) {
7765 PyErr_SetString(PyExc_TypeError,
7766 "character mapping must be in range(256)");
7767 Py_DECREF(x);
7768 return NULL;
7769 }
7770 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007772 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007774 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 /* wrong return value */
7776 PyErr_Format(PyExc_TypeError,
7777 "character mapping must return integer, bytes or None, not %.400s",
7778 x->ob_type->tp_name);
7779 Py_DECREF(x);
7780 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781 }
7782}
7783
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007784static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007785charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007786{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007787 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7788 /* exponentially overallocate to minimize reallocations */
7789 if (requiredsize < 2*outsize)
7790 requiredsize = 2*outsize;
7791 if (_PyBytes_Resize(outobj, requiredsize))
7792 return -1;
7793 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007794}
7795
Benjamin Peterson14339b62009-01-31 16:36:08 +00007796typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007798} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007799/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007800 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007801 space is available. Return a new reference to the object that
7802 was put in the output buffer, or Py_None, if the mapping was undefined
7803 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007804 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007805static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007806charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007807 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007808{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007809 PyObject *rep;
7810 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007811 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007812
Christian Heimes90aa7642007-12-19 02:45:37 +00007813 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007814 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007815 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007816 if (res == -1)
7817 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 if (outsize<requiredsize)
7819 if (charmapencode_resize(outobj, outpos, requiredsize))
7820 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007821 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 outstart[(*outpos)++] = (char)res;
7823 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007824 }
7825
7826 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007827 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 Py_DECREF(rep);
7831 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007832 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 if (PyLong_Check(rep)) {
7834 Py_ssize_t requiredsize = *outpos+1;
7835 if (outsize<requiredsize)
7836 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7837 Py_DECREF(rep);
7838 return enc_EXCEPTION;
7839 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007840 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007842 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 else {
7844 const char *repchars = PyBytes_AS_STRING(rep);
7845 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7846 Py_ssize_t requiredsize = *outpos+repsize;
7847 if (outsize<requiredsize)
7848 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7849 Py_DECREF(rep);
7850 return enc_EXCEPTION;
7851 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007852 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007853 memcpy(outstart + *outpos, repchars, repsize);
7854 *outpos += repsize;
7855 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007856 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007857 Py_DECREF(rep);
7858 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007859}
7860
7861/* handle an error in PyUnicode_EncodeCharmap
7862 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007863static int
7864charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007865 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007866 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007867 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007868 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007869{
7870 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007871 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007872 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007873 enum PyUnicode_Kind kind;
7874 void *data;
7875 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007876 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007877 Py_ssize_t collstartpos = *inpos;
7878 Py_ssize_t collendpos = *inpos+1;
7879 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007880 char *encoding = "charmap";
7881 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007883 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007884 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007885
Benjamin Petersonbac79492012-01-14 13:34:47 -05007886 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007887 return -1;
7888 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007889 /* find all unencodable characters */
7890 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007891 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007892 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007893 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007894 val = encoding_map_lookup(ch, mapping);
7895 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 break;
7897 ++collendpos;
7898 continue;
7899 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007900
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007901 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7902 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 if (rep==NULL)
7904 return -1;
7905 else if (rep!=Py_None) {
7906 Py_DECREF(rep);
7907 break;
7908 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007909 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007910 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007911 }
7912 /* cache callback name lookup
7913 * (if not done yet, i.e. it's the first error) */
7914 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 if ((errors==NULL) || (!strcmp(errors, "strict")))
7916 *known_errorHandler = 1;
7917 else if (!strcmp(errors, "replace"))
7918 *known_errorHandler = 2;
7919 else if (!strcmp(errors, "ignore"))
7920 *known_errorHandler = 3;
7921 else if (!strcmp(errors, "xmlcharrefreplace"))
7922 *known_errorHandler = 4;
7923 else
7924 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007925 }
7926 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007927 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007928 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007929 return -1;
7930 case 2: /* replace */
7931 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 x = charmapencode_output('?', mapping, res, respos);
7933 if (x==enc_EXCEPTION) {
7934 return -1;
7935 }
7936 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007937 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007938 return -1;
7939 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007940 }
7941 /* fall through */
7942 case 3: /* ignore */
7943 *inpos = collendpos;
7944 break;
7945 case 4: /* xmlcharrefreplace */
7946 /* generate replacement (temporarily (mis)uses p) */
7947 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 char buffer[2+29+1+1];
7949 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007950 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 for (cp = buffer; *cp; ++cp) {
7952 x = charmapencode_output(*cp, mapping, res, respos);
7953 if (x==enc_EXCEPTION)
7954 return -1;
7955 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007956 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 return -1;
7958 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007959 }
7960 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007961 *inpos = collendpos;
7962 break;
7963 default:
7964 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007965 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00007966 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007967 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007969 if (PyBytes_Check(repunicode)) {
7970 /* Directly copy bytes result to output. */
7971 Py_ssize_t outsize = PyBytes_Size(*res);
7972 Py_ssize_t requiredsize;
7973 repsize = PyBytes_Size(repunicode);
7974 requiredsize = *respos + repsize;
7975 if (requiredsize > outsize)
7976 /* Make room for all additional bytes. */
7977 if (charmapencode_resize(res, respos, requiredsize)) {
7978 Py_DECREF(repunicode);
7979 return -1;
7980 }
7981 memcpy(PyBytes_AsString(*res) + *respos,
7982 PyBytes_AsString(repunicode), repsize);
7983 *respos += repsize;
7984 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007985 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007986 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007987 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007988 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05007989 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007990 Py_DECREF(repunicode);
7991 return -1;
7992 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01007993 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007994 data = PyUnicode_DATA(repunicode);
7995 kind = PyUnicode_KIND(repunicode);
7996 for (index = 0; index < repsize; index++) {
7997 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
7998 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008000 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008001 return -1;
8002 }
8003 else if (x==enc_FAILED) {
8004 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008005 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008006 return -1;
8007 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008008 }
8009 *inpos = newpos;
8010 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008011 }
8012 return 0;
8013}
8014
Alexander Belopolsky40018472011-02-26 01:02:56 +00008015PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008016_PyUnicode_EncodeCharmap(PyObject *unicode,
8017 PyObject *mapping,
8018 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008020 /* output object */
8021 PyObject *res = NULL;
8022 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008023 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008024 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008025 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008026 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008027 PyObject *errorHandler = NULL;
8028 PyObject *exc = NULL;
8029 /* the following variable is used for caching string comparisons
8030 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8031 * 3=ignore, 4=xmlcharrefreplace */
8032 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008033 void *data;
8034 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008035
Benjamin Petersonbac79492012-01-14 13:34:47 -05008036 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008037 return NULL;
8038 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008039 data = PyUnicode_DATA(unicode);
8040 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008041
Guido van Rossumd57fd912000-03-10 22:53:23 +00008042 /* Default to Latin-1 */
8043 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008044 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008045
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008046 /* allocate enough for a simple encoding without
8047 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008048 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049 if (res == NULL)
8050 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008051 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008053
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008054 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008055 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008057 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 if (x==enc_EXCEPTION) /* error */
8059 goto onError;
8060 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008061 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 &exc,
8063 &known_errorHandler, &errorHandler, errors,
8064 &res, &respos)) {
8065 goto onError;
8066 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008067 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 else
8069 /* done with this character => adjust input position */
8070 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008071 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008072
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008073 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008074 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008075 if (_PyBytes_Resize(&res, respos) < 0)
8076 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008077
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078 Py_XDECREF(exc);
8079 Py_XDECREF(errorHandler);
8080 return res;
8081
Benjamin Peterson29060642009-01-31 22:14:21 +00008082 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008083 Py_XDECREF(res);
8084 Py_XDECREF(exc);
8085 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008086 return NULL;
8087}
8088
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008089/* Deprecated */
8090PyObject *
8091PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8092 Py_ssize_t size,
8093 PyObject *mapping,
8094 const char *errors)
8095{
8096 PyObject *result;
8097 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8098 if (unicode == NULL)
8099 return NULL;
8100 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8101 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008102 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008103}
8104
Alexander Belopolsky40018472011-02-26 01:02:56 +00008105PyObject *
8106PyUnicode_AsCharmapString(PyObject *unicode,
8107 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008108{
8109 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008110 PyErr_BadArgument();
8111 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008112 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008113 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008114}
8115
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008116/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008117static void
8118make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008119 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008120 Py_ssize_t startpos, Py_ssize_t endpos,
8121 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008122{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008123 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008124 *exceptionObject = _PyUnicodeTranslateError_Create(
8125 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 }
8127 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8129 goto onError;
8130 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8131 goto onError;
8132 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8133 goto onError;
8134 return;
8135 onError:
8136 Py_DECREF(*exceptionObject);
8137 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008138 }
8139}
8140
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141/* error handling callback helper:
8142 build arguments, call the callback and check the arguments,
8143 put the result into newpos and return the replacement string, which
8144 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008145static PyObject *
8146unicode_translate_call_errorhandler(const char *errors,
8147 PyObject **errorHandler,
8148 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008149 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008150 Py_ssize_t startpos, Py_ssize_t endpos,
8151 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008153 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008155 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008156 PyObject *restuple;
8157 PyObject *resunicode;
8158
8159 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008161 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008163 }
8164
8165 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008166 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008167 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008169
8170 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008174 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008175 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 Py_DECREF(restuple);
8177 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178 }
8179 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 &resunicode, &i_newpos)) {
8181 Py_DECREF(restuple);
8182 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008183 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008184 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008185 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008186 else
8187 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008188 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008189 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8190 Py_DECREF(restuple);
8191 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008192 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008193 Py_INCREF(resunicode);
8194 Py_DECREF(restuple);
8195 return resunicode;
8196}
8197
8198/* Lookup the character ch in the mapping and put the result in result,
8199 which must be decrefed by the caller.
8200 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008202charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008203{
Christian Heimes217cfd12007-12-02 14:31:20 +00008204 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205 PyObject *x;
8206
8207 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008209 x = PyObject_GetItem(mapping, w);
8210 Py_DECREF(w);
8211 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8213 /* No mapping found means: use 1:1 mapping. */
8214 PyErr_Clear();
8215 *result = NULL;
8216 return 0;
8217 } else
8218 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008219 }
8220 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008221 *result = x;
8222 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008224 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 long value = PyLong_AS_LONG(x);
8226 long max = PyUnicode_GetMax();
8227 if (value < 0 || value > max) {
8228 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008229 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 Py_DECREF(x);
8231 return -1;
8232 }
8233 *result = x;
8234 return 0;
8235 }
8236 else if (PyUnicode_Check(x)) {
8237 *result = x;
8238 return 0;
8239 }
8240 else {
8241 /* wrong return value */
8242 PyErr_SetString(PyExc_TypeError,
8243 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008244 Py_DECREF(x);
8245 return -1;
8246 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247}
8248/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 if not reallocate and adjust various state variables.
8250 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008251static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008252charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008254{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008255 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008256 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008257 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 /* exponentially overallocate to minimize reallocations */
8259 if (requiredsize < 2 * oldsize)
8260 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008261 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8262 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008264 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008265 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 }
8267 return 0;
8268}
8269/* lookup the character, put the result in the output string and adjust
8270 various state variables. Return a new reference to the object that
8271 was put in the output buffer in *result, or Py_None, if the mapping was
8272 undefined (in which case no character was written).
8273 The called must decref result.
8274 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008275static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008276charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8277 PyObject *mapping, Py_UCS4 **output,
8278 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008279 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8282 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008283 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008286 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 }
8288 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008290 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008292 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 }
8294 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008295 Py_ssize_t repsize;
8296 if (PyUnicode_READY(*res) == -1)
8297 return -1;
8298 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (repsize==1) {
8300 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008301 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 }
8303 else if (repsize!=0) {
8304 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008305 Py_ssize_t requiredsize = *opos +
8306 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008308 Py_ssize_t i;
8309 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008311 for(i = 0; i < repsize; i++)
8312 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 }
8315 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 return 0;
8318}
8319
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008321_PyUnicode_TranslateCharmap(PyObject *input,
8322 PyObject *mapping,
8323 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008325 /* input object */
8326 char *idata;
8327 Py_ssize_t size, i;
8328 int kind;
8329 /* output buffer */
8330 Py_UCS4 *output = NULL;
8331 Py_ssize_t osize;
8332 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008334 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 char *reason = "character maps to <undefined>";
8336 PyObject *errorHandler = NULL;
8337 PyObject *exc = NULL;
8338 /* the following variable is used for caching string comparisons
8339 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8340 * 3=ignore, 4=xmlcharrefreplace */
8341 int known_errorHandler = -1;
8342
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 PyErr_BadArgument();
8345 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008346 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008348 if (PyUnicode_READY(input) == -1)
8349 return NULL;
8350 idata = (char*)PyUnicode_DATA(input);
8351 kind = PyUnicode_KIND(input);
8352 size = PyUnicode_GET_LENGTH(input);
8353 i = 0;
8354
8355 if (size == 0) {
8356 Py_INCREF(input);
8357 return input;
8358 }
8359
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 /* allocate enough for a simple 1:1 translation without
8361 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008362 osize = size;
8363 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8364 opos = 0;
8365 if (output == NULL) {
8366 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008368 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008370 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 /* try to encode it */
8372 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373 if (charmaptranslate_output(input, i, mapping,
8374 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 Py_XDECREF(x);
8376 goto onError;
8377 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008378 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008380 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 else { /* untranslatable character */
8382 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8383 Py_ssize_t repsize;
8384 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008387 Py_ssize_t collstart = i;
8388 Py_ssize_t collend = i+1;
8389 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008390
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 while (collend < size) {
8393 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 goto onError;
8395 Py_XDECREF(x);
8396 if (x!=Py_None)
8397 break;
8398 ++collend;
8399 }
8400 /* cache callback name lookup
8401 * (if not done yet, i.e. it's the first error) */
8402 if (known_errorHandler==-1) {
8403 if ((errors==NULL) || (!strcmp(errors, "strict")))
8404 known_errorHandler = 1;
8405 else if (!strcmp(errors, "replace"))
8406 known_errorHandler = 2;
8407 else if (!strcmp(errors, "ignore"))
8408 known_errorHandler = 3;
8409 else if (!strcmp(errors, "xmlcharrefreplace"))
8410 known_errorHandler = 4;
8411 else
8412 known_errorHandler = 0;
8413 }
8414 switch (known_errorHandler) {
8415 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008416 make_translate_exception(&exc,
8417 input, collstart, collend, reason);
8418 if (exc != NULL)
8419 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008420 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 case 2: /* replace */
8422 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008423 for (coll = collstart; coll<collend; coll++)
8424 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 /* fall through */
8426 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008427 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 break;
8429 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 /* generate replacement (temporarily (mis)uses i) */
8431 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 char buffer[2+29+1+1];
8433 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008434 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8435 if (charmaptranslate_makespace(&output, &osize,
8436 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 goto onError;
8438 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008441 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 break;
8443 default:
8444 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 reason, input, &exc,
8446 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008447 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008449 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008450 Py_DECREF(repunicode);
8451 goto onError;
8452 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 repsize = PyUnicode_GET_LENGTH(repunicode);
8455 if (charmaptranslate_makespace(&output, &osize,
8456 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 Py_DECREF(repunicode);
8458 goto onError;
8459 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 for (uni2 = 0; repsize-->0; ++uni2)
8461 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8462 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008464 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465 }
8466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8468 if (!res)
8469 goto onError;
8470 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 Py_XDECREF(exc);
8472 Py_XDECREF(errorHandler);
8473 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008474
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008476 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477 Py_XDECREF(exc);
8478 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008479 return NULL;
8480}
8481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008482/* Deprecated. Use PyUnicode_Translate instead. */
8483PyObject *
8484PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8485 Py_ssize_t size,
8486 PyObject *mapping,
8487 const char *errors)
8488{
Christian Heimes5f520f42012-09-11 14:03:25 +02008489 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8491 if (!unicode)
8492 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008493 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8494 Py_DECREF(unicode);
8495 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008496}
8497
Alexander Belopolsky40018472011-02-26 01:02:56 +00008498PyObject *
8499PyUnicode_Translate(PyObject *str,
8500 PyObject *mapping,
8501 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008502{
8503 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008504
Guido van Rossumd57fd912000-03-10 22:53:23 +00008505 str = PyUnicode_FromObject(str);
8506 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008507 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509 Py_DECREF(str);
8510 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008511}
Tim Petersced69f82003-09-16 20:30:58 +00008512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008514fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515{
8516 /* No need to call PyUnicode_READY(self) because this function is only
8517 called as a callback from fixup() which does it already. */
8518 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8519 const int kind = PyUnicode_KIND(self);
8520 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008521 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008522 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008523 Py_ssize_t i;
8524
8525 for (i = 0; i < len; ++i) {
8526 ch = PyUnicode_READ(kind, data, i);
8527 fixed = 0;
8528 if (ch > 127) {
8529 if (Py_UNICODE_ISSPACE(ch))
8530 fixed = ' ';
8531 else {
8532 const int decimal = Py_UNICODE_TODECIMAL(ch);
8533 if (decimal >= 0)
8534 fixed = '0' + decimal;
8535 }
8536 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008537 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008538 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008539 PyUnicode_WRITE(kind, data, i, fixed);
8540 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008541 else
8542 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 }
8545
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008546 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008547}
8548
8549PyObject *
8550_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8551{
8552 if (!PyUnicode_Check(unicode)) {
8553 PyErr_BadInternalCall();
8554 return NULL;
8555 }
8556 if (PyUnicode_READY(unicode) == -1)
8557 return NULL;
8558 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8559 /* If the string is already ASCII, just return the same string */
8560 Py_INCREF(unicode);
8561 return unicode;
8562 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008563 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008564}
8565
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008566PyObject *
8567PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8568 Py_ssize_t length)
8569{
Victor Stinnerf0124502011-11-21 23:12:56 +01008570 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008571 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008572 Py_UCS4 maxchar;
8573 enum PyUnicode_Kind kind;
8574 void *data;
8575
Victor Stinner99d7ad02012-02-22 13:37:39 +01008576 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008577 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008578 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008579 if (ch > 127) {
8580 int decimal = Py_UNICODE_TODECIMAL(ch);
8581 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008582 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008583 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008584 }
8585 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008586
8587 /* Copy to a new string */
8588 decimal = PyUnicode_New(length, maxchar);
8589 if (decimal == NULL)
8590 return decimal;
8591 kind = PyUnicode_KIND(decimal);
8592 data = PyUnicode_DATA(decimal);
8593 /* Iterate over code points */
8594 for (i = 0; i < length; i++) {
8595 Py_UNICODE ch = s[i];
8596 if (ch > 127) {
8597 int decimal = Py_UNICODE_TODECIMAL(ch);
8598 if (decimal >= 0)
8599 ch = '0' + decimal;
8600 }
8601 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008603 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008604}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008605/* --- Decimal Encoder ---------------------------------------------------- */
8606
Alexander Belopolsky40018472011-02-26 01:02:56 +00008607int
8608PyUnicode_EncodeDecimal(Py_UNICODE *s,
8609 Py_ssize_t length,
8610 char *output,
8611 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008612{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008613 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008614 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008615 enum PyUnicode_Kind kind;
8616 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008617
8618 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 PyErr_BadArgument();
8620 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008621 }
8622
Victor Stinner42bf7752011-11-21 22:52:58 +01008623 unicode = PyUnicode_FromUnicode(s, length);
8624 if (unicode == NULL)
8625 return -1;
8626
Benjamin Petersonbac79492012-01-14 13:34:47 -05008627 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008628 Py_DECREF(unicode);
8629 return -1;
8630 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008631 kind = PyUnicode_KIND(unicode);
8632 data = PyUnicode_DATA(unicode);
8633
Victor Stinnerb84d7232011-11-22 01:50:07 +01008634 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008635 PyObject *exc;
8636 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008638 Py_ssize_t startpos;
8639
8640 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008641
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008643 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008644 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008646 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 decimal = Py_UNICODE_TODECIMAL(ch);
8648 if (decimal >= 0) {
8649 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008650 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 continue;
8652 }
8653 if (0 < ch && ch < 256) {
8654 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008655 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 continue;
8657 }
Victor Stinner6345be92011-11-25 20:09:01 +01008658
Victor Stinner42bf7752011-11-21 22:52:58 +01008659 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008660 exc = NULL;
8661 raise_encode_exception(&exc, "decimal", unicode,
8662 startpos, startpos+1,
8663 "invalid decimal Unicode string");
8664 Py_XDECREF(exc);
8665 Py_DECREF(unicode);
8666 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008667 }
8668 /* 0-terminate the output string */
8669 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008670 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008671 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008672}
8673
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674/* --- Helpers ------------------------------------------------------------ */
8675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008676static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008677any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 Py_ssize_t start,
8679 Py_ssize_t end)
8680{
8681 int kind1, kind2, kind;
8682 void *buf1, *buf2;
8683 Py_ssize_t len1, len2, result;
8684
8685 kind1 = PyUnicode_KIND(s1);
8686 kind2 = PyUnicode_KIND(s2);
8687 kind = kind1 > kind2 ? kind1 : kind2;
8688 buf1 = PyUnicode_DATA(s1);
8689 buf2 = PyUnicode_DATA(s2);
8690 if (kind1 != kind)
8691 buf1 = _PyUnicode_AsKind(s1, kind);
8692 if (!buf1)
8693 return -2;
8694 if (kind2 != kind)
8695 buf2 = _PyUnicode_AsKind(s2, kind);
8696 if (!buf2) {
8697 if (kind1 != kind) PyMem_Free(buf1);
8698 return -2;
8699 }
8700 len1 = PyUnicode_GET_LENGTH(s1);
8701 len2 = PyUnicode_GET_LENGTH(s2);
8702
Victor Stinner794d5672011-10-10 03:21:36 +02008703 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008704 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008705 case PyUnicode_1BYTE_KIND:
8706 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8707 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8708 else
8709 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8710 break;
8711 case PyUnicode_2BYTE_KIND:
8712 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8713 break;
8714 case PyUnicode_4BYTE_KIND:
8715 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8716 break;
8717 default:
8718 assert(0); result = -2;
8719 }
8720 }
8721 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008722 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008723 case PyUnicode_1BYTE_KIND:
8724 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8725 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8726 else
8727 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8728 break;
8729 case PyUnicode_2BYTE_KIND:
8730 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8731 break;
8732 case PyUnicode_4BYTE_KIND:
8733 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8734 break;
8735 default:
8736 assert(0); result = -2;
8737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 }
8739
8740 if (kind1 != kind)
8741 PyMem_Free(buf1);
8742 if (kind2 != kind)
8743 PyMem_Free(buf2);
8744
8745 return result;
8746}
8747
8748Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008749_PyUnicode_InsertThousandsGrouping(
8750 PyObject *unicode, Py_ssize_t index,
8751 Py_ssize_t n_buffer,
8752 void *digits, Py_ssize_t n_digits,
8753 Py_ssize_t min_width,
8754 const char *grouping, PyObject *thousands_sep,
8755 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756{
Victor Stinner41a863c2012-02-24 00:37:51 +01008757 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008758 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008759 Py_ssize_t thousands_sep_len;
8760 Py_ssize_t len;
8761
8762 if (unicode != NULL) {
8763 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008764 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008765 }
8766 else {
8767 kind = PyUnicode_1BYTE_KIND;
8768 data = NULL;
8769 }
8770 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8771 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8772 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8773 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008774 if (thousands_sep_kind < kind) {
8775 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8776 if (!thousands_sep_data)
8777 return -1;
8778 }
8779 else {
8780 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8781 if (!data)
8782 return -1;
8783 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008784 }
8785
Benjamin Petersonead6b532011-12-20 17:23:42 -06008786 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008788 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008789 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008790 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008791 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008792 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008793 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008794 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008795 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008796 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008797 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008798 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008800 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008801 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008802 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008803 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008804 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008806 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008807 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008808 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008809 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008810 break;
8811 default:
8812 assert(0);
8813 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008815 if (unicode != NULL && thousands_sep_kind != kind) {
8816 if (thousands_sep_kind < kind)
8817 PyMem_Free(thousands_sep_data);
8818 else
8819 PyMem_Free(data);
8820 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008821 if (unicode == NULL) {
8822 *maxchar = 127;
8823 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008824 *maxchar = MAX_MAXCHAR(*maxchar,
8825 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008826 }
8827 }
8828 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829}
8830
8831
Thomas Wouters477c8d52006-05-27 19:21:47 +00008832/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008833#define ADJUST_INDICES(start, end, len) \
8834 if (end > len) \
8835 end = len; \
8836 else if (end < 0) { \
8837 end += len; \
8838 if (end < 0) \
8839 end = 0; \
8840 } \
8841 if (start < 0) { \
8842 start += len; \
8843 if (start < 0) \
8844 start = 0; \
8845 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008846
Alexander Belopolsky40018472011-02-26 01:02:56 +00008847Py_ssize_t
8848PyUnicode_Count(PyObject *str,
8849 PyObject *substr,
8850 Py_ssize_t start,
8851 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008852{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008853 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008854 PyObject* str_obj;
8855 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008856 int kind1, kind2, kind;
8857 void *buf1 = NULL, *buf2 = NULL;
8858 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008859
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008860 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008861 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008862 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008863 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008864 if (!sub_obj) {
8865 Py_DECREF(str_obj);
8866 return -1;
8867 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008868 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008869 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008870 Py_DECREF(str_obj);
8871 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008872 }
Tim Petersced69f82003-09-16 20:30:58 +00008873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874 kind1 = PyUnicode_KIND(str_obj);
8875 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008876 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008879 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008880 if (kind2 > kind) {
8881 Py_DECREF(sub_obj);
8882 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008883 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008884 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008885 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008886 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008887 if (!buf2)
8888 goto onError;
8889 len1 = PyUnicode_GET_LENGTH(str_obj);
8890 len2 = PyUnicode_GET_LENGTH(sub_obj);
8891
8892 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008893 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008894 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008895 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8896 result = asciilib_count(
8897 ((Py_UCS1*)buf1) + start, end - start,
8898 buf2, len2, PY_SSIZE_T_MAX
8899 );
8900 else
8901 result = ucs1lib_count(
8902 ((Py_UCS1*)buf1) + start, end - start,
8903 buf2, len2, PY_SSIZE_T_MAX
8904 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905 break;
8906 case PyUnicode_2BYTE_KIND:
8907 result = ucs2lib_count(
8908 ((Py_UCS2*)buf1) + start, end - start,
8909 buf2, len2, PY_SSIZE_T_MAX
8910 );
8911 break;
8912 case PyUnicode_4BYTE_KIND:
8913 result = ucs4lib_count(
8914 ((Py_UCS4*)buf1) + start, end - start,
8915 buf2, len2, PY_SSIZE_T_MAX
8916 );
8917 break;
8918 default:
8919 assert(0); result = 0;
8920 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008921
8922 Py_DECREF(sub_obj);
8923 Py_DECREF(str_obj);
8924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925 if (kind2 != kind)
8926 PyMem_Free(buf2);
8927
Guido van Rossumd57fd912000-03-10 22:53:23 +00008928 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008929 onError:
8930 Py_DECREF(sub_obj);
8931 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 if (kind2 != kind && buf2)
8933 PyMem_Free(buf2);
8934 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008935}
8936
Alexander Belopolsky40018472011-02-26 01:02:56 +00008937Py_ssize_t
8938PyUnicode_Find(PyObject *str,
8939 PyObject *sub,
8940 Py_ssize_t start,
8941 Py_ssize_t end,
8942 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008943{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008944 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008945
Guido van Rossumd57fd912000-03-10 22:53:23 +00008946 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008947 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00008948 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008949 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008950 if (!sub) {
8951 Py_DECREF(str);
8952 return -2;
8953 }
8954 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
8955 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00008956 Py_DECREF(str);
8957 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008958 }
Tim Petersced69f82003-09-16 20:30:58 +00008959
Victor Stinner794d5672011-10-10 03:21:36 +02008960 result = any_find_slice(direction,
8961 str, sub, start, end
8962 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00008963
Guido van Rossumd57fd912000-03-10 22:53:23 +00008964 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008965 Py_DECREF(sub);
8966
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967 return result;
8968}
8969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970Py_ssize_t
8971PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8972 Py_ssize_t start, Py_ssize_t end,
8973 int direction)
8974{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008976 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 if (PyUnicode_READY(str) == -1)
8978 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008979 if (start < 0 || end < 0) {
8980 PyErr_SetString(PyExc_IndexError, "string index out of range");
8981 return -2;
8982 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 if (end > PyUnicode_GET_LENGTH(str))
8984 end = PyUnicode_GET_LENGTH(str);
8985 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008986 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
8987 kind, end-start, ch, direction);
8988 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008990 else
8991 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992}
8993
Alexander Belopolsky40018472011-02-26 01:02:56 +00008994static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008995tailmatch(PyObject *self,
8996 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008997 Py_ssize_t start,
8998 Py_ssize_t end,
8999 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 int kind_self;
9002 int kind_sub;
9003 void *data_self;
9004 void *data_sub;
9005 Py_ssize_t offset;
9006 Py_ssize_t i;
9007 Py_ssize_t end_sub;
9008
9009 if (PyUnicode_READY(self) == -1 ||
9010 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009011 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012
9013 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009014 return 1;
9015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9017 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009018 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009019 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021 kind_self = PyUnicode_KIND(self);
9022 data_self = PyUnicode_DATA(self);
9023 kind_sub = PyUnicode_KIND(substring);
9024 data_sub = PyUnicode_DATA(substring);
9025 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9026
9027 if (direction > 0)
9028 offset = end;
9029 else
9030 offset = start;
9031
9032 if (PyUnicode_READ(kind_self, data_self, offset) ==
9033 PyUnicode_READ(kind_sub, data_sub, 0) &&
9034 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9035 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9036 /* If both are of the same kind, memcmp is sufficient */
9037 if (kind_self == kind_sub) {
9038 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009039 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 data_sub,
9041 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009042 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 }
9044 /* otherwise we have to compare each character by first accesing it */
9045 else {
9046 /* We do not need to compare 0 and len(substring)-1 because
9047 the if statement above ensured already that they are equal
9048 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049 for (i = 1; i < end_sub; ++i) {
9050 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9051 PyUnicode_READ(kind_sub, data_sub, i))
9052 return 0;
9053 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009054 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009055 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056 }
9057
9058 return 0;
9059}
9060
Alexander Belopolsky40018472011-02-26 01:02:56 +00009061Py_ssize_t
9062PyUnicode_Tailmatch(PyObject *str,
9063 PyObject *substr,
9064 Py_ssize_t start,
9065 Py_ssize_t end,
9066 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009068 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009069
Guido van Rossumd57fd912000-03-10 22:53:23 +00009070 str = PyUnicode_FromObject(str);
9071 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009072 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073 substr = PyUnicode_FromObject(substr);
9074 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009075 Py_DECREF(str);
9076 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009077 }
Tim Petersced69f82003-09-16 20:30:58 +00009078
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009079 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009080 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081 Py_DECREF(str);
9082 Py_DECREF(substr);
9083 return result;
9084}
9085
Guido van Rossumd57fd912000-03-10 22:53:23 +00009086/* Apply fixfct filter to the Unicode object self and return a
9087 reference to the modified object */
9088
Alexander Belopolsky40018472011-02-26 01:02:56 +00009089static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009090fixup(PyObject *self,
9091 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093 PyObject *u;
9094 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009095 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009096
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009097 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009098 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009099 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009100 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102 /* fix functions return the new maximum character in a string,
9103 if the kind of the resulting unicode object does not change,
9104 everything is fine. Otherwise we need to change the string kind
9105 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009106 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009107
9108 if (maxchar_new == 0) {
9109 /* no changes */;
9110 if (PyUnicode_CheckExact(self)) {
9111 Py_DECREF(u);
9112 Py_INCREF(self);
9113 return self;
9114 }
9115 else
9116 return u;
9117 }
9118
Victor Stinnere6abb482012-05-02 01:15:40 +02009119 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120
Victor Stinnereaab6042011-12-11 22:22:39 +01009121 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009122 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009123
9124 /* In case the maximum character changed, we need to
9125 convert the string to the new category. */
9126 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9127 if (v == NULL) {
9128 Py_DECREF(u);
9129 return NULL;
9130 }
9131 if (maxchar_new > maxchar_old) {
9132 /* If the maxchar increased so that the kind changed, not all
9133 characters are representable anymore and we need to fix the
9134 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009135 _PyUnicode_FastCopyCharacters(v, 0,
9136 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009137 maxchar_old = fixfct(v);
9138 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 }
9140 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009141 _PyUnicode_FastCopyCharacters(v, 0,
9142 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009144 Py_DECREF(u);
9145 assert(_PyUnicode_CheckConsistency(v, 1));
9146 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147}
9148
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009149static PyObject *
9150ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009152 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9153 char *resdata, *data = PyUnicode_DATA(self);
9154 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009155
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009156 res = PyUnicode_New(len, 127);
9157 if (res == NULL)
9158 return NULL;
9159 resdata = PyUnicode_DATA(res);
9160 if (lower)
9161 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009163 _Py_bytes_upper(resdata, data, len);
9164 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165}
9166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009168handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009169{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009170 Py_ssize_t j;
9171 int final_sigma;
9172 Py_UCS4 c;
9173 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009174
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009175 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9176
9177 where ! is a negation and \p{xxx} is a character with property xxx.
9178 */
9179 for (j = i - 1; j >= 0; j--) {
9180 c = PyUnicode_READ(kind, data, j);
9181 if (!_PyUnicode_IsCaseIgnorable(c))
9182 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009183 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009184 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9185 if (final_sigma) {
9186 for (j = i + 1; j < length; j++) {
9187 c = PyUnicode_READ(kind, data, j);
9188 if (!_PyUnicode_IsCaseIgnorable(c))
9189 break;
9190 }
9191 final_sigma = j == length || !_PyUnicode_IsCased(c);
9192 }
9193 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009194}
9195
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009196static int
9197lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9198 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009199{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009200 /* Obscure special case. */
9201 if (c == 0x3A3) {
9202 mapped[0] = handle_capital_sigma(kind, data, length, i);
9203 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009205 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009206}
9207
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009208static Py_ssize_t
9209do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009210{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009211 Py_ssize_t i, k = 0;
9212 int n_res, j;
9213 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009214
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009215 c = PyUnicode_READ(kind, data, 0);
9216 n_res = _PyUnicode_ToUpperFull(c, mapped);
9217 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009218 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009219 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009220 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009221 for (i = 1; i < length; i++) {
9222 c = PyUnicode_READ(kind, data, i);
9223 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9224 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009225 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009226 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009227 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009228 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009229 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009230}
9231
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009232static Py_ssize_t
9233do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9234 Py_ssize_t i, k = 0;
9235
9236 for (i = 0; i < length; i++) {
9237 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9238 int n_res, j;
9239 if (Py_UNICODE_ISUPPER(c)) {
9240 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9241 }
9242 else if (Py_UNICODE_ISLOWER(c)) {
9243 n_res = _PyUnicode_ToUpperFull(c, mapped);
9244 }
9245 else {
9246 n_res = 1;
9247 mapped[0] = c;
9248 }
9249 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009250 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009251 res[k++] = mapped[j];
9252 }
9253 }
9254 return k;
9255}
9256
9257static Py_ssize_t
9258do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9259 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009261 Py_ssize_t i, k = 0;
9262
9263 for (i = 0; i < length; i++) {
9264 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9265 int n_res, j;
9266 if (lower)
9267 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9268 else
9269 n_res = _PyUnicode_ToUpperFull(c, mapped);
9270 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009271 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009272 res[k++] = mapped[j];
9273 }
9274 }
9275 return k;
9276}
9277
9278static Py_ssize_t
9279do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9280{
9281 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9282}
9283
9284static Py_ssize_t
9285do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9286{
9287 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9288}
9289
Benjamin Petersone51757f2012-01-12 21:10:29 -05009290static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009291do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9292{
9293 Py_ssize_t i, k = 0;
9294
9295 for (i = 0; i < length; i++) {
9296 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9297 Py_UCS4 mapped[3];
9298 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9299 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009300 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009301 res[k++] = mapped[j];
9302 }
9303 }
9304 return k;
9305}
9306
9307static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009308do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9309{
9310 Py_ssize_t i, k = 0;
9311 int previous_is_cased;
9312
9313 previous_is_cased = 0;
9314 for (i = 0; i < length; i++) {
9315 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9316 Py_UCS4 mapped[3];
9317 int n_res, j;
9318
9319 if (previous_is_cased)
9320 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9321 else
9322 n_res = _PyUnicode_ToTitleFull(c, mapped);
9323
9324 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009325 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009326 res[k++] = mapped[j];
9327 }
9328
9329 previous_is_cased = _PyUnicode_IsCased(c);
9330 }
9331 return k;
9332}
9333
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009334static PyObject *
9335case_operation(PyObject *self,
9336 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9337{
9338 PyObject *res = NULL;
9339 Py_ssize_t length, newlength = 0;
9340 int kind, outkind;
9341 void *data, *outdata;
9342 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9343
Benjamin Petersoneea48462012-01-16 14:28:50 -05009344 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009345
9346 kind = PyUnicode_KIND(self);
9347 data = PyUnicode_DATA(self);
9348 length = PyUnicode_GET_LENGTH(self);
9349 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9350 if (tmp == NULL)
9351 return PyErr_NoMemory();
9352 newlength = perform(kind, data, length, tmp, &maxchar);
9353 res = PyUnicode_New(newlength, maxchar);
9354 if (res == NULL)
9355 goto leave;
9356 tmpend = tmp + newlength;
9357 outdata = PyUnicode_DATA(res);
9358 outkind = PyUnicode_KIND(res);
9359 switch (outkind) {
9360 case PyUnicode_1BYTE_KIND:
9361 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9362 break;
9363 case PyUnicode_2BYTE_KIND:
9364 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9365 break;
9366 case PyUnicode_4BYTE_KIND:
9367 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9368 break;
9369 default:
9370 assert(0);
9371 break;
9372 }
9373 leave:
9374 PyMem_FREE(tmp);
9375 return res;
9376}
9377
Tim Peters8ce9f162004-08-27 01:49:32 +00009378PyObject *
9379PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009382 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009384 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009385 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9386 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009387 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009389 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009391 int use_memcpy;
9392 unsigned char *res_data = NULL, *sep_data = NULL;
9393 PyObject *last_obj;
9394 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395
Tim Peters05eba1f2004-08-27 21:32:02 +00009396 fseq = PySequence_Fast(seq, "");
9397 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009398 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009399 }
9400
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009401 /* NOTE: the following code can't call back into Python code,
9402 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009403 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009404
Tim Peters05eba1f2004-08-27 21:32:02 +00009405 seqlen = PySequence_Fast_GET_SIZE(fseq);
9406 /* If empty sequence, return u"". */
9407 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009408 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009409 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009410 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009411
Tim Peters05eba1f2004-08-27 21:32:02 +00009412 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009413 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009414 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009415 if (seqlen == 1) {
9416 if (PyUnicode_CheckExact(items[0])) {
9417 res = items[0];
9418 Py_INCREF(res);
9419 Py_DECREF(fseq);
9420 return res;
9421 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009422 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009423 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009424 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009425 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009426 /* Set up sep and seplen */
9427 if (separator == NULL) {
9428 /* fall back to a blank space separator */
9429 sep = PyUnicode_FromOrdinal(' ');
9430 if (!sep)
9431 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009432 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009433 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009434 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009435 else {
9436 if (!PyUnicode_Check(separator)) {
9437 PyErr_Format(PyExc_TypeError,
9438 "separator: expected str instance,"
9439 " %.80s found",
9440 Py_TYPE(separator)->tp_name);
9441 goto onError;
9442 }
9443 if (PyUnicode_READY(separator))
9444 goto onError;
9445 sep = separator;
9446 seplen = PyUnicode_GET_LENGTH(separator);
9447 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9448 /* inc refcount to keep this code path symmetric with the
9449 above case of a blank separator */
9450 Py_INCREF(sep);
9451 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009452 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009453 }
9454
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009455 /* There are at least two things to join, or else we have a subclass
9456 * of str in the sequence.
9457 * Do a pre-pass to figure out the total amount of space we'll
9458 * need (sz), and see whether all argument are strings.
9459 */
9460 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009461#ifdef Py_DEBUG
9462 use_memcpy = 0;
9463#else
9464 use_memcpy = 1;
9465#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009466 for (i = 0; i < seqlen; i++) {
9467 const Py_ssize_t old_sz = sz;
9468 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009469 if (!PyUnicode_Check(item)) {
9470 PyErr_Format(PyExc_TypeError,
9471 "sequence item %zd: expected str instance,"
9472 " %.80s found",
9473 i, Py_TYPE(item)->tp_name);
9474 goto onError;
9475 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 if (PyUnicode_READY(item) == -1)
9477 goto onError;
9478 sz += PyUnicode_GET_LENGTH(item);
9479 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009480 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009481 if (i != 0)
9482 sz += seplen;
9483 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9484 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009485 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009486 goto onError;
9487 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009488 if (use_memcpy && last_obj != NULL) {
9489 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9490 use_memcpy = 0;
9491 }
9492 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009493 }
Tim Petersced69f82003-09-16 20:30:58 +00009494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009496 if (res == NULL)
9497 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009498
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009499 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009500#ifdef Py_DEBUG
9501 use_memcpy = 0;
9502#else
9503 if (use_memcpy) {
9504 res_data = PyUnicode_1BYTE_DATA(res);
9505 kind = PyUnicode_KIND(res);
9506 if (seplen != 0)
9507 sep_data = PyUnicode_1BYTE_DATA(sep);
9508 }
9509#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009510 if (use_memcpy) {
9511 for (i = 0; i < seqlen; ++i) {
9512 Py_ssize_t itemlen;
9513 item = items[i];
9514
9515 /* Copy item, and maybe the separator. */
9516 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009517 Py_MEMCPY(res_data,
9518 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009519 kind * seplen);
9520 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009521 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009522
9523 itemlen = PyUnicode_GET_LENGTH(item);
9524 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009525 Py_MEMCPY(res_data,
9526 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009527 kind * itemlen);
9528 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009529 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009530 }
9531 assert(res_data == PyUnicode_1BYTE_DATA(res)
9532 + kind * PyUnicode_GET_LENGTH(res));
9533 }
9534 else {
9535 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9536 Py_ssize_t itemlen;
9537 item = items[i];
9538
9539 /* Copy item, and maybe the separator. */
9540 if (i && seplen != 0) {
9541 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9542 res_offset += seplen;
9543 }
9544
9545 itemlen = PyUnicode_GET_LENGTH(item);
9546 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009547 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009548 res_offset += itemlen;
9549 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009550 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009551 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009552 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009553
Tim Peters05eba1f2004-08-27 21:32:02 +00009554 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009556 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009560 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009562 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563 return NULL;
9564}
9565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566#define FILL(kind, data, value, start, length) \
9567 do { \
9568 Py_ssize_t i_ = 0; \
9569 assert(kind != PyUnicode_WCHAR_KIND); \
9570 switch ((kind)) { \
9571 case PyUnicode_1BYTE_KIND: { \
9572 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009573 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 break; \
9575 } \
9576 case PyUnicode_2BYTE_KIND: { \
9577 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9578 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9579 break; \
9580 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009581 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9583 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9584 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009585 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009586 } \
9587 } \
9588 } while (0)
9589
Victor Stinnerd3f08822012-05-29 12:57:52 +02009590void
9591_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9592 Py_UCS4 fill_char)
9593{
9594 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9595 const void *data = PyUnicode_DATA(unicode);
9596 assert(PyUnicode_IS_READY(unicode));
9597 assert(unicode_modifiable(unicode));
9598 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9599 assert(start >= 0);
9600 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9601 FILL(kind, data, fill_char, start, length);
9602}
9603
Victor Stinner3fe55312012-01-04 00:33:50 +01009604Py_ssize_t
9605PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9606 Py_UCS4 fill_char)
9607{
9608 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009609
9610 if (!PyUnicode_Check(unicode)) {
9611 PyErr_BadInternalCall();
9612 return -1;
9613 }
9614 if (PyUnicode_READY(unicode) == -1)
9615 return -1;
9616 if (unicode_check_modifiable(unicode))
9617 return -1;
9618
Victor Stinnerd3f08822012-05-29 12:57:52 +02009619 if (start < 0) {
9620 PyErr_SetString(PyExc_IndexError, "string index out of range");
9621 return -1;
9622 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009623 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9624 PyErr_SetString(PyExc_ValueError,
9625 "fill character is bigger than "
9626 "the string maximum character");
9627 return -1;
9628 }
9629
9630 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9631 length = Py_MIN(maxlen, length);
9632 if (length <= 0)
9633 return 0;
9634
Victor Stinnerd3f08822012-05-29 12:57:52 +02009635 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009636 return length;
9637}
9638
Victor Stinner9310abb2011-10-05 00:59:23 +02009639static PyObject *
9640pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009641 Py_ssize_t left,
9642 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009643 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009644{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 PyObject *u;
9646 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009647 int kind;
9648 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009649
9650 if (left < 0)
9651 left = 0;
9652 if (right < 0)
9653 right = 0;
9654
Victor Stinnerc4b49542011-12-11 22:44:26 +01009655 if (left == 0 && right == 0)
9656 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9659 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009660 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9661 return NULL;
9662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009664 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009666 if (!u)
9667 return NULL;
9668
9669 kind = PyUnicode_KIND(u);
9670 data = PyUnicode_DATA(u);
9671 if (left)
9672 FILL(kind, data, fill, 0, left);
9673 if (right)
9674 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009675 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009676 assert(_PyUnicode_CheckConsistency(u, 1));
9677 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678}
9679
Alexander Belopolsky40018472011-02-26 01:02:56 +00009680PyObject *
9681PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009683 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684
9685 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009686 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009687 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009688 if (PyUnicode_READY(string) == -1) {
9689 Py_DECREF(string);
9690 return NULL;
9691 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009692
Benjamin Petersonead6b532011-12-20 17:23:42 -06009693 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009694 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009695 if (PyUnicode_IS_ASCII(string))
9696 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009697 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009698 PyUnicode_GET_LENGTH(string), keepends);
9699 else
9700 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009701 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009702 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009703 break;
9704 case PyUnicode_2BYTE_KIND:
9705 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009706 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 PyUnicode_GET_LENGTH(string), keepends);
9708 break;
9709 case PyUnicode_4BYTE_KIND:
9710 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009711 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009712 PyUnicode_GET_LENGTH(string), keepends);
9713 break;
9714 default:
9715 assert(0);
9716 list = 0;
9717 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718 Py_DECREF(string);
9719 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009720}
9721
Alexander Belopolsky40018472011-02-26 01:02:56 +00009722static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009723split(PyObject *self,
9724 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009725 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009726{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009727 int kind1, kind2, kind;
9728 void *buf1, *buf2;
9729 Py_ssize_t len1, len2;
9730 PyObject* out;
9731
Guido van Rossumd57fd912000-03-10 22:53:23 +00009732 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009733 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 if (PyUnicode_READY(self) == -1)
9736 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009738 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009739 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009740 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009741 if (PyUnicode_IS_ASCII(self))
9742 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009743 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009744 PyUnicode_GET_LENGTH(self), maxcount
9745 );
9746 else
9747 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009748 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009749 PyUnicode_GET_LENGTH(self), maxcount
9750 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 case PyUnicode_2BYTE_KIND:
9752 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009753 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009754 PyUnicode_GET_LENGTH(self), maxcount
9755 );
9756 case PyUnicode_4BYTE_KIND:
9757 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009758 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 PyUnicode_GET_LENGTH(self), maxcount
9760 );
9761 default:
9762 assert(0);
9763 return NULL;
9764 }
9765
9766 if (PyUnicode_READY(substring) == -1)
9767 return NULL;
9768
9769 kind1 = PyUnicode_KIND(self);
9770 kind2 = PyUnicode_KIND(substring);
9771 kind = kind1 > kind2 ? kind1 : kind2;
9772 buf1 = PyUnicode_DATA(self);
9773 buf2 = PyUnicode_DATA(substring);
9774 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009775 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009776 if (!buf1)
9777 return NULL;
9778 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009779 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 if (!buf2) {
9781 if (kind1 != kind) PyMem_Free(buf1);
9782 return NULL;
9783 }
9784 len1 = PyUnicode_GET_LENGTH(self);
9785 len2 = PyUnicode_GET_LENGTH(substring);
9786
Benjamin Petersonead6b532011-12-20 17:23:42 -06009787 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009788 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009789 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9790 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009791 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009792 else
9793 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009794 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009795 break;
9796 case PyUnicode_2BYTE_KIND:
9797 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009798 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009799 break;
9800 case PyUnicode_4BYTE_KIND:
9801 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009802 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 break;
9804 default:
9805 out = NULL;
9806 }
9807 if (kind1 != kind)
9808 PyMem_Free(buf1);
9809 if (kind2 != kind)
9810 PyMem_Free(buf2);
9811 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009812}
9813
Alexander Belopolsky40018472011-02-26 01:02:56 +00009814static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009815rsplit(PyObject *self,
9816 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009817 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009818{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009819 int kind1, kind2, kind;
9820 void *buf1, *buf2;
9821 Py_ssize_t len1, len2;
9822 PyObject* out;
9823
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009824 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009825 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 if (PyUnicode_READY(self) == -1)
9828 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009830 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009831 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009833 if (PyUnicode_IS_ASCII(self))
9834 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009835 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009836 PyUnicode_GET_LENGTH(self), maxcount
9837 );
9838 else
9839 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009840 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009841 PyUnicode_GET_LENGTH(self), maxcount
9842 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 case PyUnicode_2BYTE_KIND:
9844 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009845 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009846 PyUnicode_GET_LENGTH(self), maxcount
9847 );
9848 case PyUnicode_4BYTE_KIND:
9849 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009850 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 PyUnicode_GET_LENGTH(self), maxcount
9852 );
9853 default:
9854 assert(0);
9855 return NULL;
9856 }
9857
9858 if (PyUnicode_READY(substring) == -1)
9859 return NULL;
9860
9861 kind1 = PyUnicode_KIND(self);
9862 kind2 = PyUnicode_KIND(substring);
9863 kind = kind1 > kind2 ? kind1 : kind2;
9864 buf1 = PyUnicode_DATA(self);
9865 buf2 = PyUnicode_DATA(substring);
9866 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009867 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 if (!buf1)
9869 return NULL;
9870 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009871 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 if (!buf2) {
9873 if (kind1 != kind) PyMem_Free(buf1);
9874 return NULL;
9875 }
9876 len1 = PyUnicode_GET_LENGTH(self);
9877 len2 = PyUnicode_GET_LENGTH(substring);
9878
Benjamin Petersonead6b532011-12-20 17:23:42 -06009879 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009880 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009881 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9882 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009883 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009884 else
9885 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009886 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009887 break;
9888 case PyUnicode_2BYTE_KIND:
9889 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009890 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 break;
9892 case PyUnicode_4BYTE_KIND:
9893 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009894 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 break;
9896 default:
9897 out = NULL;
9898 }
9899 if (kind1 != kind)
9900 PyMem_Free(buf1);
9901 if (kind2 != kind)
9902 PyMem_Free(buf2);
9903 return out;
9904}
9905
9906static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009907anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9908 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009910 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009911 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009912 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9913 return asciilib_find(buf1, len1, buf2, len2, offset);
9914 else
9915 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 case PyUnicode_2BYTE_KIND:
9917 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9918 case PyUnicode_4BYTE_KIND:
9919 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9920 }
9921 assert(0);
9922 return -1;
9923}
9924
9925static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009926anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9927 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009929 switch (kind) {
9930 case PyUnicode_1BYTE_KIND:
9931 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9932 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9933 else
9934 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9935 case PyUnicode_2BYTE_KIND:
9936 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9937 case PyUnicode_4BYTE_KIND:
9938 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9939 }
9940 assert(0);
9941 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009942}
9943
Serhiy Storchakae2cef882013-04-13 22:45:04 +03009944static void
9945replace_1char_inplace(PyObject *u, Py_ssize_t pos,
9946 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
9947{
9948 int kind = PyUnicode_KIND(u);
9949 void *data = PyUnicode_DATA(u);
9950 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
9951 if (kind == PyUnicode_1BYTE_KIND) {
9952 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
9953 (Py_UCS1 *)data + len,
9954 u1, u2, maxcount);
9955 }
9956 else if (kind == PyUnicode_2BYTE_KIND) {
9957 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
9958 (Py_UCS2 *)data + len,
9959 u1, u2, maxcount);
9960 }
9961 else {
9962 assert(kind == PyUnicode_4BYTE_KIND);
9963 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
9964 (Py_UCS4 *)data + len,
9965 u1, u2, maxcount);
9966 }
9967}
9968
Alexander Belopolsky40018472011-02-26 01:02:56 +00009969static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970replace(PyObject *self, PyObject *str1,
9971 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009972{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 PyObject *u;
9974 char *sbuf = PyUnicode_DATA(self);
9975 char *buf1 = PyUnicode_DATA(str1);
9976 char *buf2 = PyUnicode_DATA(str2);
9977 int srelease = 0, release1 = 0, release2 = 0;
9978 int skind = PyUnicode_KIND(self);
9979 int kind1 = PyUnicode_KIND(str1);
9980 int kind2 = PyUnicode_KIND(str2);
9981 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9982 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9983 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009984 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +03009985 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986
9987 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009988 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009990 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991
Victor Stinner59de0ee2011-10-07 10:01:28 +02009992 if (str1 == str2)
9993 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009994
Victor Stinner49a0a212011-10-12 23:46:10 +02009995 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +03009996 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
9997 if (maxchar < maxchar_str1)
9998 /* substring too wide to be present */
9999 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010000 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10001 /* Replacing str1 with str2 may cause a maxchar reduction in the
10002 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010003 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Victor Stinnere6abb482012-05-02 01:15:40 +020010004 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010007 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010009 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010011 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010012 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010013 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010014
Victor Stinner69ed0f42013-04-09 21:48:24 +020010015 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010016 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010017 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010018 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010019 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010021 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010023
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010024 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10025 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010026 }
10027 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 int rkind = skind;
10029 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010030 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010031
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 if (kind1 < rkind) {
10033 /* widen substring */
10034 buf1 = _PyUnicode_AsKind(str1, rkind);
10035 if (!buf1) goto error;
10036 release1 = 1;
10037 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010038 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010039 if (i < 0)
10040 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 if (rkind > kind2) {
10042 /* widen replacement */
10043 buf2 = _PyUnicode_AsKind(str2, rkind);
10044 if (!buf2) goto error;
10045 release2 = 1;
10046 }
10047 else if (rkind < kind2) {
10048 /* widen self and buf1 */
10049 rkind = kind2;
10050 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010051 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 sbuf = _PyUnicode_AsKind(self, rkind);
10053 if (!sbuf) goto error;
10054 srelease = 1;
10055 buf1 = _PyUnicode_AsKind(str1, rkind);
10056 if (!buf1) goto error;
10057 release1 = 1;
10058 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010059 u = PyUnicode_New(slen, maxchar);
10060 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010062 assert(PyUnicode_KIND(u) == rkind);
10063 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010064
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010065 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010066 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010067 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010069 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010071
10072 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010073 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010074 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010075 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010076 if (i == -1)
10077 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010078 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010080 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010081 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010082 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010083 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010084 }
10085 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010087 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 int rkind = skind;
10089 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010092 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 buf1 = _PyUnicode_AsKind(str1, rkind);
10094 if (!buf1) goto error;
10095 release1 = 1;
10096 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010097 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010098 if (n == 0)
10099 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010101 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 buf2 = _PyUnicode_AsKind(str2, rkind);
10103 if (!buf2) goto error;
10104 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010107 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 rkind = kind2;
10109 sbuf = _PyUnicode_AsKind(self, rkind);
10110 if (!sbuf) goto error;
10111 srelease = 1;
10112 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010113 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 buf1 = _PyUnicode_AsKind(str1, rkind);
10115 if (!buf1) goto error;
10116 release1 = 1;
10117 }
10118 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10119 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010120 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 PyErr_SetString(PyExc_OverflowError,
10122 "replace string is too long");
10123 goto error;
10124 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010125 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010126 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010127 _Py_INCREF_UNICODE_EMPTY();
10128 if (!unicode_empty)
10129 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010130 u = unicode_empty;
10131 goto done;
10132 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010133 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 PyErr_SetString(PyExc_OverflowError,
10135 "replace string is too long");
10136 goto error;
10137 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010138 u = PyUnicode_New(new_size, maxchar);
10139 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010141 assert(PyUnicode_KIND(u) == rkind);
10142 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 ires = i = 0;
10144 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010145 while (n-- > 0) {
10146 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010148 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010150 if (j == -1)
10151 break;
10152 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010153 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010154 memcpy(res + rkind * ires,
10155 sbuf + rkind * i,
10156 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010158 }
10159 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010161 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010163 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010167 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010169 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010170 memcpy(res + rkind * ires,
10171 sbuf + rkind * i,
10172 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010173 }
10174 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010175 /* interleave */
10176 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010177 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010179 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010181 if (--n <= 0)
10182 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010183 memcpy(res + rkind * ires,
10184 sbuf + rkind * i,
10185 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 ires++;
10187 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010188 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010189 memcpy(res + rkind * ires,
10190 sbuf + rkind * i,
10191 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010192 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010193 }
10194
10195 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010196 unicode_adjust_maxchar(&u);
10197 if (u == NULL)
10198 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010200
10201 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 if (srelease)
10203 PyMem_FREE(sbuf);
10204 if (release1)
10205 PyMem_FREE(buf1);
10206 if (release2)
10207 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010208 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010210
Benjamin Peterson29060642009-01-31 22:14:21 +000010211 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010212 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 if (srelease)
10214 PyMem_FREE(sbuf);
10215 if (release1)
10216 PyMem_FREE(buf1);
10217 if (release2)
10218 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010219 return unicode_result_unchanged(self);
10220
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 error:
10222 if (srelease && sbuf)
10223 PyMem_FREE(sbuf);
10224 if (release1 && buf1)
10225 PyMem_FREE(buf1);
10226 if (release2 && buf2)
10227 PyMem_FREE(buf2);
10228 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229}
10230
10231/* --- Unicode Object Methods --------------------------------------------- */
10232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010233PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010234 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235\n\
10236Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010237characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010238
10239static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010240unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010241{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010242 if (PyUnicode_READY(self) == -1)
10243 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010244 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010245}
10246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010247PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010248 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010249\n\
10250Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010251have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010252
10253static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010254unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010255{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010256 if (PyUnicode_READY(self) == -1)
10257 return NULL;
10258 if (PyUnicode_GET_LENGTH(self) == 0)
10259 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010260 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010261}
10262
Benjamin Petersond5890c82012-01-14 13:23:30 -050010263PyDoc_STRVAR(casefold__doc__,
10264 "S.casefold() -> str\n\
10265\n\
10266Return a version of S suitable for caseless comparisons.");
10267
10268static PyObject *
10269unicode_casefold(PyObject *self)
10270{
10271 if (PyUnicode_READY(self) == -1)
10272 return NULL;
10273 if (PyUnicode_IS_ASCII(self))
10274 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010275 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010276}
10277
10278
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010279/* Argument converter. Coerces to a single unicode character */
10280
10281static int
10282convert_uc(PyObject *obj, void *addr)
10283{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010285 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010286
Benjamin Peterson14339b62009-01-31 16:36:08 +000010287 uniobj = PyUnicode_FromObject(obj);
10288 if (uniobj == NULL) {
10289 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010290 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010291 return 0;
10292 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010294 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010295 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010296 Py_DECREF(uniobj);
10297 return 0;
10298 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010300 Py_DECREF(uniobj);
10301 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010302}
10303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010304PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010305 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010307Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010308done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309
10310static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010311unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010312{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010313 Py_ssize_t marg, left;
10314 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 Py_UCS4 fillchar = ' ';
10316
Victor Stinnere9a29352011-10-01 02:14:59 +020010317 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010319
Benjamin Petersonbac79492012-01-14 13:34:47 -050010320 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321 return NULL;
10322
Victor Stinnerc4b49542011-12-11 22:44:26 +010010323 if (PyUnicode_GET_LENGTH(self) >= width)
10324 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325
Victor Stinnerc4b49542011-12-11 22:44:26 +010010326 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327 left = marg / 2 + (marg & width & 1);
10328
Victor Stinner9310abb2011-10-05 00:59:23 +020010329 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330}
10331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332/* This function assumes that str1 and str2 are readied by the caller. */
10333
Marc-André Lemburge5034372000-08-08 08:04:29 +000010334static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010335unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010336{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010337#define COMPARE(TYPE1, TYPE2) \
10338 do { \
10339 TYPE1* p1 = (TYPE1 *)data1; \
10340 TYPE2* p2 = (TYPE2 *)data2; \
10341 TYPE1* end = p1 + len; \
10342 Py_UCS4 c1, c2; \
10343 for (; p1 != end; p1++, p2++) { \
10344 c1 = *p1; \
10345 c2 = *p2; \
10346 if (c1 != c2) \
10347 return (c1 < c2) ? -1 : 1; \
10348 } \
10349 } \
10350 while (0)
10351
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 int kind1, kind2;
10353 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010354 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010355
Victor Stinner90db9c42012-10-04 21:53:50 +020010356 /* a string is equal to itself */
10357 if (str1 == str2)
10358 return 0;
10359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 kind1 = PyUnicode_KIND(str1);
10361 kind2 = PyUnicode_KIND(str2);
10362 data1 = PyUnicode_DATA(str1);
10363 data2 = PyUnicode_DATA(str2);
10364 len1 = PyUnicode_GET_LENGTH(str1);
10365 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010366 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010367
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010368 switch(kind1) {
10369 case PyUnicode_1BYTE_KIND:
10370 {
10371 switch(kind2) {
10372 case PyUnicode_1BYTE_KIND:
10373 {
10374 int cmp = memcmp(data1, data2, len);
10375 /* normalize result of memcmp() into the range [-1; 1] */
10376 if (cmp < 0)
10377 return -1;
10378 if (cmp > 0)
10379 return 1;
10380 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010381 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010382 case PyUnicode_2BYTE_KIND:
10383 COMPARE(Py_UCS1, Py_UCS2);
10384 break;
10385 case PyUnicode_4BYTE_KIND:
10386 COMPARE(Py_UCS1, Py_UCS4);
10387 break;
10388 default:
10389 assert(0);
10390 }
10391 break;
10392 }
10393 case PyUnicode_2BYTE_KIND:
10394 {
10395 switch(kind2) {
10396 case PyUnicode_1BYTE_KIND:
10397 COMPARE(Py_UCS2, Py_UCS1);
10398 break;
10399 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010400 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010401 COMPARE(Py_UCS2, Py_UCS2);
10402 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010403 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010404 case PyUnicode_4BYTE_KIND:
10405 COMPARE(Py_UCS2, Py_UCS4);
10406 break;
10407 default:
10408 assert(0);
10409 }
10410 break;
10411 }
10412 case PyUnicode_4BYTE_KIND:
10413 {
10414 switch(kind2) {
10415 case PyUnicode_1BYTE_KIND:
10416 COMPARE(Py_UCS4, Py_UCS1);
10417 break;
10418 case PyUnicode_2BYTE_KIND:
10419 COMPARE(Py_UCS4, Py_UCS2);
10420 break;
10421 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010422 {
10423#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10424 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10425 /* normalize result of wmemcmp() into the range [-1; 1] */
10426 if (cmp < 0)
10427 return -1;
10428 if (cmp > 0)
10429 return 1;
10430#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010431 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010432#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010433 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010434 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010435 default:
10436 assert(0);
10437 }
10438 break;
10439 }
10440 default:
10441 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010442 }
10443
Victor Stinner770e19e2012-10-04 22:59:45 +020010444 if (len1 == len2)
10445 return 0;
10446 if (len1 < len2)
10447 return -1;
10448 else
10449 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010450
10451#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010452}
10453
Victor Stinnere5567ad2012-10-23 02:48:49 +020010454static int
10455unicode_compare_eq(PyObject *str1, PyObject *str2)
10456{
10457 int kind;
10458 void *data1, *data2;
10459 Py_ssize_t len;
10460 int cmp;
10461
10462 /* a string is equal to itself */
10463 if (str1 == str2)
10464 return 1;
10465
10466 len = PyUnicode_GET_LENGTH(str1);
10467 if (PyUnicode_GET_LENGTH(str2) != len)
10468 return 0;
10469 kind = PyUnicode_KIND(str1);
10470 if (PyUnicode_KIND(str2) != kind)
10471 return 0;
10472 data1 = PyUnicode_DATA(str1);
10473 data2 = PyUnicode_DATA(str2);
10474
10475 cmp = memcmp(data1, data2, len * kind);
10476 return (cmp == 0);
10477}
10478
10479
Alexander Belopolsky40018472011-02-26 01:02:56 +000010480int
10481PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10484 if (PyUnicode_READY(left) == -1 ||
10485 PyUnicode_READY(right) == -1)
10486 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010487 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010489 PyErr_Format(PyExc_TypeError,
10490 "Can't compare %.100s and %.100s",
10491 left->ob_type->tp_name,
10492 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010493 return -1;
10494}
10495
Martin v. Löwis5b222132007-06-10 09:51:05 +000010496int
10497PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10498{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 Py_ssize_t i;
10500 int kind;
10501 void *data;
10502 Py_UCS4 chr;
10503
Victor Stinner910337b2011-10-03 03:20:16 +020010504 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 if (PyUnicode_READY(uni) == -1)
10506 return -1;
10507 kind = PyUnicode_KIND(uni);
10508 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010509 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10511 if (chr != str[i])
10512 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010513 /* This check keeps Python strings that end in '\0' from comparing equal
10514 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010516 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010517 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010518 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010519 return 0;
10520}
10521
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010522
Benjamin Peterson29060642009-01-31 22:14:21 +000010523#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010524 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010525
Alexander Belopolsky40018472011-02-26 01:02:56 +000010526PyObject *
10527PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010528{
10529 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010530 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010531
Victor Stinnere5567ad2012-10-23 02:48:49 +020010532 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10533 Py_RETURN_NOTIMPLEMENTED;
10534
10535 if (PyUnicode_READY(left) == -1 ||
10536 PyUnicode_READY(right) == -1)
10537 return NULL;
10538
10539 if (op == Py_EQ || op == Py_NE) {
10540 result = unicode_compare_eq(left, right);
10541 if (op == Py_EQ)
10542 v = TEST_COND(result);
10543 else
10544 v = TEST_COND(!result);
10545 }
10546 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010547 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010548
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010549 /* Convert the return value to a Boolean */
10550 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010551 case Py_LE:
10552 v = TEST_COND(result <= 0);
10553 break;
10554 case Py_GE:
10555 v = TEST_COND(result >= 0);
10556 break;
10557 case Py_LT:
10558 v = TEST_COND(result == -1);
10559 break;
10560 case Py_GT:
10561 v = TEST_COND(result == 1);
10562 break;
10563 default:
10564 PyErr_BadArgument();
10565 return NULL;
10566 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010567 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010568 Py_INCREF(v);
10569 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010570}
10571
Alexander Belopolsky40018472011-02-26 01:02:56 +000010572int
10573PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010574{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010575 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010576 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 void *buf1, *buf2;
10578 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010579 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010580
10581 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010582 sub = PyUnicode_FromObject(element);
10583 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010584 PyErr_Format(PyExc_TypeError,
10585 "'in <string>' requires string as left operand, not %s",
10586 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010588 }
10589
Thomas Wouters477c8d52006-05-27 19:21:47 +000010590 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010591 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010592 Py_DECREF(sub);
10593 return -1;
10594 }
10595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 kind1 = PyUnicode_KIND(str);
10597 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 buf1 = PyUnicode_DATA(str);
10599 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010600 if (kind2 != kind1) {
10601 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010602 Py_DECREF(sub);
10603 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010604 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010605 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010606 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010607 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 if (!buf2) {
10609 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010610 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 return -1;
10612 }
10613 len1 = PyUnicode_GET_LENGTH(str);
10614 len2 = PyUnicode_GET_LENGTH(sub);
10615
Victor Stinner77282cb2013-04-14 19:22:47 +020010616 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 case PyUnicode_1BYTE_KIND:
10618 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10619 break;
10620 case PyUnicode_2BYTE_KIND:
10621 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10622 break;
10623 case PyUnicode_4BYTE_KIND:
10624 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10625 break;
10626 default:
10627 result = -1;
10628 assert(0);
10629 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010630
10631 Py_DECREF(str);
10632 Py_DECREF(sub);
10633
Victor Stinner77282cb2013-04-14 19:22:47 +020010634 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 PyMem_Free(buf2);
10636
Guido van Rossum403d68b2000-03-13 15:55:09 +000010637 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010638}
10639
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640/* Concat to string or Unicode object giving a new Unicode object. */
10641
Alexander Belopolsky40018472011-02-26 01:02:56 +000010642PyObject *
10643PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010646 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010647 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648
10649 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010652 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010655 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656
10657 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010658 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010659 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010662 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010663 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010665 }
10666
Victor Stinner488fa492011-12-12 00:01:39 +010010667 u_len = PyUnicode_GET_LENGTH(u);
10668 v_len = PyUnicode_GET_LENGTH(v);
10669 if (u_len > PY_SSIZE_T_MAX - v_len) {
10670 PyErr_SetString(PyExc_OverflowError,
10671 "strings are too large to concat");
10672 goto onError;
10673 }
10674 new_len = u_len + v_len;
10675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010677 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010678 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010681 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010682 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010683 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010684 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10685 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010686 Py_DECREF(u);
10687 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010688 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690
Benjamin Peterson29060642009-01-31 22:14:21 +000010691 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010692 Py_XDECREF(u);
10693 Py_XDECREF(v);
10694 return NULL;
10695}
10696
Walter Dörwald1ab83302007-05-18 17:15:44 +000010697void
Victor Stinner23e56682011-10-03 03:54:37 +020010698PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010699{
Victor Stinner23e56682011-10-03 03:54:37 +020010700 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010701 Py_UCS4 maxchar, maxchar2;
10702 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010703
10704 if (p_left == NULL) {
10705 if (!PyErr_Occurred())
10706 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010707 return;
10708 }
Victor Stinner23e56682011-10-03 03:54:37 +020010709 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020010710 if (right == NULL || left == NULL
10711 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010712 if (!PyErr_Occurred())
10713 PyErr_BadInternalCall();
10714 goto error;
10715 }
10716
Benjamin Petersonbac79492012-01-14 13:34:47 -050010717 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010718 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010719 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010720 goto error;
10721
Victor Stinner488fa492011-12-12 00:01:39 +010010722 /* Shortcuts */
10723 if (left == unicode_empty) {
10724 Py_DECREF(left);
10725 Py_INCREF(right);
10726 *p_left = right;
10727 return;
10728 }
10729 if (right == unicode_empty)
10730 return;
10731
10732 left_len = PyUnicode_GET_LENGTH(left);
10733 right_len = PyUnicode_GET_LENGTH(right);
10734 if (left_len > PY_SSIZE_T_MAX - right_len) {
10735 PyErr_SetString(PyExc_OverflowError,
10736 "strings are too large to concat");
10737 goto error;
10738 }
10739 new_len = left_len + right_len;
10740
10741 if (unicode_modifiable(left)
10742 && PyUnicode_CheckExact(right)
10743 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010744 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10745 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010746 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010747 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010748 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10749 {
10750 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010751 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010010752 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020010753
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010754 /* copy 'right' into the newly allocated area of 'left' */
10755 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010756 }
Victor Stinner488fa492011-12-12 00:01:39 +010010757 else {
10758 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10759 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010760 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010761
Victor Stinner488fa492011-12-12 00:01:39 +010010762 /* Concat the two Unicode strings */
10763 res = PyUnicode_New(new_len, maxchar);
10764 if (res == NULL)
10765 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010766 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10767 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010768 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020010769 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010010770 }
10771 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010772 return;
10773
10774error:
Victor Stinner488fa492011-12-12 00:01:39 +010010775 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010776}
10777
10778void
10779PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10780{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010781 PyUnicode_Append(pleft, right);
10782 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010783}
10784
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010785PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010787\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010788Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010789string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010790interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010791
10792static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010793unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010795 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010796 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010797 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 int kind1, kind2, kind;
10800 void *buf1, *buf2;
10801 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802
Jesus Ceaac451502011-04-20 17:09:23 +020010803 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10804 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010805 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 kind1 = PyUnicode_KIND(self);
10808 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010809 if (kind2 > kind1)
10810 return PyLong_FromLong(0);
10811 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 buf1 = PyUnicode_DATA(self);
10813 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010814 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010815 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 if (!buf2) {
10817 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 return NULL;
10819 }
10820 len1 = PyUnicode_GET_LENGTH(self);
10821 len2 = PyUnicode_GET_LENGTH(substring);
10822
10823 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010824 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010825 case PyUnicode_1BYTE_KIND:
10826 iresult = ucs1lib_count(
10827 ((Py_UCS1*)buf1) + start, end - start,
10828 buf2, len2, PY_SSIZE_T_MAX
10829 );
10830 break;
10831 case PyUnicode_2BYTE_KIND:
10832 iresult = ucs2lib_count(
10833 ((Py_UCS2*)buf1) + start, end - start,
10834 buf2, len2, PY_SSIZE_T_MAX
10835 );
10836 break;
10837 case PyUnicode_4BYTE_KIND:
10838 iresult = ucs4lib_count(
10839 ((Py_UCS4*)buf1) + start, end - start,
10840 buf2, len2, PY_SSIZE_T_MAX
10841 );
10842 break;
10843 default:
10844 assert(0); iresult = 0;
10845 }
10846
10847 result = PyLong_FromSsize_t(iresult);
10848
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010849 if (kind2 != kind)
10850 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851
10852 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010853
Guido van Rossumd57fd912000-03-10 22:53:23 +000010854 return result;
10855}
10856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010857PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010858 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010860Encode S using the codec registered for encoding. Default encoding\n\
10861is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010862handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010863a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10864'xmlcharrefreplace' as well as any other name registered with\n\
10865codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010866
10867static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010868unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010870 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871 char *encoding = NULL;
10872 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010873
Benjamin Peterson308d6372009-09-18 21:42:35 +000010874 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10875 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010876 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010877 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010878}
10879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010880PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010881 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882\n\
10883Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010884If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010885
10886static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010887unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010889 Py_ssize_t i, j, line_pos, src_len, incr;
10890 Py_UCS4 ch;
10891 PyObject *u;
10892 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010894 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010895 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896
10897 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010898 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899
Antoine Pitrou22425222011-10-04 19:10:51 +020010900 if (PyUnicode_READY(self) == -1)
10901 return NULL;
10902
Thomas Wouters7e474022000-07-16 12:04:32 +000010903 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010904 src_len = PyUnicode_GET_LENGTH(self);
10905 i = j = line_pos = 0;
10906 kind = PyUnicode_KIND(self);
10907 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010908 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010909 for (; i < src_len; i++) {
10910 ch = PyUnicode_READ(kind, src_data, i);
10911 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010912 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010913 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010914 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010915 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 goto overflow;
10917 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010919 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010920 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010922 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010923 goto overflow;
10924 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010926 if (ch == '\n' || ch == '\r')
10927 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010929 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010930 if (!found)
10931 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010932
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935 if (!u)
10936 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010937 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938
Antoine Pitroue71d5742011-10-04 15:55:09 +020010939 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940
Antoine Pitroue71d5742011-10-04 15:55:09 +020010941 for (; i < src_len; i++) {
10942 ch = PyUnicode_READ(kind, src_data, i);
10943 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010944 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 incr = tabsize - (line_pos % tabsize);
10946 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010947 FILL(kind, dest_data, ' ', j, incr);
10948 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010949 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010950 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010951 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010952 line_pos++;
10953 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010954 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010955 if (ch == '\n' || ch == '\r')
10956 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010958 }
10959 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010960 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010961
Antoine Pitroue71d5742011-10-04 15:55:09 +020010962 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010963 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10964 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965}
10966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010967PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010968 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969\n\
10970Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010971such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972arguments start and end are interpreted as in slice notation.\n\
10973\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010974Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975
10976static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010977unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010979 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010980 Py_ssize_t start;
10981 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010982 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983
Jesus Ceaac451502011-04-20 17:09:23 +020010984 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10985 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010988 if (PyUnicode_READY(self) == -1)
10989 return NULL;
10990 if (PyUnicode_READY(substring) == -1)
10991 return NULL;
10992
Victor Stinner7931d9a2011-11-04 00:22:48 +010010993 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994
10995 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 if (result == -2)
10998 return NULL;
10999
Christian Heimes217cfd12007-12-02 14:31:20 +000011000 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001}
11002
11003static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011004unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011006 void *data;
11007 enum PyUnicode_Kind kind;
11008 Py_UCS4 ch;
11009 PyObject *res;
11010
11011 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11012 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011014 }
11015 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11016 PyErr_SetString(PyExc_IndexError, "string index out of range");
11017 return NULL;
11018 }
11019 kind = PyUnicode_KIND(self);
11020 data = PyUnicode_DATA(self);
11021 ch = PyUnicode_READ(kind, data, index);
11022 if (ch < 256)
11023 return get_latin1_char(ch);
11024
11025 res = PyUnicode_New(1, ch);
11026 if (res == NULL)
11027 return NULL;
11028 kind = PyUnicode_KIND(res);
11029 data = PyUnicode_DATA(res);
11030 PyUnicode_WRITE(kind, data, 0, ch);
11031 assert(_PyUnicode_CheckConsistency(res, 1));
11032 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033}
11034
Guido van Rossumc2504932007-09-18 19:42:40 +000011035/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011036 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011037static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011038unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039{
Guido van Rossumc2504932007-09-18 19:42:40 +000011040 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011041 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011042
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011043#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011044 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011045#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046 if (_PyUnicode_HASH(self) != -1)
11047 return _PyUnicode_HASH(self);
11048 if (PyUnicode_READY(self) == -1)
11049 return -1;
11050 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011051 /*
11052 We make the hash of the empty string be 0, rather than using
11053 (prefix ^ suffix), since this slightly obfuscates the hash secret
11054 */
11055 if (len == 0) {
11056 _PyUnicode_HASH(self) = 0;
11057 return 0;
11058 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059
11060 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011061#define HASH(P) \
11062 x ^= (Py_uhash_t) *P << 7; \
11063 while (--len >= 0) \
11064 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065
Georg Brandl2fb477c2012-02-21 00:33:36 +010011066 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011067 switch (PyUnicode_KIND(self)) {
11068 case PyUnicode_1BYTE_KIND: {
11069 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11070 HASH(c);
11071 break;
11072 }
11073 case PyUnicode_2BYTE_KIND: {
11074 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11075 HASH(s);
11076 break;
11077 }
11078 default: {
11079 Py_UCS4 *l;
11080 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11081 "Impossible switch case in unicode_hash");
11082 l = PyUnicode_4BYTE_DATA(self);
11083 HASH(l);
11084 break;
11085 }
11086 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011087 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11088 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089
Guido van Rossumc2504932007-09-18 19:42:40 +000011090 if (x == -1)
11091 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011092 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011093 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011095#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011097PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011098 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011100Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101
11102static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011105 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011106 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011107 Py_ssize_t start;
11108 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
Jesus Ceaac451502011-04-20 17:09:23 +020011110 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11111 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 if (PyUnicode_READY(self) == -1)
11115 return NULL;
11116 if (PyUnicode_READY(substring) == -1)
11117 return NULL;
11118
Victor Stinner7931d9a2011-11-04 00:22:48 +010011119 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120
11121 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 if (result == -2)
11124 return NULL;
11125
Guido van Rossumd57fd912000-03-10 22:53:23 +000011126 if (result < 0) {
11127 PyErr_SetString(PyExc_ValueError, "substring not found");
11128 return NULL;
11129 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130
Christian Heimes217cfd12007-12-02 14:31:20 +000011131 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132}
11133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011134PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011135 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011137Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011138at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
11140static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011141unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 Py_ssize_t i, length;
11144 int kind;
11145 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146 int cased;
11147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148 if (PyUnicode_READY(self) == -1)
11149 return NULL;
11150 length = PyUnicode_GET_LENGTH(self);
11151 kind = PyUnicode_KIND(self);
11152 data = PyUnicode_DATA(self);
11153
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 if (length == 1)
11156 return PyBool_FromLong(
11157 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011159 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011161 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011162
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011164 for (i = 0; i < length; i++) {
11165 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011166
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11168 return PyBool_FromLong(0);
11169 else if (!cased && Py_UNICODE_ISLOWER(ch))
11170 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011172 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173}
11174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011175PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011178Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011179at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180
11181static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011182unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011184 Py_ssize_t i, length;
11185 int kind;
11186 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187 int cased;
11188
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011189 if (PyUnicode_READY(self) == -1)
11190 return NULL;
11191 length = PyUnicode_GET_LENGTH(self);
11192 kind = PyUnicode_KIND(self);
11193 data = PyUnicode_DATA(self);
11194
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 if (length == 1)
11197 return PyBool_FromLong(
11198 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011200 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011202 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011203
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 for (i = 0; i < length; i++) {
11206 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011207
Benjamin Peterson29060642009-01-31 22:14:21 +000011208 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11209 return PyBool_FromLong(0);
11210 else if (!cased && Py_UNICODE_ISUPPER(ch))
11211 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011213 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214}
11215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011216PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011219Return True if S is a titlecased string and there is at least one\n\
11220character in S, i.e. upper- and titlecase characters may only\n\
11221follow uncased characters and lowercase characters only cased ones.\n\
11222Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223
11224static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011225unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 Py_ssize_t i, length;
11228 int kind;
11229 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 int cased, previous_is_cased;
11231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 if (PyUnicode_READY(self) == -1)
11233 return NULL;
11234 length = PyUnicode_GET_LENGTH(self);
11235 kind = PyUnicode_KIND(self);
11236 data = PyUnicode_DATA(self);
11237
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 if (length == 1) {
11240 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11241 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11242 (Py_UNICODE_ISUPPER(ch) != 0));
11243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011245 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011248
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249 cased = 0;
11250 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 for (i = 0; i < length; i++) {
11252 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011253
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11255 if (previous_is_cased)
11256 return PyBool_FromLong(0);
11257 previous_is_cased = 1;
11258 cased = 1;
11259 }
11260 else if (Py_UNICODE_ISLOWER(ch)) {
11261 if (!previous_is_cased)
11262 return PyBool_FromLong(0);
11263 previous_is_cased = 1;
11264 cased = 1;
11265 }
11266 else
11267 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011269 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270}
11271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011272PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011275Return True if all characters in S are whitespace\n\
11276and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277
11278static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011279unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011281 Py_ssize_t i, length;
11282 int kind;
11283 void *data;
11284
11285 if (PyUnicode_READY(self) == -1)
11286 return NULL;
11287 length = PyUnicode_GET_LENGTH(self);
11288 kind = PyUnicode_KIND(self);
11289 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 if (length == 1)
11293 return PyBool_FromLong(
11294 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011296 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011297 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011298 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 for (i = 0; i < length; i++) {
11301 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011302 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011303 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011305 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306}
11307
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011308PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011309 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011310\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011311Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011312and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313
11314static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011315unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011316{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011317 Py_ssize_t i, length;
11318 int kind;
11319 void *data;
11320
11321 if (PyUnicode_READY(self) == -1)
11322 return NULL;
11323 length = PyUnicode_GET_LENGTH(self);
11324 kind = PyUnicode_KIND(self);
11325 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011326
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 if (length == 1)
11329 return PyBool_FromLong(
11330 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011331
11332 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011334 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 for (i = 0; i < length; i++) {
11337 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011339 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011340 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011341}
11342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011343PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011344 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011345\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011346Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011347and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011348
11349static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011350unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 int kind;
11353 void *data;
11354 Py_ssize_t len, i;
11355
11356 if (PyUnicode_READY(self) == -1)
11357 return NULL;
11358
11359 kind = PyUnicode_KIND(self);
11360 data = PyUnicode_DATA(self);
11361 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011362
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011363 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 if (len == 1) {
11365 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11366 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11367 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011368
11369 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011371 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 for (i = 0; i < len; i++) {
11374 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011375 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011376 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011377 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011378 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011379}
11380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011381PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011382 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011384Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011385False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386
11387static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011388unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 Py_ssize_t i, length;
11391 int kind;
11392 void *data;
11393
11394 if (PyUnicode_READY(self) == -1)
11395 return NULL;
11396 length = PyUnicode_GET_LENGTH(self);
11397 kind = PyUnicode_KIND(self);
11398 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 if (length == 1)
11402 return PyBool_FromLong(
11403 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011405 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011406 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011407 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 for (i = 0; i < length; i++) {
11410 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011411 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011413 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414}
11415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011419Return True if all characters in S are digits\n\
11420and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
11422static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011423unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 Py_ssize_t i, length;
11426 int kind;
11427 void *data;
11428
11429 if (PyUnicode_READY(self) == -1)
11430 return NULL;
11431 length = PyUnicode_GET_LENGTH(self);
11432 kind = PyUnicode_KIND(self);
11433 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 if (length == 1) {
11437 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11438 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11439 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011441 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445 for (i = 0; i < length; i++) {
11446 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011449 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450}
11451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011452PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011453 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011455Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011456False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457
11458static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011459unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 Py_ssize_t i, length;
11462 int kind;
11463 void *data;
11464
11465 if (PyUnicode_READY(self) == -1)
11466 return NULL;
11467 length = PyUnicode_GET_LENGTH(self);
11468 kind = PyUnicode_KIND(self);
11469 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 if (length == 1)
11473 return PyBool_FromLong(
11474 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011476 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 for (i = 0; i < length; i++) {
11481 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011484 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485}
11486
Martin v. Löwis47383402007-08-15 07:32:56 +000011487int
11488PyUnicode_IsIdentifier(PyObject *self)
11489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 int kind;
11491 void *data;
11492 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011493 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 if (PyUnicode_READY(self) == -1) {
11496 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 }
11499
11500 /* Special case for empty strings */
11501 if (PyUnicode_GET_LENGTH(self) == 0)
11502 return 0;
11503 kind = PyUnicode_KIND(self);
11504 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011505
11506 /* PEP 3131 says that the first character must be in
11507 XID_Start and subsequent characters in XID_Continue,
11508 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011509 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011510 letters, digits, underscore). However, given the current
11511 definition of XID_Start and XID_Continue, it is sufficient
11512 to check just for these, except that _ must be allowed
11513 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011515 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011516 return 0;
11517
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011518 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011520 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011521 return 1;
11522}
11523
11524PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011526\n\
11527Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011528to the language definition.\n\
11529\n\
11530Use keyword.iskeyword() to test for reserved identifiers\n\
11531such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011532
11533static PyObject*
11534unicode_isidentifier(PyObject *self)
11535{
11536 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11537}
11538
Georg Brandl559e5d72008-06-11 18:37:52 +000011539PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011541\n\
11542Return True if all characters in S are considered\n\
11543printable in repr() or S is empty, False otherwise.");
11544
11545static PyObject*
11546unicode_isprintable(PyObject *self)
11547{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 Py_ssize_t i, length;
11549 int kind;
11550 void *data;
11551
11552 if (PyUnicode_READY(self) == -1)
11553 return NULL;
11554 length = PyUnicode_GET_LENGTH(self);
11555 kind = PyUnicode_KIND(self);
11556 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011557
11558 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 if (length == 1)
11560 return PyBool_FromLong(
11561 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011563 for (i = 0; i < length; i++) {
11564 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011565 Py_RETURN_FALSE;
11566 }
11567 }
11568 Py_RETURN_TRUE;
11569}
11570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011571PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011572 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573\n\
11574Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011575iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
11577static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011578unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011580 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581}
11582
Martin v. Löwis18e16552006-02-15 17:27:45 +000011583static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011584unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 if (PyUnicode_READY(self) == -1)
11587 return -1;
11588 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589}
11590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011591PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011594Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011595done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596
11597static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011598unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011600 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 Py_UCS4 fillchar = ' ';
11602
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011603 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604 return NULL;
11605
Benjamin Petersonbac79492012-01-14 13:34:47 -050011606 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011607 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608
Victor Stinnerc4b49542011-12-11 22:44:26 +010011609 if (PyUnicode_GET_LENGTH(self) >= width)
11610 return unicode_result_unchanged(self);
11611
11612 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613}
11614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011615PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011616 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011618Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619
11620static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011621unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011623 if (PyUnicode_READY(self) == -1)
11624 return NULL;
11625 if (PyUnicode_IS_ASCII(self))
11626 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011627 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628}
11629
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011630#define LEFTSTRIP 0
11631#define RIGHTSTRIP 1
11632#define BOTHSTRIP 2
11633
11634/* Arrays indexed by above */
11635static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11636
11637#define STRIPNAME(i) (stripformat[i]+3)
11638
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011639/* externally visible for str.strip(unicode) */
11640PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011641_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011642{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 void *data;
11644 int kind;
11645 Py_ssize_t i, j, len;
11646 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011647 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11650 return NULL;
11651
11652 kind = PyUnicode_KIND(self);
11653 data = PyUnicode_DATA(self);
11654 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011655 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11657 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011658 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011659
Benjamin Peterson14339b62009-01-31 16:36:08 +000011660 i = 0;
11661 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011662 while (i < len) {
11663 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11664 if (!BLOOM(sepmask, ch))
11665 break;
11666 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11667 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011668 i++;
11669 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011670 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011671
Benjamin Peterson14339b62009-01-31 16:36:08 +000011672 j = len;
11673 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011674 j--;
11675 while (j >= i) {
11676 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11677 if (!BLOOM(sepmask, ch))
11678 break;
11679 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11680 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011681 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011682 }
11683
Benjamin Peterson29060642009-01-31 22:14:21 +000011684 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011685 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011686
Victor Stinner7931d9a2011-11-04 00:22:48 +010011687 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688}
11689
11690PyObject*
11691PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11692{
11693 unsigned char *data;
11694 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011695 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696
Victor Stinnerde636f32011-10-01 03:55:54 +020011697 if (PyUnicode_READY(self) == -1)
11698 return NULL;
11699
Victor Stinner684d5fd2012-05-03 02:32:34 +020011700 length = PyUnicode_GET_LENGTH(self);
11701 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011702
Victor Stinner684d5fd2012-05-03 02:32:34 +020011703 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011704 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705
Victor Stinnerde636f32011-10-01 03:55:54 +020011706 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011707 PyErr_SetString(PyExc_IndexError, "string index out of range");
11708 return NULL;
11709 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011710 if (start >= length || end < start)
11711 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011712
Victor Stinner684d5fd2012-05-03 02:32:34 +020011713 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011714 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011715 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011716 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011717 }
11718 else {
11719 kind = PyUnicode_KIND(self);
11720 data = PyUnicode_1BYTE_DATA(self);
11721 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011722 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011723 length);
11724 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726
11727static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011728do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 Py_ssize_t len, i, j;
11731
11732 if (PyUnicode_READY(self) == -1)
11733 return NULL;
11734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011736
Victor Stinnercc7af722013-04-09 22:39:24 +020011737 if (PyUnicode_IS_ASCII(self)) {
11738 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
11739
11740 i = 0;
11741 if (striptype != RIGHTSTRIP) {
11742 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020011743 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020011744 if (!_Py_ascii_whitespace[ch])
11745 break;
11746 i++;
11747 }
11748 }
11749
11750 j = len;
11751 if (striptype != LEFTSTRIP) {
11752 j--;
11753 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020011754 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020011755 if (!_Py_ascii_whitespace[ch])
11756 break;
11757 j--;
11758 }
11759 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011760 }
11761 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011762 else {
11763 int kind = PyUnicode_KIND(self);
11764 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765
Victor Stinnercc7af722013-04-09 22:39:24 +020011766 i = 0;
11767 if (striptype != RIGHTSTRIP) {
11768 while (i < len) {
11769 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11770 if (!Py_UNICODE_ISSPACE(ch))
11771 break;
11772 i++;
11773 }
Victor Stinner9c79e412013-04-09 22:21:08 +020011774 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011775
11776 j = len;
11777 if (striptype != LEFTSTRIP) {
11778 j--;
11779 while (j >= i) {
11780 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11781 if (!Py_UNICODE_ISSPACE(ch))
11782 break;
11783 j--;
11784 }
11785 j++;
11786 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011787 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
Victor Stinner7931d9a2011-11-04 00:22:48 +010011789 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790}
11791
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792
11793static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011794do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011796 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011797
Benjamin Peterson14339b62009-01-31 16:36:08 +000011798 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11799 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011800
Benjamin Peterson14339b62009-01-31 16:36:08 +000011801 if (sep != NULL && sep != Py_None) {
11802 if (PyUnicode_Check(sep))
11803 return _PyUnicode_XStrip(self, striptype, sep);
11804 else {
11805 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011806 "%s arg must be None or str",
11807 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011808 return NULL;
11809 }
11810 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811
Benjamin Peterson14339b62009-01-31 16:36:08 +000011812 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011813}
11814
11815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011816PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818\n\
11819Return a copy of the string S with leading and trailing\n\
11820whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011821If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011822
11823static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011824unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011825{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011826 if (PyTuple_GET_SIZE(args) == 0)
11827 return do_strip(self, BOTHSTRIP); /* Common case */
11828 else
11829 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830}
11831
11832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011833PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011834 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011835\n\
11836Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011837If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011838
11839static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011840unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011842 if (PyTuple_GET_SIZE(args) == 0)
11843 return do_strip(self, LEFTSTRIP); /* Common case */
11844 else
11845 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011846}
11847
11848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011849PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011851\n\
11852Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011853If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011854
11855static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011856unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011857{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011858 if (PyTuple_GET_SIZE(args) == 0)
11859 return do_strip(self, RIGHTSTRIP); /* Common case */
11860 else
11861 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011862}
11863
11864
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011866unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011867{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011868 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870
Serhiy Storchaka05997252013-01-26 12:14:02 +020011871 if (len < 1)
11872 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
Victor Stinnerc4b49542011-12-11 22:44:26 +010011874 /* no repeat, return original string */
11875 if (len == 1)
11876 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011877
Benjamin Petersonbac79492012-01-14 13:34:47 -050011878 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 return NULL;
11880
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011881 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011882 PyErr_SetString(PyExc_OverflowError,
11883 "repeated string is too long");
11884 return NULL;
11885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011887
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011888 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889 if (!u)
11890 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011891 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 if (PyUnicode_GET_LENGTH(str) == 1) {
11894 const int kind = PyUnicode_KIND(str);
11895 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011896 if (kind == PyUnicode_1BYTE_KIND) {
11897 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011898 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011899 }
11900 else if (kind == PyUnicode_2BYTE_KIND) {
11901 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011902 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011903 ucs2[n] = fill_char;
11904 } else {
11905 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11906 assert(kind == PyUnicode_4BYTE_KIND);
11907 for (n = 0; n < len; ++n)
11908 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011909 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 }
11911 else {
11912 /* number of characters copied this far */
11913 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011914 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 char *to = (char *) PyUnicode_DATA(u);
11916 Py_MEMCPY(to, PyUnicode_DATA(str),
11917 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011918 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 n = (done <= nchars-done) ? done : nchars-done;
11920 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011921 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923 }
11924
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011925 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011926 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927}
11928
Alexander Belopolsky40018472011-02-26 01:02:56 +000011929PyObject *
11930PyUnicode_Replace(PyObject *obj,
11931 PyObject *subobj,
11932 PyObject *replobj,
11933 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934{
11935 PyObject *self;
11936 PyObject *str1;
11937 PyObject *str2;
11938 PyObject *result;
11939
11940 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011941 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011942 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011944 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 Py_DECREF(self);
11946 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 }
11948 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011949 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 Py_DECREF(self);
11951 Py_DECREF(str1);
11952 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011954 if (PyUnicode_READY(self) == -1 ||
11955 PyUnicode_READY(str1) == -1 ||
11956 PyUnicode_READY(str2) == -1)
11957 result = NULL;
11958 else
11959 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960 Py_DECREF(self);
11961 Py_DECREF(str1);
11962 Py_DECREF(str2);
11963 return result;
11964}
11965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011966PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011967 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968\n\
11969Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011970old replaced by new. If the optional argument count is\n\
11971given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972
11973static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011974unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 PyObject *str1;
11977 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011978 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979 PyObject *result;
11980
Martin v. Löwis18e16552006-02-15 17:27:45 +000011981 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011982 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011983 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011984 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011986 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 return NULL;
11988 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011989 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011990 Py_DECREF(str1);
11991 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011992 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011993 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11994 result = NULL;
11995 else
11996 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997
11998 Py_DECREF(str1);
11999 Py_DECREF(str2);
12000 return result;
12001}
12002
Alexander Belopolsky40018472011-02-26 01:02:56 +000012003static PyObject *
12004unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012006 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 Py_ssize_t isize;
12008 Py_ssize_t osize, squote, dquote, i, o;
12009 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012010 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012014 return NULL;
12015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 isize = PyUnicode_GET_LENGTH(unicode);
12017 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 /* Compute length of output, quote characters, and
12020 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012021 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 max = 127;
12023 squote = dquote = 0;
12024 ikind = PyUnicode_KIND(unicode);
12025 for (i = 0; i < isize; i++) {
12026 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12027 switch (ch) {
12028 case '\'': squote++; osize++; break;
12029 case '"': dquote++; osize++; break;
12030 case '\\': case '\t': case '\r': case '\n':
12031 osize += 2; break;
12032 default:
12033 /* Fast-path ASCII */
12034 if (ch < ' ' || ch == 0x7f)
12035 osize += 4; /* \xHH */
12036 else if (ch < 0x7f)
12037 osize++;
12038 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12039 osize++;
12040 max = ch > max ? ch : max;
12041 }
12042 else if (ch < 0x100)
12043 osize += 4; /* \xHH */
12044 else if (ch < 0x10000)
12045 osize += 6; /* \uHHHH */
12046 else
12047 osize += 10; /* \uHHHHHHHH */
12048 }
12049 }
12050
12051 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012052 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012054 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 if (dquote)
12056 /* Both squote and dquote present. Use squote,
12057 and escape them */
12058 osize += squote;
12059 else
12060 quote = '"';
12061 }
Victor Stinner55c08782013-04-14 18:45:39 +020012062 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063
12064 repr = PyUnicode_New(osize, max);
12065 if (repr == NULL)
12066 return NULL;
12067 okind = PyUnicode_KIND(repr);
12068 odata = PyUnicode_DATA(repr);
12069
12070 PyUnicode_WRITE(okind, odata, 0, quote);
12071 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012072 if (unchanged) {
12073 _PyUnicode_FastCopyCharacters(repr, 1,
12074 unicode, 0,
12075 isize);
12076 }
12077 else {
12078 for (i = 0, o = 1; i < isize; i++) {
12079 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080
Victor Stinner55c08782013-04-14 18:45:39 +020012081 /* Escape quotes and backslashes */
12082 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012083 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012084 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012085 continue;
12086 }
12087
12088 /* Map special whitespace to '\t', \n', '\r' */
12089 if (ch == '\t') {
12090 PyUnicode_WRITE(okind, odata, o++, '\\');
12091 PyUnicode_WRITE(okind, odata, o++, 't');
12092 }
12093 else if (ch == '\n') {
12094 PyUnicode_WRITE(okind, odata, o++, '\\');
12095 PyUnicode_WRITE(okind, odata, o++, 'n');
12096 }
12097 else if (ch == '\r') {
12098 PyUnicode_WRITE(okind, odata, o++, '\\');
12099 PyUnicode_WRITE(okind, odata, o++, 'r');
12100 }
12101
12102 /* Map non-printable US ASCII to '\xhh' */
12103 else if (ch < ' ' || ch == 0x7F) {
12104 PyUnicode_WRITE(okind, odata, o++, '\\');
12105 PyUnicode_WRITE(okind, odata, o++, 'x');
12106 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12107 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12108 }
12109
12110 /* Copy ASCII characters as-is */
12111 else if (ch < 0x7F) {
12112 PyUnicode_WRITE(okind, odata, o++, ch);
12113 }
12114
12115 /* Non-ASCII characters */
12116 else {
12117 /* Map Unicode whitespace and control characters
12118 (categories Z* and C* except ASCII space)
12119 */
12120 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12121 PyUnicode_WRITE(okind, odata, o++, '\\');
12122 /* Map 8-bit characters to '\xhh' */
12123 if (ch <= 0xff) {
12124 PyUnicode_WRITE(okind, odata, o++, 'x');
12125 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12126 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12127 }
12128 /* Map 16-bit characters to '\uxxxx' */
12129 else if (ch <= 0xffff) {
12130 PyUnicode_WRITE(okind, odata, o++, 'u');
12131 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12132 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12133 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12134 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12135 }
12136 /* Map 21-bit characters to '\U00xxxxxx' */
12137 else {
12138 PyUnicode_WRITE(okind, odata, o++, 'U');
12139 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12140 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12141 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12142 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12143 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12144 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12145 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12146 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12147 }
12148 }
12149 /* Copy characters as-is */
12150 else {
12151 PyUnicode_WRITE(okind, odata, o++, ch);
12152 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012153 }
12154 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012157 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012158 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159}
12160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012161PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012162 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163\n\
12164Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012165such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166arguments start and end are interpreted as in slice notation.\n\
12167\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012168Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169
12170static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012171unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012173 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012174 Py_ssize_t start;
12175 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012176 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177
Jesus Ceaac451502011-04-20 17:09:23 +020012178 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12179 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012180 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 if (PyUnicode_READY(self) == -1)
12183 return NULL;
12184 if (PyUnicode_READY(substring) == -1)
12185 return NULL;
12186
Victor Stinner7931d9a2011-11-04 00:22:48 +010012187 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
12189 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 if (result == -2)
12192 return NULL;
12193
Christian Heimes217cfd12007-12-02 14:31:20 +000012194 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195}
12196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012197PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012198 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012200Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201
12202static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012205 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012206 Py_ssize_t start;
12207 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012208 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
Jesus Ceaac451502011-04-20 17:09:23 +020012210 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12211 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012212 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (PyUnicode_READY(self) == -1)
12215 return NULL;
12216 if (PyUnicode_READY(substring) == -1)
12217 return NULL;
12218
Victor Stinner7931d9a2011-11-04 00:22:48 +010012219 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220
12221 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 if (result == -2)
12224 return NULL;
12225
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226 if (result < 0) {
12227 PyErr_SetString(PyExc_ValueError, "substring not found");
12228 return NULL;
12229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230
Christian Heimes217cfd12007-12-02 14:31:20 +000012231 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232}
12233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012234PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012237Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012238done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239
12240static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012241unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012243 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012244 Py_UCS4 fillchar = ' ';
12245
Victor Stinnere9a29352011-10-01 02:14:59 +020012246 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012248
Benjamin Petersonbac79492012-01-14 13:34:47 -050012249 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250 return NULL;
12251
Victor Stinnerc4b49542011-12-11 22:44:26 +010012252 if (PyUnicode_GET_LENGTH(self) >= width)
12253 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254
Victor Stinnerc4b49542011-12-11 22:44:26 +010012255 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256}
12257
Alexander Belopolsky40018472011-02-26 01:02:56 +000012258PyObject *
12259PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260{
12261 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012262
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 s = PyUnicode_FromObject(s);
12264 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012265 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012266 if (sep != NULL) {
12267 sep = PyUnicode_FromObject(sep);
12268 if (sep == NULL) {
12269 Py_DECREF(s);
12270 return NULL;
12271 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272 }
12273
Victor Stinner9310abb2011-10-05 00:59:23 +020012274 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275
12276 Py_DECREF(s);
12277 Py_XDECREF(sep);
12278 return result;
12279}
12280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012281PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012282 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283\n\
12284Return a list of the words in S, using sep as the\n\
12285delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012286splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012287whitespace string is a separator and empty strings are\n\
12288removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289
12290static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012291unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012293 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012295 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012297 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12298 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012299 return NULL;
12300
12301 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012302 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012304 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012306 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012307}
12308
Thomas Wouters477c8d52006-05-27 19:21:47 +000012309PyObject *
12310PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12311{
12312 PyObject* str_obj;
12313 PyObject* sep_obj;
12314 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 int kind1, kind2, kind;
12316 void *buf1 = NULL, *buf2 = NULL;
12317 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012318
12319 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012320 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012322 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012323 if (!sep_obj) {
12324 Py_DECREF(str_obj);
12325 return NULL;
12326 }
12327 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12328 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012329 Py_DECREF(str_obj);
12330 return NULL;
12331 }
12332
Victor Stinner14f8f022011-10-05 20:58:25 +020012333 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012335 kind = Py_MAX(kind1, kind2);
12336 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012338 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 if (!buf1)
12340 goto onError;
12341 buf2 = PyUnicode_DATA(sep_obj);
12342 if (kind2 != kind)
12343 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12344 if (!buf2)
12345 goto onError;
12346 len1 = PyUnicode_GET_LENGTH(str_obj);
12347 len2 = PyUnicode_GET_LENGTH(sep_obj);
12348
Benjamin Petersonead6b532011-12-20 17:23:42 -060012349 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012351 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12352 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12353 else
12354 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 break;
12356 case PyUnicode_2BYTE_KIND:
12357 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12358 break;
12359 case PyUnicode_4BYTE_KIND:
12360 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12361 break;
12362 default:
12363 assert(0);
12364 out = 0;
12365 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012366
12367 Py_DECREF(sep_obj);
12368 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 if (kind1 != kind)
12370 PyMem_Free(buf1);
12371 if (kind2 != kind)
12372 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373
12374 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 onError:
12376 Py_DECREF(sep_obj);
12377 Py_DECREF(str_obj);
12378 if (kind1 != kind && buf1)
12379 PyMem_Free(buf1);
12380 if (kind2 != kind && buf2)
12381 PyMem_Free(buf2);
12382 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012383}
12384
12385
12386PyObject *
12387PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12388{
12389 PyObject* str_obj;
12390 PyObject* sep_obj;
12391 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 int kind1, kind2, kind;
12393 void *buf1 = NULL, *buf2 = NULL;
12394 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395
12396 str_obj = PyUnicode_FromObject(str_in);
12397 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012398 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399 sep_obj = PyUnicode_FromObject(sep_in);
12400 if (!sep_obj) {
12401 Py_DECREF(str_obj);
12402 return NULL;
12403 }
12404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 kind1 = PyUnicode_KIND(str_in);
12406 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012407 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012408 buf1 = PyUnicode_DATA(str_in);
12409 if (kind1 != kind)
12410 buf1 = _PyUnicode_AsKind(str_in, kind);
12411 if (!buf1)
12412 goto onError;
12413 buf2 = PyUnicode_DATA(sep_obj);
12414 if (kind2 != kind)
12415 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12416 if (!buf2)
12417 goto onError;
12418 len1 = PyUnicode_GET_LENGTH(str_obj);
12419 len2 = PyUnicode_GET_LENGTH(sep_obj);
12420
Benjamin Petersonead6b532011-12-20 17:23:42 -060012421 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012423 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12424 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12425 else
12426 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 break;
12428 case PyUnicode_2BYTE_KIND:
12429 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12430 break;
12431 case PyUnicode_4BYTE_KIND:
12432 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12433 break;
12434 default:
12435 assert(0);
12436 out = 0;
12437 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012438
12439 Py_DECREF(sep_obj);
12440 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 if (kind1 != kind)
12442 PyMem_Free(buf1);
12443 if (kind2 != kind)
12444 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012445
12446 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012447 onError:
12448 Py_DECREF(sep_obj);
12449 Py_DECREF(str_obj);
12450 if (kind1 != kind && buf1)
12451 PyMem_Free(buf1);
12452 if (kind2 != kind && buf2)
12453 PyMem_Free(buf2);
12454 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012455}
12456
12457PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012458 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012459\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012460Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012461the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012462found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463
12464static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012465unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012466{
Victor Stinner9310abb2011-10-05 00:59:23 +020012467 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012468}
12469
12470PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012471 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012472\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012473Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012474the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012475separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012476
12477static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012478unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012479{
Victor Stinner9310abb2011-10-05 00:59:23 +020012480 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012481}
12482
Alexander Belopolsky40018472011-02-26 01:02:56 +000012483PyObject *
12484PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012485{
12486 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012487
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012488 s = PyUnicode_FromObject(s);
12489 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012490 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 if (sep != NULL) {
12492 sep = PyUnicode_FromObject(sep);
12493 if (sep == NULL) {
12494 Py_DECREF(s);
12495 return NULL;
12496 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012497 }
12498
Victor Stinner9310abb2011-10-05 00:59:23 +020012499 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012500
12501 Py_DECREF(s);
12502 Py_XDECREF(sep);
12503 return result;
12504}
12505
12506PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012507 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012508\n\
12509Return a list of the words in S, using sep as the\n\
12510delimiter string, starting at the end of the string and\n\
12511working to the front. If maxsplit is given, at most maxsplit\n\
12512splits are done. If sep is not specified, any whitespace string\n\
12513is a separator.");
12514
12515static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012516unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012517{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012518 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012519 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012520 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012521
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012522 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12523 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012524 return NULL;
12525
12526 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012527 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012528 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012529 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012530 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012531 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012532}
12533
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012534PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012535 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536\n\
12537Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012538Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012539is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540
12541static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012542unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012544 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012545 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012547 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12548 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549 return NULL;
12550
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012551 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552}
12553
12554static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012555PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012556{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012557 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558}
12559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012560PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012561 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562\n\
12563Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012564and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565
12566static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012567unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012569 if (PyUnicode_READY(self) == -1)
12570 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012571 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012572}
12573
Georg Brandlceee0772007-11-27 23:48:05 +000012574PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012575 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012576\n\
12577Return a translation table usable for str.translate().\n\
12578If there is only one argument, it must be a dictionary mapping Unicode\n\
12579ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012580Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012581If there are two arguments, they must be strings of equal length, and\n\
12582in the resulting dictionary, each character in x will be mapped to the\n\
12583character at the same position in y. If there is a third argument, it\n\
12584must be a string, whose characters will be mapped to None in the result.");
12585
12586static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012587unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012588{
12589 PyObject *x, *y = NULL, *z = NULL;
12590 PyObject *new = NULL, *key, *value;
12591 Py_ssize_t i = 0;
12592 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012593
Georg Brandlceee0772007-11-27 23:48:05 +000012594 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12595 return NULL;
12596 new = PyDict_New();
12597 if (!new)
12598 return NULL;
12599 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600 int x_kind, y_kind, z_kind;
12601 void *x_data, *y_data, *z_data;
12602
Georg Brandlceee0772007-11-27 23:48:05 +000012603 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012604 if (!PyUnicode_Check(x)) {
12605 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12606 "be a string if there is a second argument");
12607 goto err;
12608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012610 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12611 "arguments must have equal length");
12612 goto err;
12613 }
12614 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012615 x_kind = PyUnicode_KIND(x);
12616 y_kind = PyUnicode_KIND(y);
12617 x_data = PyUnicode_DATA(x);
12618 y_data = PyUnicode_DATA(y);
12619 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12620 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012621 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012622 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012623 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012624 if (!value) {
12625 Py_DECREF(key);
12626 goto err;
12627 }
Georg Brandlceee0772007-11-27 23:48:05 +000012628 res = PyDict_SetItem(new, key, value);
12629 Py_DECREF(key);
12630 Py_DECREF(value);
12631 if (res < 0)
12632 goto err;
12633 }
12634 /* create entries for deleting chars in z */
12635 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 z_kind = PyUnicode_KIND(z);
12637 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012638 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012640 if (!key)
12641 goto err;
12642 res = PyDict_SetItem(new, key, Py_None);
12643 Py_DECREF(key);
12644 if (res < 0)
12645 goto err;
12646 }
12647 }
12648 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 int kind;
12650 void *data;
12651
Georg Brandlceee0772007-11-27 23:48:05 +000012652 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012653 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012654 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12655 "to maketrans it must be a dict");
12656 goto err;
12657 }
12658 /* copy entries into the new dict, converting string keys to int keys */
12659 while (PyDict_Next(x, &i, &key, &value)) {
12660 if (PyUnicode_Check(key)) {
12661 /* convert string keys to integer keys */
12662 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012663 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012664 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12665 "table must be of length 1");
12666 goto err;
12667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 kind = PyUnicode_KIND(key);
12669 data = PyUnicode_DATA(key);
12670 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012671 if (!newkey)
12672 goto err;
12673 res = PyDict_SetItem(new, newkey, value);
12674 Py_DECREF(newkey);
12675 if (res < 0)
12676 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012677 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012678 /* just keep integer keys */
12679 if (PyDict_SetItem(new, key, value) < 0)
12680 goto err;
12681 } else {
12682 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12683 "be strings or integers");
12684 goto err;
12685 }
12686 }
12687 }
12688 return new;
12689 err:
12690 Py_DECREF(new);
12691 return NULL;
12692}
12693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012694PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696\n\
12697Return a copy of the string S, where all characters have been mapped\n\
12698through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012699Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012700Unmapped characters are left untouched. Characters mapped to None\n\
12701are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702
12703static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707}
12708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012709PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012710 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012712Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713
12714static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012715unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012717 if (PyUnicode_READY(self) == -1)
12718 return NULL;
12719 if (PyUnicode_IS_ASCII(self))
12720 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012721 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722}
12723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012724PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012725 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012727Pad a numeric string S with zeros on the left, to fill a field\n\
12728of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729
12730static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012731unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012733 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012734 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012735 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 int kind;
12737 void *data;
12738 Py_UCS4 chr;
12739
Martin v. Löwis18e16552006-02-15 17:27:45 +000012740 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741 return NULL;
12742
Benjamin Petersonbac79492012-01-14 13:34:47 -050012743 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012744 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
Victor Stinnerc4b49542011-12-11 22:44:26 +010012746 if (PyUnicode_GET_LENGTH(self) >= width)
12747 return unicode_result_unchanged(self);
12748
12749 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750
12751 u = pad(self, fill, 0, '0');
12752
Walter Dörwald068325e2002-04-15 13:36:47 +000012753 if (u == NULL)
12754 return NULL;
12755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 kind = PyUnicode_KIND(u);
12757 data = PyUnicode_DATA(u);
12758 chr = PyUnicode_READ(kind, data, fill);
12759
12760 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762 PyUnicode_WRITE(kind, data, 0, chr);
12763 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764 }
12765
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012766 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012767 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769
12770#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012771static PyObject *
12772unicode__decimal2ascii(PyObject *self)
12773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012775}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776#endif
12777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012778PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012779 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012781Return True if S starts with the specified prefix, False otherwise.\n\
12782With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012783With optional end, stop comparing S at that position.\n\
12784prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785
12786static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012787unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012788 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012790 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012791 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012792 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012793 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012794 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795
Jesus Ceaac451502011-04-20 17:09:23 +020012796 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012797 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012798 if (PyTuple_Check(subobj)) {
12799 Py_ssize_t i;
12800 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012801 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012802 if (substring == NULL)
12803 return NULL;
12804 result = tailmatch(self, substring, start, end, -1);
12805 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012806 if (result == -1)
12807 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012808 if (result) {
12809 Py_RETURN_TRUE;
12810 }
12811 }
12812 /* nothing matched */
12813 Py_RETURN_FALSE;
12814 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012815 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012816 if (substring == NULL) {
12817 if (PyErr_ExceptionMatches(PyExc_TypeError))
12818 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12819 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012821 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012822 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012824 if (result == -1)
12825 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012826 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827}
12828
12829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012830PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012831 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012833Return True if S ends with the specified suffix, False otherwise.\n\
12834With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012835With optional end, stop comparing S at that position.\n\
12836suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012837
12838static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012839unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012840 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012842 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012843 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012844 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012845 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012846 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847
Jesus Ceaac451502011-04-20 17:09:23 +020012848 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012849 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012850 if (PyTuple_Check(subobj)) {
12851 Py_ssize_t i;
12852 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012853 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012854 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012855 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012856 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012857 result = tailmatch(self, substring, start, end, +1);
12858 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012859 if (result == -1)
12860 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012861 if (result) {
12862 Py_RETURN_TRUE;
12863 }
12864 }
12865 Py_RETURN_FALSE;
12866 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012867 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012868 if (substring == NULL) {
12869 if (PyErr_ExceptionMatches(PyExc_TypeError))
12870 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12871 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012872 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012873 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012874 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010012875 if (result == -1)
12876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012878 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012879}
12880
Victor Stinner202fdca2012-05-07 12:47:02 +020012881Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012882_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012883{
Victor Stinner8f674cc2013-04-17 23:02:17 +020012884 if (!writer->readonly)
12885 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
12886 else {
12887 /* Copy-on-write mode: set buffer size to 0 so
12888 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
12889 * next write. */
12890 writer->size = 0;
12891 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012892 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12893 writer->data = PyUnicode_DATA(writer->buffer);
12894 writer->kind = PyUnicode_KIND(writer->buffer);
12895}
12896
Victor Stinnerd3f08822012-05-29 12:57:52 +020012897void
Victor Stinner8f674cc2013-04-17 23:02:17 +020012898_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012899{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012900 memset(writer, 0, sizeof(*writer));
12901#ifdef Py_DEBUG
12902 writer->kind = 5; /* invalid kind */
12903#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020012904 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020012905}
12906
Victor Stinnerd3f08822012-05-29 12:57:52 +020012907int
12908_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12909 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012910{
12911 Py_ssize_t newlen;
12912 PyObject *newbuffer;
12913
Victor Stinnerd3f08822012-05-29 12:57:52 +020012914 assert(length > 0);
12915
Victor Stinner202fdca2012-05-07 12:47:02 +020012916 if (length > PY_SSIZE_T_MAX - writer->pos) {
12917 PyErr_NoMemory();
12918 return -1;
12919 }
12920 newlen = writer->pos + length;
12921
Victor Stinner8f674cc2013-04-17 23:02:17 +020012922 maxchar = MAX_MAXCHAR(maxchar, writer->min_char);
12923
Victor Stinnerd3f08822012-05-29 12:57:52 +020012924 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020012925 assert(!writer->readonly);
12926 if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / 4)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012927 /* overallocate 25% to limit the number of resize */
Victor Stinner8f674cc2013-04-17 23:02:17 +020012928 newlen += newlen / 4;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012929 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020012930 if (newlen < writer->min_length)
12931 newlen = writer->min_length;
12932
Victor Stinnerd3f08822012-05-29 12:57:52 +020012933 writer->buffer = PyUnicode_New(newlen, maxchar);
12934 if (writer->buffer == NULL)
12935 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012936 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020012937 else if (newlen > writer->size) {
12938 if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / 4)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012939 /* overallocate 25% to limit the number of resize */
Victor Stinner8f674cc2013-04-17 23:02:17 +020012940 newlen += newlen / 4;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012941 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020012942 if (newlen < writer->min_length)
12943 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012944
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012945 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012946 /* resize + widen */
12947 newbuffer = PyUnicode_New(newlen, maxchar);
12948 if (newbuffer == NULL)
12949 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012950 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12951 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012952 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012953 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012954 }
12955 else {
12956 newbuffer = resize_compact(writer->buffer, newlen);
12957 if (newbuffer == NULL)
12958 return -1;
12959 }
12960 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012961 }
12962 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012963 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012964 newbuffer = PyUnicode_New(writer->size, maxchar);
12965 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012966 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012967 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12968 writer->buffer, 0, writer->pos);
12969 Py_DECREF(writer->buffer);
12970 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012971 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020012972 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012973 return 0;
12974}
12975
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020012976Py_LOCAL_INLINE(int)
12977_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020012978{
12979 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
12980 return -1;
12981 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
12982 writer->pos++;
12983 return 0;
12984}
12985
12986int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020012987_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
12988{
12989 return _PyUnicodeWriter_WriteCharInline(writer, ch);
12990}
12991
12992int
Victor Stinnerd3f08822012-05-29 12:57:52 +020012993_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12994{
12995 Py_UCS4 maxchar;
12996 Py_ssize_t len;
12997
12998 if (PyUnicode_READY(str) == -1)
12999 return -1;
13000 len = PyUnicode_GET_LENGTH(str);
13001 if (len == 0)
13002 return 0;
13003 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13004 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013005 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013006 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013007 Py_INCREF(str);
13008 writer->buffer = str;
13009 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013010 writer->pos += len;
13011 return 0;
13012 }
13013 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13014 return -1;
13015 }
13016 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13017 str, 0, len);
13018 writer->pos += len;
13019 return 0;
13020}
13021
Victor Stinnere215d962012-10-06 23:03:36 +020013022int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013023_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13024 Py_ssize_t start, Py_ssize_t end)
13025{
13026 Py_UCS4 maxchar;
13027 Py_ssize_t len;
13028
13029 if (PyUnicode_READY(str) == -1)
13030 return -1;
13031
13032 assert(0 <= start);
13033 assert(end <= PyUnicode_GET_LENGTH(str));
13034 assert(start <= end);
13035
13036 if (end == 0)
13037 return 0;
13038
13039 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13040 return _PyUnicodeWriter_WriteStr(writer, str);
13041
13042 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13043 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13044 else
13045 maxchar = writer->maxchar;
13046 len = end - start;
13047
13048 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13049 return -1;
13050
13051 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13052 str, start, len);
13053 writer->pos += len;
13054 return 0;
13055}
13056
13057int
Victor Stinnere215d962012-10-06 23:03:36 +020013058_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
13059{
13060 Py_UCS4 maxchar;
13061
13062 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13063 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13064 return -1;
13065 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13066 writer->pos += len;
13067 return 0;
13068}
13069
Victor Stinnerd3f08822012-05-29 12:57:52 +020013070PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013071_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013072{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013073 if (writer->pos == 0) {
13074 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013075 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013076 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013077 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013078 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
13079 return writer->buffer;
13080 }
13081 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13082 PyObject *newbuffer;
13083 newbuffer = resize_compact(writer->buffer, writer->pos);
13084 if (newbuffer == NULL) {
13085 Py_DECREF(writer->buffer);
13086 return NULL;
13087 }
13088 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013089 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020013090 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner2cb16aa2013-03-06 19:28:37 +010013091 return unicode_result_ready(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013092}
13093
Victor Stinnerd3f08822012-05-29 12:57:52 +020013094void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013095_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013096{
13097 Py_CLEAR(writer->buffer);
13098}
13099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013100#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013101
13102PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013103 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013104\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013105Return a formatted version of S, using substitutions from args and kwargs.\n\
13106The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013107
Eric Smith27bbca62010-11-04 17:06:58 +000013108PyDoc_STRVAR(format_map__doc__,
13109 "S.format_map(mapping) -> str\n\
13110\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013111Return a formatted version of S, using substitutions from mapping.\n\
13112The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013113
Eric Smith4a7d76d2008-05-30 18:10:19 +000013114static PyObject *
13115unicode__format__(PyObject* self, PyObject* args)
13116{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013117 PyObject *format_spec;
13118 _PyUnicodeWriter writer;
13119 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013120
13121 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13122 return NULL;
13123
Victor Stinnerd3f08822012-05-29 12:57:52 +020013124 if (PyUnicode_READY(self) == -1)
13125 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013126 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013127 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13128 self, format_spec, 0,
13129 PyUnicode_GET_LENGTH(format_spec));
13130 if (ret == -1) {
13131 _PyUnicodeWriter_Dealloc(&writer);
13132 return NULL;
13133 }
13134 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013135}
13136
Eric Smith8c663262007-08-25 02:26:07 +000013137PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013138 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013139\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013140Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013141
13142static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013143unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013144{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 Py_ssize_t size;
13146
13147 /* If it's a compact object, account for base structure +
13148 character data. */
13149 if (PyUnicode_IS_COMPACT_ASCII(v))
13150 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13151 else if (PyUnicode_IS_COMPACT(v))
13152 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013153 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013154 else {
13155 /* If it is a two-block object, account for base object, and
13156 for character block if present. */
13157 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013158 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013160 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013161 }
13162 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013163 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013164 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013165 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013166 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013167 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013168
13169 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013170}
13171
13172PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013173 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013174
13175static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013176unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013177{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013178 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013179 if (!copy)
13180 return NULL;
13181 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013182}
13183
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013185 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013186 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013187 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13188 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013189 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13190 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013191 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013192 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13193 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13194 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13195 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13196 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013197 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013198 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13199 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13200 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013201 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013202 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13203 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13204 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013205 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013206 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013207 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013208 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013209 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13210 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13211 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13212 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13213 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13214 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13215 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13216 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13217 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13218 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13219 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13220 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13221 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13222 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013223 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013224 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013225 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013226 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013227 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013228 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013229 {"maketrans", (PyCFunction) unicode_maketrans,
13230 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013231 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013232#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013233 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013234 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235#endif
13236
Benjamin Peterson14339b62009-01-31 16:36:08 +000013237 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238 {NULL, NULL}
13239};
13240
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013241static PyObject *
13242unicode_mod(PyObject *v, PyObject *w)
13243{
Brian Curtindfc80e32011-08-10 20:28:54 -050013244 if (!PyUnicode_Check(v))
13245 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013247}
13248
13249static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013250 0, /*nb_add*/
13251 0, /*nb_subtract*/
13252 0, /*nb_multiply*/
13253 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013254};
13255
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013257 (lenfunc) unicode_length, /* sq_length */
13258 PyUnicode_Concat, /* sq_concat */
13259 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13260 (ssizeargfunc) unicode_getitem, /* sq_item */
13261 0, /* sq_slice */
13262 0, /* sq_ass_item */
13263 0, /* sq_ass_slice */
13264 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265};
13266
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013267static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013268unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013269{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013270 if (PyUnicode_READY(self) == -1)
13271 return NULL;
13272
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013273 if (PyIndex_Check(item)) {
13274 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013275 if (i == -1 && PyErr_Occurred())
13276 return NULL;
13277 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013278 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013279 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013280 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013281 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013282 PyObject *result;
13283 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013284 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013285 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013289 return NULL;
13290 }
13291
13292 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013293 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013294 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013295 slicelength == PyUnicode_GET_LENGTH(self)) {
13296 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013297 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013298 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013299 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013300 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013301 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013302 src_kind = PyUnicode_KIND(self);
13303 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013304 if (!PyUnicode_IS_ASCII(self)) {
13305 kind_limit = kind_maxchar_limit(src_kind);
13306 max_char = 0;
13307 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13308 ch = PyUnicode_READ(src_kind, src_data, cur);
13309 if (ch > max_char) {
13310 max_char = ch;
13311 if (max_char >= kind_limit)
13312 break;
13313 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013314 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013315 }
Victor Stinner55c99112011-10-13 01:17:06 +020013316 else
13317 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013318 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013319 if (result == NULL)
13320 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013321 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013322 dest_data = PyUnicode_DATA(result);
13323
13324 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013325 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13326 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013327 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013328 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013329 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013330 } else {
13331 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13332 return NULL;
13333 }
13334}
13335
13336static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013337 (lenfunc)unicode_length, /* mp_length */
13338 (binaryfunc)unicode_subscript, /* mp_subscript */
13339 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013340};
13341
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343/* Helpers for PyUnicode_Format() */
13344
Victor Stinnera47082312012-10-04 02:19:54 +020013345struct unicode_formatter_t {
13346 PyObject *args;
13347 int args_owned;
13348 Py_ssize_t arglen, argidx;
13349 PyObject *dict;
13350
13351 enum PyUnicode_Kind fmtkind;
13352 Py_ssize_t fmtcnt, fmtpos;
13353 void *fmtdata;
13354 PyObject *fmtstr;
13355
13356 _PyUnicodeWriter writer;
13357};
13358
13359struct unicode_format_arg_t {
13360 Py_UCS4 ch;
13361 int flags;
13362 Py_ssize_t width;
13363 int prec;
13364 int sign;
13365};
13366
Guido van Rossumd57fd912000-03-10 22:53:23 +000013367static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013368unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013369{
Victor Stinnera47082312012-10-04 02:19:54 +020013370 Py_ssize_t argidx = ctx->argidx;
13371
13372 if (argidx < ctx->arglen) {
13373 ctx->argidx++;
13374 if (ctx->arglen < 0)
13375 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 else
Victor Stinnera47082312012-10-04 02:19:54 +020013377 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013378 }
13379 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013381 return NULL;
13382}
13383
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013384/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013385
Victor Stinnera47082312012-10-04 02:19:54 +020013386/* Format a float into the writer if the writer is not NULL, or into *p_output
13387 otherwise.
13388
13389 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013390static int
Victor Stinnera47082312012-10-04 02:19:54 +020013391formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13392 PyObject **p_output,
13393 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013394{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013395 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013396 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013397 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013398 int prec;
13399 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013400
Guido van Rossumd57fd912000-03-10 22:53:23 +000013401 x = PyFloat_AsDouble(v);
13402 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013403 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013404
Victor Stinnera47082312012-10-04 02:19:54 +020013405 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013406 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013408
Victor Stinnera47082312012-10-04 02:19:54 +020013409 if (arg->flags & F_ALT)
13410 dtoa_flags = Py_DTSF_ALT;
13411 else
13412 dtoa_flags = 0;
13413 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013414 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013415 return -1;
13416 len = strlen(p);
13417 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013418 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13419 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013420 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013421 }
Victor Stinner184252a2012-06-16 02:57:41 +020013422 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013423 writer->pos += len;
13424 }
13425 else
13426 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013427 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013428 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013429}
13430
Victor Stinnerd0880d52012-04-27 23:40:13 +020013431/* formatlong() emulates the format codes d, u, o, x and X, and
13432 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13433 * Python's regular ints.
13434 * Return value: a new PyUnicodeObject*, or NULL if error.
13435 * The output string is of the form
13436 * "-"? ("0x" | "0X")? digit+
13437 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13438 * set in flags. The case of hex digits will be correct,
13439 * There will be at least prec digits, zero-filled on the left if
13440 * necessary to get that many.
13441 * val object to be converted
13442 * flags bitmask of format flags; only F_ALT is looked at
13443 * prec minimum number of digits; 0-fill on left if needed
13444 * type a character in [duoxX]; u acts the same as d
13445 *
13446 * CAUTION: o, x and X conversions on regular ints can never
13447 * produce a '-' sign, but can for Python's unbounded ints.
13448 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013449static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013450formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013451{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013452 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013453 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013454 Py_ssize_t i;
13455 int sign; /* 1 if '-', else 0 */
13456 int len; /* number of characters */
13457 Py_ssize_t llen;
13458 int numdigits; /* len == numnondigits + numdigits */
13459 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013460 int prec = arg->prec;
13461 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013462
Victor Stinnerd0880d52012-04-27 23:40:13 +020013463 /* Avoid exceeding SSIZE_T_MAX */
13464 if (prec > INT_MAX-3) {
13465 PyErr_SetString(PyExc_OverflowError,
13466 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013467 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013468 }
13469
13470 assert(PyLong_Check(val));
13471
13472 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013473 default:
13474 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013475 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013476 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013477 case 'u':
13478 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013479 if (PyBool_Check(val))
13480 result = PyNumber_ToBase(val, 10);
13481 else
13482 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013483 break;
13484 case 'o':
13485 numnondigits = 2;
13486 result = PyNumber_ToBase(val, 8);
13487 break;
13488 case 'x':
13489 case 'X':
13490 numnondigits = 2;
13491 result = PyNumber_ToBase(val, 16);
13492 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013493 }
13494 if (!result)
13495 return NULL;
13496
13497 assert(unicode_modifiable(result));
13498 assert(PyUnicode_IS_READY(result));
13499 assert(PyUnicode_IS_ASCII(result));
13500
13501 /* To modify the string in-place, there can only be one reference. */
13502 if (Py_REFCNT(result) != 1) {
13503 PyErr_BadInternalCall();
13504 return NULL;
13505 }
13506 buf = PyUnicode_DATA(result);
13507 llen = PyUnicode_GET_LENGTH(result);
13508 if (llen > INT_MAX) {
13509 PyErr_SetString(PyExc_ValueError,
13510 "string too large in _PyBytes_FormatLong");
13511 return NULL;
13512 }
13513 len = (int)llen;
13514 sign = buf[0] == '-';
13515 numnondigits += sign;
13516 numdigits = len - numnondigits;
13517 assert(numdigits > 0);
13518
13519 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013520 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013521 (type == 'o' || type == 'x' || type == 'X'))) {
13522 assert(buf[sign] == '0');
13523 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13524 buf[sign+1] == 'o');
13525 numnondigits -= 2;
13526 buf += 2;
13527 len -= 2;
13528 if (sign)
13529 buf[0] = '-';
13530 assert(len == numnondigits + numdigits);
13531 assert(numdigits > 0);
13532 }
13533
13534 /* Fill with leading zeroes to meet minimum width. */
13535 if (prec > numdigits) {
13536 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13537 numnondigits + prec);
13538 char *b1;
13539 if (!r1) {
13540 Py_DECREF(result);
13541 return NULL;
13542 }
13543 b1 = PyBytes_AS_STRING(r1);
13544 for (i = 0; i < numnondigits; ++i)
13545 *b1++ = *buf++;
13546 for (i = 0; i < prec - numdigits; i++)
13547 *b1++ = '0';
13548 for (i = 0; i < numdigits; i++)
13549 *b1++ = *buf++;
13550 *b1 = '\0';
13551 Py_DECREF(result);
13552 result = r1;
13553 buf = PyBytes_AS_STRING(result);
13554 len = numnondigits + prec;
13555 }
13556
13557 /* Fix up case for hex conversions. */
13558 if (type == 'X') {
13559 /* Need to convert all lower case letters to upper case.
13560 and need to convert 0x to 0X (and -0x to -0X). */
13561 for (i = 0; i < len; i++)
13562 if (buf[i] >= 'a' && buf[i] <= 'x')
13563 buf[i] -= 'a'-'A';
13564 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013565 if (!PyUnicode_Check(result)
13566 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013567 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013568 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013569 Py_DECREF(result);
13570 result = unicode;
13571 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013572 else if (len != PyUnicode_GET_LENGTH(result)) {
13573 if (PyUnicode_Resize(&result, len) < 0)
13574 Py_CLEAR(result);
13575 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013576 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013577}
13578
Victor Stinner621ef3d2012-10-02 00:33:47 +020013579/* Format an integer.
13580 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013581 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013582 * -1 and raise an exception on error */
13583static int
Victor Stinnera47082312012-10-04 02:19:54 +020013584mainformatlong(PyObject *v,
13585 struct unicode_format_arg_t *arg,
13586 PyObject **p_output,
13587 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013588{
13589 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013590 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013591
13592 if (!PyNumber_Check(v))
13593 goto wrongtype;
13594
13595 if (!PyLong_Check(v)) {
13596 iobj = PyNumber_Long(v);
13597 if (iobj == NULL) {
13598 if (PyErr_ExceptionMatches(PyExc_TypeError))
13599 goto wrongtype;
13600 return -1;
13601 }
13602 assert(PyLong_Check(iobj));
13603 }
13604 else {
13605 iobj = v;
13606 Py_INCREF(iobj);
13607 }
13608
13609 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013610 && arg->width == -1 && arg->prec == -1
13611 && !(arg->flags & (F_SIGN | F_BLANK))
13612 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013613 {
13614 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013615 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013616 int base;
13617
Victor Stinnera47082312012-10-04 02:19:54 +020013618 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013619 {
13620 default:
13621 assert(0 && "'type' not in [diuoxX]");
13622 case 'd':
13623 case 'i':
13624 case 'u':
13625 base = 10;
13626 break;
13627 case 'o':
13628 base = 8;
13629 break;
13630 case 'x':
13631 case 'X':
13632 base = 16;
13633 break;
13634 }
13635
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013636 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13637 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013638 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013639 }
13640 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013641 return 1;
13642 }
13643
Victor Stinnera47082312012-10-04 02:19:54 +020013644 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013645 Py_DECREF(iobj);
13646 if (res == NULL)
13647 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013648 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013649 return 0;
13650
13651wrongtype:
13652 PyErr_Format(PyExc_TypeError,
13653 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013654 "not %.200s",
13655 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013656 return -1;
13657}
13658
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013659static Py_UCS4
13660formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013661{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013662 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013663 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013664 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013665 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013667 goto onError;
13668 }
13669 else {
13670 /* Integer input truncated to a character */
13671 long x;
13672 x = PyLong_AsLong(v);
13673 if (x == -1 && PyErr_Occurred())
13674 goto onError;
13675
Victor Stinner8faf8212011-12-08 22:14:11 +010013676 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013677 PyErr_SetString(PyExc_OverflowError,
13678 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013679 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013680 }
13681
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013682 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013683 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013684
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013686 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013687 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013688 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013689}
13690
Victor Stinnera47082312012-10-04 02:19:54 +020013691/* Parse options of an argument: flags, width, precision.
13692 Handle also "%(name)" syntax.
13693
13694 Return 0 if the argument has been formatted into arg->str.
13695 Return 1 if the argument has been written into ctx->writer,
13696 Raise an exception and return -1 on error. */
13697static int
13698unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13699 struct unicode_format_arg_t *arg)
13700{
13701#define FORMAT_READ(ctx) \
13702 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13703
13704 PyObject *v;
13705
Victor Stinnera47082312012-10-04 02:19:54 +020013706 if (arg->ch == '(') {
13707 /* Get argument value from a dictionary. Example: "%(name)s". */
13708 Py_ssize_t keystart;
13709 Py_ssize_t keylen;
13710 PyObject *key;
13711 int pcount = 1;
13712
13713 if (ctx->dict == NULL) {
13714 PyErr_SetString(PyExc_TypeError,
13715 "format requires a mapping");
13716 return -1;
13717 }
13718 ++ctx->fmtpos;
13719 --ctx->fmtcnt;
13720 keystart = ctx->fmtpos;
13721 /* Skip over balanced parentheses */
13722 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13723 arg->ch = FORMAT_READ(ctx);
13724 if (arg->ch == ')')
13725 --pcount;
13726 else if (arg->ch == '(')
13727 ++pcount;
13728 ctx->fmtpos++;
13729 }
13730 keylen = ctx->fmtpos - keystart - 1;
13731 if (ctx->fmtcnt < 0 || pcount > 0) {
13732 PyErr_SetString(PyExc_ValueError,
13733 "incomplete format key");
13734 return -1;
13735 }
13736 key = PyUnicode_Substring(ctx->fmtstr,
13737 keystart, keystart + keylen);
13738 if (key == NULL)
13739 return -1;
13740 if (ctx->args_owned) {
13741 Py_DECREF(ctx->args);
13742 ctx->args_owned = 0;
13743 }
13744 ctx->args = PyObject_GetItem(ctx->dict, key);
13745 Py_DECREF(key);
13746 if (ctx->args == NULL)
13747 return -1;
13748 ctx->args_owned = 1;
13749 ctx->arglen = -1;
13750 ctx->argidx = -2;
13751 }
13752
13753 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020013754 while (--ctx->fmtcnt >= 0) {
13755 arg->ch = FORMAT_READ(ctx);
13756 ctx->fmtpos++;
13757 switch (arg->ch) {
13758 case '-': arg->flags |= F_LJUST; continue;
13759 case '+': arg->flags |= F_SIGN; continue;
13760 case ' ': arg->flags |= F_BLANK; continue;
13761 case '#': arg->flags |= F_ALT; continue;
13762 case '0': arg->flags |= F_ZERO; continue;
13763 }
13764 break;
13765 }
13766
13767 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020013768 if (arg->ch == '*') {
13769 v = unicode_format_getnextarg(ctx);
13770 if (v == NULL)
13771 return -1;
13772 if (!PyLong_Check(v)) {
13773 PyErr_SetString(PyExc_TypeError,
13774 "* wants int");
13775 return -1;
13776 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013777 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013778 if (arg->width == -1 && PyErr_Occurred())
13779 return -1;
13780 if (arg->width < 0) {
13781 arg->flags |= F_LJUST;
13782 arg->width = -arg->width;
13783 }
13784 if (--ctx->fmtcnt >= 0) {
13785 arg->ch = FORMAT_READ(ctx);
13786 ctx->fmtpos++;
13787 }
13788 }
13789 else if (arg->ch >= '0' && arg->ch <= '9') {
13790 arg->width = arg->ch - '0';
13791 while (--ctx->fmtcnt >= 0) {
13792 arg->ch = FORMAT_READ(ctx);
13793 ctx->fmtpos++;
13794 if (arg->ch < '0' || arg->ch > '9')
13795 break;
13796 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13797 mixing signed and unsigned comparison. Since arg->ch is between
13798 '0' and '9', casting to int is safe. */
13799 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13800 PyErr_SetString(PyExc_ValueError,
13801 "width too big");
13802 return -1;
13803 }
13804 arg->width = arg->width*10 + (arg->ch - '0');
13805 }
13806 }
13807
13808 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020013809 if (arg->ch == '.') {
13810 arg->prec = 0;
13811 if (--ctx->fmtcnt >= 0) {
13812 arg->ch = FORMAT_READ(ctx);
13813 ctx->fmtpos++;
13814 }
13815 if (arg->ch == '*') {
13816 v = unicode_format_getnextarg(ctx);
13817 if (v == NULL)
13818 return -1;
13819 if (!PyLong_Check(v)) {
13820 PyErr_SetString(PyExc_TypeError,
13821 "* wants int");
13822 return -1;
13823 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013824 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013825 if (arg->prec == -1 && PyErr_Occurred())
13826 return -1;
13827 if (arg->prec < 0)
13828 arg->prec = 0;
13829 if (--ctx->fmtcnt >= 0) {
13830 arg->ch = FORMAT_READ(ctx);
13831 ctx->fmtpos++;
13832 }
13833 }
13834 else if (arg->ch >= '0' && arg->ch <= '9') {
13835 arg->prec = arg->ch - '0';
13836 while (--ctx->fmtcnt >= 0) {
13837 arg->ch = FORMAT_READ(ctx);
13838 ctx->fmtpos++;
13839 if (arg->ch < '0' || arg->ch > '9')
13840 break;
13841 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13842 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013843 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013844 return -1;
13845 }
13846 arg->prec = arg->prec*10 + (arg->ch - '0');
13847 }
13848 }
13849 }
13850
13851 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13852 if (ctx->fmtcnt >= 0) {
13853 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13854 if (--ctx->fmtcnt >= 0) {
13855 arg->ch = FORMAT_READ(ctx);
13856 ctx->fmtpos++;
13857 }
13858 }
13859 }
13860 if (ctx->fmtcnt < 0) {
13861 PyErr_SetString(PyExc_ValueError,
13862 "incomplete format");
13863 return -1;
13864 }
13865 return 0;
13866
13867#undef FORMAT_READ
13868}
13869
13870/* Format one argument. Supported conversion specifiers:
13871
13872 - "s", "r", "a": any type
13873 - "i", "d", "u", "o", "x", "X": int
13874 - "e", "E", "f", "F", "g", "G": float
13875 - "c": int or str (1 character)
13876
Victor Stinner8dbd4212012-12-04 09:30:24 +010013877 When possible, the output is written directly into the Unicode writer
13878 (ctx->writer). A string is created when padding is required.
13879
Victor Stinnera47082312012-10-04 02:19:54 +020013880 Return 0 if the argument has been formatted into *p_str,
13881 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010013882 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020013883static int
13884unicode_format_arg_format(struct unicode_formatter_t *ctx,
13885 struct unicode_format_arg_t *arg,
13886 PyObject **p_str)
13887{
13888 PyObject *v;
13889 _PyUnicodeWriter *writer = &ctx->writer;
13890
13891 if (ctx->fmtcnt == 0)
13892 ctx->writer.overallocate = 0;
13893
13894 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013895 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020013896 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013897 return 1;
13898 }
13899
13900 v = unicode_format_getnextarg(ctx);
13901 if (v == NULL)
13902 return -1;
13903
Victor Stinnera47082312012-10-04 02:19:54 +020013904
13905 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020013906 case 's':
13907 case 'r':
13908 case 'a':
13909 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
13910 /* Fast path */
13911 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
13912 return -1;
13913 return 1;
13914 }
13915
13916 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
13917 *p_str = v;
13918 Py_INCREF(*p_str);
13919 }
13920 else {
13921 if (arg->ch == 's')
13922 *p_str = PyObject_Str(v);
13923 else if (arg->ch == 'r')
13924 *p_str = PyObject_Repr(v);
13925 else
13926 *p_str = PyObject_ASCII(v);
13927 }
13928 break;
13929
13930 case 'i':
13931 case 'd':
13932 case 'u':
13933 case 'o':
13934 case 'x':
13935 case 'X':
13936 {
13937 int ret = mainformatlong(v, arg, p_str, writer);
13938 if (ret != 0)
13939 return ret;
13940 arg->sign = 1;
13941 break;
13942 }
13943
13944 case 'e':
13945 case 'E':
13946 case 'f':
13947 case 'F':
13948 case 'g':
13949 case 'G':
13950 if (arg->width == -1 && arg->prec == -1
13951 && !(arg->flags & (F_SIGN | F_BLANK)))
13952 {
13953 /* Fast path */
13954 if (formatfloat(v, arg, NULL, writer) == -1)
13955 return -1;
13956 return 1;
13957 }
13958
13959 arg->sign = 1;
13960 if (formatfloat(v, arg, p_str, NULL) == -1)
13961 return -1;
13962 break;
13963
13964 case 'c':
13965 {
13966 Py_UCS4 ch = formatchar(v);
13967 if (ch == (Py_UCS4) -1)
13968 return -1;
13969 if (arg->width == -1 && arg->prec == -1) {
13970 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013971 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020013972 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013973 return 1;
13974 }
13975 *p_str = PyUnicode_FromOrdinal(ch);
13976 break;
13977 }
13978
13979 default:
13980 PyErr_Format(PyExc_ValueError,
13981 "unsupported format character '%c' (0x%x) "
13982 "at index %zd",
13983 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
13984 (int)arg->ch,
13985 ctx->fmtpos - 1);
13986 return -1;
13987 }
13988 if (*p_str == NULL)
13989 return -1;
13990 assert (PyUnicode_Check(*p_str));
13991 return 0;
13992}
13993
13994static int
13995unicode_format_arg_output(struct unicode_formatter_t *ctx,
13996 struct unicode_format_arg_t *arg,
13997 PyObject *str)
13998{
13999 Py_ssize_t len;
14000 enum PyUnicode_Kind kind;
14001 void *pbuf;
14002 Py_ssize_t pindex;
14003 Py_UCS4 signchar;
14004 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014005 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014006 Py_ssize_t sublen;
14007 _PyUnicodeWriter *writer = &ctx->writer;
14008 Py_UCS4 fill;
14009
14010 fill = ' ';
14011 if (arg->sign && arg->flags & F_ZERO)
14012 fill = '0';
14013
14014 if (PyUnicode_READY(str) == -1)
14015 return -1;
14016
14017 len = PyUnicode_GET_LENGTH(str);
14018 if ((arg->width == -1 || arg->width <= len)
14019 && (arg->prec == -1 || arg->prec >= len)
14020 && !(arg->flags & (F_SIGN | F_BLANK)))
14021 {
14022 /* Fast path */
14023 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14024 return -1;
14025 return 0;
14026 }
14027
14028 /* Truncate the string for "s", "r" and "a" formats
14029 if the precision is set */
14030 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14031 if (arg->prec >= 0 && len > arg->prec)
14032 len = arg->prec;
14033 }
14034
14035 /* Adjust sign and width */
14036 kind = PyUnicode_KIND(str);
14037 pbuf = PyUnicode_DATA(str);
14038 pindex = 0;
14039 signchar = '\0';
14040 if (arg->sign) {
14041 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14042 if (ch == '-' || ch == '+') {
14043 signchar = ch;
14044 len--;
14045 pindex++;
14046 }
14047 else if (arg->flags & F_SIGN)
14048 signchar = '+';
14049 else if (arg->flags & F_BLANK)
14050 signchar = ' ';
14051 else
14052 arg->sign = 0;
14053 }
14054 if (arg->width < len)
14055 arg->width = len;
14056
14057 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014058 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014059 if (!(arg->flags & F_LJUST)) {
14060 if (arg->sign) {
14061 if ((arg->width-1) > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014062 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014063 }
14064 else {
14065 if (arg->width > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014066 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014067 }
14068 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014069 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14070 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
14071 maxchar = MAX_MAXCHAR(maxchar, strmaxchar);
14072 }
14073
Victor Stinnera47082312012-10-04 02:19:54 +020014074 buflen = arg->width;
14075 if (arg->sign && len == arg->width)
14076 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014077 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014078 return -1;
14079
14080 /* Write the sign if needed */
14081 if (arg->sign) {
14082 if (fill != ' ') {
14083 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14084 writer->pos += 1;
14085 }
14086 if (arg->width > len)
14087 arg->width--;
14088 }
14089
14090 /* Write the numeric prefix for "x", "X" and "o" formats
14091 if the alternate form is used.
14092 For example, write "0x" for the "%#x" format. */
14093 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14094 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14095 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14096 if (fill != ' ') {
14097 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14098 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14099 writer->pos += 2;
14100 pindex += 2;
14101 }
14102 arg->width -= 2;
14103 if (arg->width < 0)
14104 arg->width = 0;
14105 len -= 2;
14106 }
14107
14108 /* Pad left with the fill character if needed */
14109 if (arg->width > len && !(arg->flags & F_LJUST)) {
14110 sublen = arg->width - len;
14111 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14112 writer->pos += sublen;
14113 arg->width = len;
14114 }
14115
14116 /* If padding with spaces: write sign if needed and/or numeric prefix if
14117 the alternate form is used */
14118 if (fill == ' ') {
14119 if (arg->sign) {
14120 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14121 writer->pos += 1;
14122 }
14123 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14124 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14125 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14126 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14127 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14128 writer->pos += 2;
14129 pindex += 2;
14130 }
14131 }
14132
14133 /* Write characters */
14134 if (len) {
14135 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14136 str, pindex, len);
14137 writer->pos += len;
14138 }
14139
14140 /* Pad right with the fill character if needed */
14141 if (arg->width > len) {
14142 sublen = arg->width - len;
14143 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14144 writer->pos += sublen;
14145 }
14146 return 0;
14147}
14148
14149/* Helper of PyUnicode_Format(): format one arg.
14150 Return 0 on success, raise an exception and return -1 on error. */
14151static int
14152unicode_format_arg(struct unicode_formatter_t *ctx)
14153{
14154 struct unicode_format_arg_t arg;
14155 PyObject *str;
14156 int ret;
14157
Victor Stinner8dbd4212012-12-04 09:30:24 +010014158 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14159 arg.flags = 0;
14160 arg.width = -1;
14161 arg.prec = -1;
14162 arg.sign = 0;
14163 str = NULL;
14164
Victor Stinnera47082312012-10-04 02:19:54 +020014165 ret = unicode_format_arg_parse(ctx, &arg);
14166 if (ret == -1)
14167 return -1;
14168
14169 ret = unicode_format_arg_format(ctx, &arg, &str);
14170 if (ret == -1)
14171 return -1;
14172
14173 if (ret != 1) {
14174 ret = unicode_format_arg_output(ctx, &arg, str);
14175 Py_DECREF(str);
14176 if (ret == -1)
14177 return -1;
14178 }
14179
14180 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14181 PyErr_SetString(PyExc_TypeError,
14182 "not all arguments converted during string formatting");
14183 return -1;
14184 }
14185 return 0;
14186}
14187
Alexander Belopolsky40018472011-02-26 01:02:56 +000014188PyObject *
14189PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014190{
Victor Stinnera47082312012-10-04 02:19:54 +020014191 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014192
Guido van Rossumd57fd912000-03-10 22:53:23 +000014193 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014194 PyErr_BadInternalCall();
14195 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014196 }
Victor Stinnera47082312012-10-04 02:19:54 +020014197
14198 ctx.fmtstr = PyUnicode_FromObject(format);
14199 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014200 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014201 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14202 Py_DECREF(ctx.fmtstr);
14203 return NULL;
14204 }
14205 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14206 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14207 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14208 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014209
Victor Stinner8f674cc2013-04-17 23:02:17 +020014210 _PyUnicodeWriter_Init(&ctx.writer);
14211 ctx.writer.min_length = ctx.fmtcnt + 100;
14212 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014213
Guido van Rossumd57fd912000-03-10 22:53:23 +000014214 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014215 ctx.arglen = PyTuple_Size(args);
14216 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014217 }
14218 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014219 ctx.arglen = -1;
14220 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014221 }
Victor Stinnera47082312012-10-04 02:19:54 +020014222 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014223 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014224 ctx.dict = args;
14225 else
14226 ctx.dict = NULL;
14227 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014228
Victor Stinnera47082312012-10-04 02:19:54 +020014229 while (--ctx.fmtcnt >= 0) {
14230 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014231 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014232
14233 nonfmtpos = ctx.fmtpos++;
14234 while (ctx.fmtcnt >= 0 &&
14235 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14236 ctx.fmtpos++;
14237 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014238 }
Victor Stinnera47082312012-10-04 02:19:54 +020014239 if (ctx.fmtcnt < 0) {
14240 ctx.fmtpos--;
14241 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014242 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014243
Victor Stinnercfc4c132013-04-03 01:48:39 +020014244 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14245 nonfmtpos, ctx.fmtpos) < 0)
14246 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014247 }
14248 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014249 ctx.fmtpos++;
14250 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014251 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014252 }
14253 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014254
Victor Stinnera47082312012-10-04 02:19:54 +020014255 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014256 PyErr_SetString(PyExc_TypeError,
14257 "not all arguments converted during string formatting");
14258 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014259 }
14260
Victor Stinnera47082312012-10-04 02:19:54 +020014261 if (ctx.args_owned) {
14262 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014263 }
Victor Stinnera47082312012-10-04 02:19:54 +020014264 Py_DECREF(ctx.fmtstr);
14265 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014266
Benjamin Peterson29060642009-01-31 22:14:21 +000014267 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014268 Py_DECREF(ctx.fmtstr);
14269 _PyUnicodeWriter_Dealloc(&ctx.writer);
14270 if (ctx.args_owned) {
14271 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014272 }
14273 return NULL;
14274}
14275
Jeremy Hylton938ace62002-07-17 16:30:39 +000014276static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014277unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14278
Tim Peters6d6c1a32001-08-02 04:15:00 +000014279static PyObject *
14280unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14281{
Benjamin Peterson29060642009-01-31 22:14:21 +000014282 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014283 static char *kwlist[] = {"object", "encoding", "errors", 0};
14284 char *encoding = NULL;
14285 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014286
Benjamin Peterson14339b62009-01-31 16:36:08 +000014287 if (type != &PyUnicode_Type)
14288 return unicode_subtype_new(type, args, kwds);
14289 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014290 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014291 return NULL;
14292 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014293 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014294 if (encoding == NULL && errors == NULL)
14295 return PyObject_Str(x);
14296 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014297 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014298}
14299
Guido van Rossume023fe02001-08-30 03:12:59 +000014300static PyObject *
14301unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14302{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014303 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014304 Py_ssize_t length, char_size;
14305 int share_wstr, share_utf8;
14306 unsigned int kind;
14307 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014308
Benjamin Peterson14339b62009-01-31 16:36:08 +000014309 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014310
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014311 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014312 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014314 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014315 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014316 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014317 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014318 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014319
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014320 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014321 if (self == NULL) {
14322 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014323 return NULL;
14324 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014325 kind = PyUnicode_KIND(unicode);
14326 length = PyUnicode_GET_LENGTH(unicode);
14327
14328 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014329#ifdef Py_DEBUG
14330 _PyUnicode_HASH(self) = -1;
14331#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014332 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014333#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014334 _PyUnicode_STATE(self).interned = 0;
14335 _PyUnicode_STATE(self).kind = kind;
14336 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014337 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014338 _PyUnicode_STATE(self).ready = 1;
14339 _PyUnicode_WSTR(self) = NULL;
14340 _PyUnicode_UTF8_LENGTH(self) = 0;
14341 _PyUnicode_UTF8(self) = NULL;
14342 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014343 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014344
14345 share_utf8 = 0;
14346 share_wstr = 0;
14347 if (kind == PyUnicode_1BYTE_KIND) {
14348 char_size = 1;
14349 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14350 share_utf8 = 1;
14351 }
14352 else if (kind == PyUnicode_2BYTE_KIND) {
14353 char_size = 2;
14354 if (sizeof(wchar_t) == 2)
14355 share_wstr = 1;
14356 }
14357 else {
14358 assert(kind == PyUnicode_4BYTE_KIND);
14359 char_size = 4;
14360 if (sizeof(wchar_t) == 4)
14361 share_wstr = 1;
14362 }
14363
14364 /* Ensure we won't overflow the length. */
14365 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14366 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014367 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014368 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014369 data = PyObject_MALLOC((length + 1) * char_size);
14370 if (data == NULL) {
14371 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014372 goto onError;
14373 }
14374
Victor Stinnerc3c74152011-10-02 20:39:55 +020014375 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014376 if (share_utf8) {
14377 _PyUnicode_UTF8_LENGTH(self) = length;
14378 _PyUnicode_UTF8(self) = data;
14379 }
14380 if (share_wstr) {
14381 _PyUnicode_WSTR_LENGTH(self) = length;
14382 _PyUnicode_WSTR(self) = (wchar_t *)data;
14383 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014384
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014385 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014386 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014387 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014388#ifdef Py_DEBUG
14389 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14390#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014391 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014392 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014393
14394onError:
14395 Py_DECREF(unicode);
14396 Py_DECREF(self);
14397 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014398}
14399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014400PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014401"str(object='') -> str\n\
14402str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014403\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014404Create a new string object from the given object. If encoding or\n\
14405errors is specified, then the object must expose a data buffer\n\
14406that will be decoded using the given encoding and error handler.\n\
14407Otherwise, returns the result of object.__str__() (if defined)\n\
14408or repr(object).\n\
14409encoding defaults to sys.getdefaultencoding().\n\
14410errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014411
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014412static PyObject *unicode_iter(PyObject *seq);
14413
Guido van Rossumd57fd912000-03-10 22:53:23 +000014414PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014415 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014416 "str", /* tp_name */
14417 sizeof(PyUnicodeObject), /* tp_size */
14418 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014419 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014420 (destructor)unicode_dealloc, /* tp_dealloc */
14421 0, /* tp_print */
14422 0, /* tp_getattr */
14423 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014424 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014425 unicode_repr, /* tp_repr */
14426 &unicode_as_number, /* tp_as_number */
14427 &unicode_as_sequence, /* tp_as_sequence */
14428 &unicode_as_mapping, /* tp_as_mapping */
14429 (hashfunc) unicode_hash, /* tp_hash*/
14430 0, /* tp_call*/
14431 (reprfunc) unicode_str, /* tp_str */
14432 PyObject_GenericGetAttr, /* tp_getattro */
14433 0, /* tp_setattro */
14434 0, /* tp_as_buffer */
14435 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014436 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014437 unicode_doc, /* tp_doc */
14438 0, /* tp_traverse */
14439 0, /* tp_clear */
14440 PyUnicode_RichCompare, /* tp_richcompare */
14441 0, /* tp_weaklistoffset */
14442 unicode_iter, /* tp_iter */
14443 0, /* tp_iternext */
14444 unicode_methods, /* tp_methods */
14445 0, /* tp_members */
14446 0, /* tp_getset */
14447 &PyBaseObject_Type, /* tp_base */
14448 0, /* tp_dict */
14449 0, /* tp_descr_get */
14450 0, /* tp_descr_set */
14451 0, /* tp_dictoffset */
14452 0, /* tp_init */
14453 0, /* tp_alloc */
14454 unicode_new, /* tp_new */
14455 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014456};
14457
14458/* Initialize the Unicode implementation */
14459
Victor Stinner3a50e702011-10-18 21:21:00 +020014460int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014461{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014462 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014463 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014464 0x000A, /* LINE FEED */
14465 0x000D, /* CARRIAGE RETURN */
14466 0x001C, /* FILE SEPARATOR */
14467 0x001D, /* GROUP SEPARATOR */
14468 0x001E, /* RECORD SEPARATOR */
14469 0x0085, /* NEXT LINE */
14470 0x2028, /* LINE SEPARATOR */
14471 0x2029, /* PARAGRAPH SEPARATOR */
14472 };
14473
Fred Drakee4315f52000-05-09 19:53:39 +000014474 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014475 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014476 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014477 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014478 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014479
Guido van Rossumcacfc072002-05-24 19:01:59 +000014480 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014481 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014482
14483 /* initialize the linebreak bloom filter */
14484 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014485 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014486 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014487
14488 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014489
Benjamin Petersonc4311282012-10-30 23:21:10 -040014490 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14491 Py_FatalError("Can't initialize field name iterator type");
14492
14493 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14494 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014495
Victor Stinner3a50e702011-10-18 21:21:00 +020014496#ifdef HAVE_MBCS
14497 winver.dwOSVersionInfoSize = sizeof(winver);
14498 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14499 PyErr_SetFromWindowsErr(0);
14500 return -1;
14501 }
14502#endif
14503 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014504}
14505
14506/* Finalize the Unicode implementation */
14507
Christian Heimesa156e092008-02-16 07:38:31 +000014508int
14509PyUnicode_ClearFreeList(void)
14510{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014511 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014512}
14513
Guido van Rossumd57fd912000-03-10 22:53:23 +000014514void
Thomas Wouters78890102000-07-22 19:25:51 +000014515_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014516{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014517 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014518
Serhiy Storchaka05997252013-01-26 12:14:02 +020014519 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014520
Serhiy Storchaka05997252013-01-26 12:14:02 +020014521 for (i = 0; i < 256; i++)
14522 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014523 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014524 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014525}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014526
Walter Dörwald16807132007-05-25 13:52:07 +000014527void
14528PyUnicode_InternInPlace(PyObject **p)
14529{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014530 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014531 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014532#ifdef Py_DEBUG
14533 assert(s != NULL);
14534 assert(_PyUnicode_CHECK(s));
14535#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014536 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014537 return;
14538#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014539 /* If it's a subclass, we don't really know what putting
14540 it in the interned dict might do. */
14541 if (!PyUnicode_CheckExact(s))
14542 return;
14543 if (PyUnicode_CHECK_INTERNED(s))
14544 return;
14545 if (interned == NULL) {
14546 interned = PyDict_New();
14547 if (interned == NULL) {
14548 PyErr_Clear(); /* Don't leave an exception */
14549 return;
14550 }
14551 }
14552 /* It might be that the GetItem call fails even
14553 though the key is present in the dictionary,
14554 namely when this happens during a stack overflow. */
14555 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014556 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014557 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014558
Victor Stinnerf0335102013-04-14 19:13:03 +020014559 if (t) {
14560 Py_INCREF(t);
14561 Py_DECREF(*p);
14562 *p = t;
14563 return;
14564 }
Walter Dörwald16807132007-05-25 13:52:07 +000014565
Benjamin Peterson14339b62009-01-31 16:36:08 +000014566 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014567 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014568 PyErr_Clear();
14569 PyThreadState_GET()->recursion_critical = 0;
14570 return;
14571 }
14572 PyThreadState_GET()->recursion_critical = 0;
14573 /* The two references in interned are not counted by refcnt.
14574 The deallocator will take care of this */
14575 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014576 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014577}
14578
14579void
14580PyUnicode_InternImmortal(PyObject **p)
14581{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014582 PyUnicode_InternInPlace(p);
14583 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014584 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014585 Py_INCREF(*p);
14586 }
Walter Dörwald16807132007-05-25 13:52:07 +000014587}
14588
14589PyObject *
14590PyUnicode_InternFromString(const char *cp)
14591{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014592 PyObject *s = PyUnicode_FromString(cp);
14593 if (s == NULL)
14594 return NULL;
14595 PyUnicode_InternInPlace(&s);
14596 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014597}
14598
Alexander Belopolsky40018472011-02-26 01:02:56 +000014599void
14600_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014601{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014602 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014603 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014604 Py_ssize_t i, n;
14605 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014606
Benjamin Peterson14339b62009-01-31 16:36:08 +000014607 if (interned == NULL || !PyDict_Check(interned))
14608 return;
14609 keys = PyDict_Keys(interned);
14610 if (keys == NULL || !PyList_Check(keys)) {
14611 PyErr_Clear();
14612 return;
14613 }
Walter Dörwald16807132007-05-25 13:52:07 +000014614
Benjamin Peterson14339b62009-01-31 16:36:08 +000014615 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14616 detector, interned unicode strings are not forcibly deallocated;
14617 rather, we give them their stolen references back, and then clear
14618 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014619
Benjamin Peterson14339b62009-01-31 16:36:08 +000014620 n = PyList_GET_SIZE(keys);
14621 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014622 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014623 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014624 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014625 if (PyUnicode_READY(s) == -1) {
14626 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014627 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014629 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014630 case SSTATE_NOT_INTERNED:
14631 /* XXX Shouldn't happen */
14632 break;
14633 case SSTATE_INTERNED_IMMORTAL:
14634 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014635 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014636 break;
14637 case SSTATE_INTERNED_MORTAL:
14638 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014639 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014640 break;
14641 default:
14642 Py_FatalError("Inconsistent interned string state.");
14643 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014644 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014645 }
14646 fprintf(stderr, "total size of all interned strings: "
14647 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14648 "mortal/immortal\n", mortal_size, immortal_size);
14649 Py_DECREF(keys);
14650 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014651 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014652}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014653
14654
14655/********************* Unicode Iterator **************************/
14656
14657typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014658 PyObject_HEAD
14659 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014660 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014661} unicodeiterobject;
14662
14663static void
14664unicodeiter_dealloc(unicodeiterobject *it)
14665{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014666 _PyObject_GC_UNTRACK(it);
14667 Py_XDECREF(it->it_seq);
14668 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014669}
14670
14671static int
14672unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14673{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014674 Py_VISIT(it->it_seq);
14675 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014676}
14677
14678static PyObject *
14679unicodeiter_next(unicodeiterobject *it)
14680{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014681 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014682
Benjamin Peterson14339b62009-01-31 16:36:08 +000014683 assert(it != NULL);
14684 seq = it->it_seq;
14685 if (seq == NULL)
14686 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014687 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014689 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14690 int kind = PyUnicode_KIND(seq);
14691 void *data = PyUnicode_DATA(seq);
14692 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14693 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014694 if (item != NULL)
14695 ++it->it_index;
14696 return item;
14697 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014698
Benjamin Peterson14339b62009-01-31 16:36:08 +000014699 Py_DECREF(seq);
14700 it->it_seq = NULL;
14701 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014702}
14703
14704static PyObject *
14705unicodeiter_len(unicodeiterobject *it)
14706{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014707 Py_ssize_t len = 0;
14708 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014709 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014710 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014711}
14712
14713PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14714
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014715static PyObject *
14716unicodeiter_reduce(unicodeiterobject *it)
14717{
14718 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014719 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014720 it->it_seq, it->it_index);
14721 } else {
14722 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14723 if (u == NULL)
14724 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014725 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014726 }
14727}
14728
14729PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14730
14731static PyObject *
14732unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14733{
14734 Py_ssize_t index = PyLong_AsSsize_t(state);
14735 if (index == -1 && PyErr_Occurred())
14736 return NULL;
14737 if (index < 0)
14738 index = 0;
14739 it->it_index = index;
14740 Py_RETURN_NONE;
14741}
14742
14743PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14744
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014745static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014746 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014747 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014748 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14749 reduce_doc},
14750 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14751 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014752 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014753};
14754
14755PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014756 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14757 "str_iterator", /* tp_name */
14758 sizeof(unicodeiterobject), /* tp_basicsize */
14759 0, /* tp_itemsize */
14760 /* methods */
14761 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14762 0, /* tp_print */
14763 0, /* tp_getattr */
14764 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014765 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014766 0, /* tp_repr */
14767 0, /* tp_as_number */
14768 0, /* tp_as_sequence */
14769 0, /* tp_as_mapping */
14770 0, /* tp_hash */
14771 0, /* tp_call */
14772 0, /* tp_str */
14773 PyObject_GenericGetAttr, /* tp_getattro */
14774 0, /* tp_setattro */
14775 0, /* tp_as_buffer */
14776 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14777 0, /* tp_doc */
14778 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14779 0, /* tp_clear */
14780 0, /* tp_richcompare */
14781 0, /* tp_weaklistoffset */
14782 PyObject_SelfIter, /* tp_iter */
14783 (iternextfunc)unicodeiter_next, /* tp_iternext */
14784 unicodeiter_methods, /* tp_methods */
14785 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014786};
14787
14788static PyObject *
14789unicode_iter(PyObject *seq)
14790{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014791 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014792
Benjamin Peterson14339b62009-01-31 16:36:08 +000014793 if (!PyUnicode_Check(seq)) {
14794 PyErr_BadInternalCall();
14795 return NULL;
14796 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014797 if (PyUnicode_READY(seq) == -1)
14798 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014799 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14800 if (it == NULL)
14801 return NULL;
14802 it->it_index = 0;
14803 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014804 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014805 _PyObject_GC_TRACK(it);
14806 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014807}
14808
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014809
14810size_t
14811Py_UNICODE_strlen(const Py_UNICODE *u)
14812{
14813 int res = 0;
14814 while(*u++)
14815 res++;
14816 return res;
14817}
14818
14819Py_UNICODE*
14820Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14821{
14822 Py_UNICODE *u = s1;
14823 while ((*u++ = *s2++));
14824 return s1;
14825}
14826
14827Py_UNICODE*
14828Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14829{
14830 Py_UNICODE *u = s1;
14831 while ((*u++ = *s2++))
14832 if (n-- == 0)
14833 break;
14834 return s1;
14835}
14836
14837Py_UNICODE*
14838Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14839{
14840 Py_UNICODE *u1 = s1;
14841 u1 += Py_UNICODE_strlen(u1);
14842 Py_UNICODE_strcpy(u1, s2);
14843 return s1;
14844}
14845
14846int
14847Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14848{
14849 while (*s1 && *s2 && *s1 == *s2)
14850 s1++, s2++;
14851 if (*s1 && *s2)
14852 return (*s1 < *s2) ? -1 : +1;
14853 if (*s1)
14854 return 1;
14855 if (*s2)
14856 return -1;
14857 return 0;
14858}
14859
14860int
14861Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14862{
14863 register Py_UNICODE u1, u2;
14864 for (; n != 0; n--) {
14865 u1 = *s1;
14866 u2 = *s2;
14867 if (u1 != u2)
14868 return (u1 < u2) ? -1 : +1;
14869 if (u1 == '\0')
14870 return 0;
14871 s1++;
14872 s2++;
14873 }
14874 return 0;
14875}
14876
14877Py_UNICODE*
14878Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14879{
14880 const Py_UNICODE *p;
14881 for (p = s; *p; p++)
14882 if (*p == c)
14883 return (Py_UNICODE*)p;
14884 return NULL;
14885}
14886
14887Py_UNICODE*
14888Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14889{
14890 const Py_UNICODE *p;
14891 p = s + Py_UNICODE_strlen(s);
14892 while (p != s) {
14893 p--;
14894 if (*p == c)
14895 return (Py_UNICODE*)p;
14896 }
14897 return NULL;
14898}
Victor Stinner331ea922010-08-10 16:37:20 +000014899
Victor Stinner71133ff2010-09-01 23:43:53 +000014900Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014901PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014902{
Victor Stinner577db2c2011-10-11 22:12:48 +020014903 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014904 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014906 if (!PyUnicode_Check(unicode)) {
14907 PyErr_BadArgument();
14908 return NULL;
14909 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014910 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014911 if (u == NULL)
14912 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014913 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014914 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014915 PyErr_NoMemory();
14916 return NULL;
14917 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014918 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014919 size *= sizeof(Py_UNICODE);
14920 copy = PyMem_Malloc(size);
14921 if (copy == NULL) {
14922 PyErr_NoMemory();
14923 return NULL;
14924 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014925 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014926 return copy;
14927}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014928
Georg Brandl66c221e2010-10-14 07:04:07 +000014929/* A _string module, to export formatter_parser and formatter_field_name_split
14930 to the string.Formatter class implemented in Python. */
14931
14932static PyMethodDef _string_methods[] = {
14933 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14934 METH_O, PyDoc_STR("split the argument as a field name")},
14935 {"formatter_parser", (PyCFunction) formatter_parser,
14936 METH_O, PyDoc_STR("parse the argument as a format string")},
14937 {NULL, NULL}
14938};
14939
14940static struct PyModuleDef _string_module = {
14941 PyModuleDef_HEAD_INIT,
14942 "_string",
14943 PyDoc_STR("string helper module"),
14944 0,
14945 _string_methods,
14946 NULL,
14947 NULL,
14948 NULL,
14949 NULL
14950};
14951
14952PyMODINIT_FUNC
14953PyInit__string(void)
14954{
14955 return PyModule_Create(&_string_module);
14956}
14957
14958
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014959#ifdef __cplusplus
14960}
14961#endif