blob: e348a4658590cbf1ee9273416871fc6457b99d7a [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
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200199/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000202/* Single character Unicode strings in the Latin-1 range are being
203 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200204static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Christian Heimes190d79e2008-01-30 11:58:22 +0000206/* Fast detection of the most frequent whitespace characters */
207const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000208 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000209/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000210/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000C: * FORM FEED */
213/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000214 0, 1, 1, 1, 1, 1, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000216/* case 0x001C: * FILE SEPARATOR */
217/* case 0x001D: * GROUP SEPARATOR */
218/* case 0x001E: * RECORD SEPARATOR */
219/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000220 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 1, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000226
Benjamin Peterson14339b62009-01-31 16:36:08 +0000227 0, 0, 0, 0, 0, 0, 0, 0,
228 0, 0, 0, 0, 0, 0, 0, 0,
229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
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
Christian Heimes190d79e2008-01-30 11:58:22 +0000235};
236
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200237/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100240static int unicode_modifiable(PyObject *unicode);
241
Victor Stinnerfe226c02011-10-03 03:52:20 +0200242
Alexander Belopolsky40018472011-02-26 01:02:56 +0000243static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100244_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200245static PyObject *
246_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
247static PyObject *
248_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
249
250static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000251unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100253 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
255
Alexander Belopolsky40018472011-02-26 01:02:56 +0000256static void
257raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300258 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100259 PyObject *unicode,
260 Py_ssize_t startpos, Py_ssize_t endpos,
261 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000262
Christian Heimes190d79e2008-01-30 11:58:22 +0000263/* Same for linebreaks */
264static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000265 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000266/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000267/* 0x000B, * LINE TABULATION */
268/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000270 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000271 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000272/* 0x001C, * FILE SEPARATOR */
273/* 0x001D, * GROUP SEPARATOR */
274/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 1, 1, 1, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000280
Benjamin Peterson14339b62009-01-31 16:36:08 +0000281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
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
Christian Heimes190d79e2008-01-30 11:58:22 +0000289};
290
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300291/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
292 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000294PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000296#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000298#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 /* This is actually an illegal character, so it should
300 not be passed to unichr. */
301 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#endif
303}
304
Victor Stinner910337b2011-10-03 03:20:16 +0200305#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200306int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100307_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200308{
309 PyASCIIObject *ascii;
310 unsigned int kind;
311
312 assert(PyUnicode_Check(op));
313
314 ascii = (PyASCIIObject *)op;
315 kind = ascii->state.kind;
316
Victor Stinnera3b334d2011-10-03 13:53:37 +0200317 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200318 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200319 assert(ascii->state.ready == 1);
320 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200322 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200323 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200324
Victor Stinnera41463c2011-10-04 01:05:08 +0200325 if (ascii->state.compact == 1) {
326 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200327 assert(kind == PyUnicode_1BYTE_KIND
328 || kind == PyUnicode_2BYTE_KIND
329 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 }
334 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200335 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
336
337 data = unicode->data.any;
338 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100339 assert(ascii->length == 0);
340 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200341 assert(ascii->state.compact == 0);
342 assert(ascii->state.ascii == 0);
343 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100344 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200345 assert(ascii->wstr != NULL);
346 assert(data == NULL);
347 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200348 }
349 else {
350 assert(kind == PyUnicode_1BYTE_KIND
351 || kind == PyUnicode_2BYTE_KIND
352 || kind == PyUnicode_4BYTE_KIND);
353 assert(ascii->state.compact == 0);
354 assert(ascii->state.ready == 1);
355 assert(data != NULL);
356 if (ascii->state.ascii) {
357 assert (compact->utf8 == data);
358 assert (compact->utf8_length == ascii->length);
359 }
360 else
361 assert (compact->utf8 != data);
362 }
363 }
364 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200365 if (
366#if SIZEOF_WCHAR_T == 2
367 kind == PyUnicode_2BYTE_KIND
368#else
369 kind == PyUnicode_4BYTE_KIND
370#endif
371 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200372 {
373 assert(ascii->wstr == data);
374 assert(compact->wstr_length == ascii->length);
375 } else
376 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200377 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200378
379 if (compact->utf8 == NULL)
380 assert(compact->utf8_length == 0);
381 if (ascii->wstr == NULL)
382 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200383 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200384 /* check that the best kind is used */
385 if (check_content && kind != PyUnicode_WCHAR_KIND)
386 {
387 Py_ssize_t i;
388 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200389 void *data;
390 Py_UCS4 ch;
391
392 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200393 for (i=0; i < ascii->length; i++)
394 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200395 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200396 if (ch > maxchar)
397 maxchar = ch;
398 }
399 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100400 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100402 assert(maxchar <= 255);
403 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 else
405 assert(maxchar < 128);
406 }
Victor Stinner77faf692011-11-20 18:56:05 +0100407 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200408 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100409 assert(maxchar <= 0xFFFF);
410 }
411 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200412 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100413 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100414 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200415 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200416 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400417 return 1;
418}
Victor Stinner910337b2011-10-03 03:20:16 +0200419#endif
420
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100421static PyObject*
422unicode_result_wchar(PyObject *unicode)
423{
424#ifndef Py_DEBUG
425 Py_ssize_t len;
426
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100427 len = _PyUnicode_WSTR_LENGTH(unicode);
428 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200430 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 }
432
433 if (len == 1) {
434 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100435 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100436 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
437 Py_DECREF(unicode);
438 return latin1_char;
439 }
440 }
441
442 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200443 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100444 return NULL;
445 }
446#else
Victor Stinneraa771272012-10-04 02:32:58 +0200447 assert(Py_REFCNT(unicode) == 1);
448
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100449 /* don't make the result ready in debug mode to ensure that the caller
450 makes the string ready before using it */
451 assert(_PyUnicode_CheckConsistency(unicode, 1));
452#endif
453 return unicode;
454}
455
456static PyObject*
457unicode_result_ready(PyObject *unicode)
458{
459 Py_ssize_t length;
460
461 length = PyUnicode_GET_LENGTH(unicode);
462 if (length == 0) {
463 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100464 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200465 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 }
467 return unicode_empty;
468 }
469
470 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200471 void *data = PyUnicode_DATA(unicode);
472 int kind = PyUnicode_KIND(unicode);
473 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100474 if (ch < 256) {
475 PyObject *latin1_char = unicode_latin1[ch];
476 if (latin1_char != NULL) {
477 if (unicode != latin1_char) {
478 Py_INCREF(latin1_char);
479 Py_DECREF(unicode);
480 }
481 return latin1_char;
482 }
483 else {
484 assert(_PyUnicode_CheckConsistency(unicode, 1));
485 Py_INCREF(unicode);
486 unicode_latin1[ch] = unicode;
487 return unicode;
488 }
489 }
490 }
491
492 assert(_PyUnicode_CheckConsistency(unicode, 1));
493 return unicode;
494}
495
496static PyObject*
497unicode_result(PyObject *unicode)
498{
499 assert(_PyUnicode_CHECK(unicode));
500 if (PyUnicode_IS_READY(unicode))
501 return unicode_result_ready(unicode);
502 else
503 return unicode_result_wchar(unicode);
504}
505
Victor Stinnerc4b49542011-12-11 22:44:26 +0100506static PyObject*
507unicode_result_unchanged(PyObject *unicode)
508{
509 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500510 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100511 return NULL;
512 Py_INCREF(unicode);
513 return unicode;
514 }
515 else
516 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100517 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100518}
519
Victor Stinner3a50e702011-10-18 21:21:00 +0200520#ifdef HAVE_MBCS
521static OSVERSIONINFOEX winver;
522#endif
523
Thomas Wouters477c8d52006-05-27 19:21:47 +0000524/* --- Bloom Filters ----------------------------------------------------- */
525
526/* stuff to implement simple "bloom filters" for Unicode characters.
527 to keep things simple, we use a single bitmask, using the least 5
528 bits from each unicode characters as the bit index. */
529
530/* the linebreak mask is set up by Unicode_Init below */
531
Antoine Pitrouf068f942010-01-13 14:19:12 +0000532#if LONG_BIT >= 128
533#define BLOOM_WIDTH 128
534#elif LONG_BIT >= 64
535#define BLOOM_WIDTH 64
536#elif LONG_BIT >= 32
537#define BLOOM_WIDTH 32
538#else
539#error "LONG_BIT is smaller than 32"
540#endif
541
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542#define BLOOM_MASK unsigned long
543
Serhiy Storchaka05997252013-01-26 12:14:02 +0200544static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
Antoine Pitrouf068f942010-01-13 14:19:12 +0000546#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Benjamin Peterson29060642009-01-31 22:14:21 +0000548#define BLOOM_LINEBREAK(ch) \
549 ((ch) < 128U ? ascii_linebreak[(ch)] : \
550 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
Alexander Belopolsky40018472011-02-26 01:02:56 +0000552Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200553make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554{
Victor Stinnera85af502013-04-09 21:53:54 +0200555#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
556 do { \
557 TYPE *data = (TYPE *)PTR; \
558 TYPE *end = data + LEN; \
559 Py_UCS4 ch; \
560 for (; data != end; data++) { \
561 ch = *data; \
562 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
563 } \
564 break; \
565 } while (0)
566
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 /* calculate simple bloom-style bitmask for a given unicode string */
568
Antoine Pitrouf068f942010-01-13 14:19:12 +0000569 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570
571 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200572 switch (kind) {
573 case PyUnicode_1BYTE_KIND:
574 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
575 break;
576 case PyUnicode_2BYTE_KIND:
577 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
578 break;
579 case PyUnicode_4BYTE_KIND:
580 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
581 break;
582 default:
583 assert(0);
584 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200586
587#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200590/* Compilation of templated routines */
591
592#include "stringlib/asciilib.h"
593#include "stringlib/fastsearch.h"
594#include "stringlib/partition.h"
595#include "stringlib/split.h"
596#include "stringlib/count.h"
597#include "stringlib/find.h"
598#include "stringlib/find_max_char.h"
599#include "stringlib/localeutil.h"
600#include "stringlib/undef.h"
601
602#include "stringlib/ucs1lib.h"
603#include "stringlib/fastsearch.h"
604#include "stringlib/partition.h"
605#include "stringlib/split.h"
606#include "stringlib/count.h"
607#include "stringlib/find.h"
608#include "stringlib/find_max_char.h"
609#include "stringlib/localeutil.h"
610#include "stringlib/undef.h"
611
612#include "stringlib/ucs2lib.h"
613#include "stringlib/fastsearch.h"
614#include "stringlib/partition.h"
615#include "stringlib/split.h"
616#include "stringlib/count.h"
617#include "stringlib/find.h"
618#include "stringlib/find_max_char.h"
619#include "stringlib/localeutil.h"
620#include "stringlib/undef.h"
621
622#include "stringlib/ucs4lib.h"
623#include "stringlib/fastsearch.h"
624#include "stringlib/partition.h"
625#include "stringlib/split.h"
626#include "stringlib/count.h"
627#include "stringlib/find.h"
628#include "stringlib/find_max_char.h"
629#include "stringlib/localeutil.h"
630#include "stringlib/undef.h"
631
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200632#include "stringlib/unicodedefs.h"
633#include "stringlib/fastsearch.h"
634#include "stringlib/count.h"
635#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100636#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637
Guido van Rossumd57fd912000-03-10 22:53:23 +0000638/* --- Unicode Object ----------------------------------------------------- */
639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200640static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200641fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200642
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200643Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
644 Py_ssize_t size, Py_UCS4 ch,
645 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200646{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200647 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
648
649 switch (kind) {
650 case PyUnicode_1BYTE_KIND:
651 {
652 Py_UCS1 ch1 = (Py_UCS1) ch;
653 if (ch1 == ch)
654 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
655 else
656 return -1;
657 }
658 case PyUnicode_2BYTE_KIND:
659 {
660 Py_UCS2 ch2 = (Py_UCS2) ch;
661 if (ch2 == ch)
662 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
663 else
664 return -1;
665 }
666 case PyUnicode_4BYTE_KIND:
667 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
668 default:
669 assert(0);
670 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672}
673
Victor Stinnerafffce42012-10-03 23:03:17 +0200674#ifdef Py_DEBUG
675/* Fill the data of an Unicode string with invalid characters to detect bugs
676 earlier.
677
678 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
679 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
680 invalid character in Unicode 6.0. */
681static void
682unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
683{
684 int kind = PyUnicode_KIND(unicode);
685 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
686 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
687 if (length <= old_length)
688 return;
689 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
690}
691#endif
692
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693static PyObject*
694resize_compact(PyObject *unicode, Py_ssize_t length)
695{
696 Py_ssize_t char_size;
697 Py_ssize_t struct_size;
698 Py_ssize_t new_size;
699 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100700 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200701#ifdef Py_DEBUG
702 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
703#endif
704
Victor Stinner79891572012-05-03 13:43:07 +0200705 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200706 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100707 assert(PyUnicode_IS_COMPACT(unicode));
708
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200709 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100710 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 struct_size = sizeof(PyASCIIObject);
712 else
713 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200714 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
717 PyErr_NoMemory();
718 return NULL;
719 }
720 new_size = (struct_size + (length + 1) * char_size);
721
Victor Stinner84def372011-12-11 20:04:56 +0100722 _Py_DEC_REFTOTAL;
723 _Py_ForgetReference(unicode);
724
725 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
726 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100727 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200728 PyErr_NoMemory();
729 return NULL;
730 }
Victor Stinner84def372011-12-11 20:04:56 +0100731 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100733
Victor Stinnerfe226c02011-10-03 03:52:20 +0200734 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200735 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100737 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200738 _PyUnicode_WSTR_LENGTH(unicode) = length;
739 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100740 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
741 PyObject_DEL(_PyUnicode_WSTR(unicode));
742 _PyUnicode_WSTR(unicode) = NULL;
743 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200744#ifdef Py_DEBUG
745 unicode_fill_invalid(unicode, old_length);
746#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200747 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
748 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200749 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200750 return unicode;
751}
752
Alexander Belopolsky40018472011-02-26 01:02:56 +0000753static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200754resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000755{
Victor Stinner95663112011-10-04 01:03:50 +0200756 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100757 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200758 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200759 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000760
Victor Stinnerfe226c02011-10-03 03:52:20 +0200761 if (PyUnicode_IS_READY(unicode)) {
762 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200763 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200765#ifdef Py_DEBUG
766 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
767#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768
769 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200770 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200771 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
772 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773
774 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
775 PyErr_NoMemory();
776 return -1;
777 }
778 new_size = (length + 1) * char_size;
779
Victor Stinner7a9105a2011-12-12 00:13:42 +0100780 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
781 {
782 PyObject_DEL(_PyUnicode_UTF8(unicode));
783 _PyUnicode_UTF8(unicode) = NULL;
784 _PyUnicode_UTF8_LENGTH(unicode) = 0;
785 }
786
Victor Stinnerfe226c02011-10-03 03:52:20 +0200787 data = (PyObject *)PyObject_REALLOC(data, new_size);
788 if (data == NULL) {
789 PyErr_NoMemory();
790 return -1;
791 }
792 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200793 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200795 _PyUnicode_WSTR_LENGTH(unicode) = length;
796 }
797 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200798 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200799 _PyUnicode_UTF8_LENGTH(unicode) = length;
800 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200801 _PyUnicode_LENGTH(unicode) = length;
802 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200803#ifdef Py_DEBUG
804 unicode_fill_invalid(unicode, old_length);
805#endif
Victor Stinner95663112011-10-04 01:03:50 +0200806 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200807 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200808 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200809 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200810 }
Victor Stinner95663112011-10-04 01:03:50 +0200811 assert(_PyUnicode_WSTR(unicode) != NULL);
812
813 /* check for integer overflow */
814 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
815 PyErr_NoMemory();
816 return -1;
817 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100818 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200819 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100820 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200821 if (!wstr) {
822 PyErr_NoMemory();
823 return -1;
824 }
825 _PyUnicode_WSTR(unicode) = wstr;
826 _PyUnicode_WSTR(unicode)[length] = 0;
827 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200828 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000829 return 0;
830}
831
Victor Stinnerfe226c02011-10-03 03:52:20 +0200832static PyObject*
833resize_copy(PyObject *unicode, Py_ssize_t length)
834{
835 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100836 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200837 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100838
Benjamin Petersonbac79492012-01-14 13:34:47 -0500839 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100840 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200841
842 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
843 if (copy == NULL)
844 return NULL;
845
846 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200847 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200848 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200849 }
850 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200851 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100852
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200853 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200854 if (w == NULL)
855 return NULL;
856 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
857 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200858 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
859 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200860 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200861 }
862}
863
Guido van Rossumd57fd912000-03-10 22:53:23 +0000864/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000865 Ux0000 terminated; some code (e.g. new_identifier)
866 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000867
868 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000869 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000870
871*/
872
Alexander Belopolsky40018472011-02-26 01:02:56 +0000873static PyUnicodeObject *
874_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875{
876 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000878
Thomas Wouters477c8d52006-05-27 19:21:47 +0000879 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880 if (length == 0 && unicode_empty != NULL) {
881 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200882 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883 }
884
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000885 /* Ensure we won't overflow the size. */
886 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
887 return (PyUnicodeObject *)PyErr_NoMemory();
888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200889 if (length < 0) {
890 PyErr_SetString(PyExc_SystemError,
891 "Negative size passed to _PyUnicode_New");
892 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000893 }
894
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200895 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
896 if (unicode == NULL)
897 return NULL;
898 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
899 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
900 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100901 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000902 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100903 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905
Jeremy Hyltond8082792003-09-16 19:41:39 +0000906 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000907 * the caller fails before initializing str -- unicode_resize()
908 * reads str[0], and the Keep-Alive optimization can keep memory
909 * allocated for str alive across a call to unicode_dealloc(unicode).
910 * We don't want unicode_resize to read uninitialized memory in
911 * that case.
912 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 _PyUnicode_WSTR(unicode)[0] = 0;
914 _PyUnicode_WSTR(unicode)[length] = 0;
915 _PyUnicode_WSTR_LENGTH(unicode) = length;
916 _PyUnicode_HASH(unicode) = -1;
917 _PyUnicode_STATE(unicode).interned = 0;
918 _PyUnicode_STATE(unicode).kind = 0;
919 _PyUnicode_STATE(unicode).compact = 0;
920 _PyUnicode_STATE(unicode).ready = 0;
921 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200922 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200924 _PyUnicode_UTF8(unicode) = NULL;
925 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100926 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000927 return unicode;
928}
929
Victor Stinnerf42dc442011-10-02 23:33:16 +0200930static const char*
931unicode_kind_name(PyObject *unicode)
932{
Victor Stinner42dfd712011-10-03 14:41:45 +0200933 /* don't check consistency: unicode_kind_name() is called from
934 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200935 if (!PyUnicode_IS_COMPACT(unicode))
936 {
937 if (!PyUnicode_IS_READY(unicode))
938 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600939 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200940 {
941 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200942 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 return "legacy ascii";
944 else
945 return "legacy latin1";
946 case PyUnicode_2BYTE_KIND:
947 return "legacy UCS2";
948 case PyUnicode_4BYTE_KIND:
949 return "legacy UCS4";
950 default:
951 return "<legacy invalid kind>";
952 }
953 }
954 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600955 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200956 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200957 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200958 return "ascii";
959 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200960 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200961 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200962 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200963 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965 default:
966 return "<invalid compact kind>";
967 }
968}
969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200970#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200971/* Functions wrapping macros for use in debugger */
972char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200973 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974}
975
976void *_PyUnicode_compact_data(void *unicode) {
977 return _PyUnicode_COMPACT_DATA(unicode);
978}
979void *_PyUnicode_data(void *unicode){
980 printf("obj %p\n", unicode);
981 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
982 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
983 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
984 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
985 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
986 return PyUnicode_DATA(unicode);
987}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200988
989void
990_PyUnicode_Dump(PyObject *op)
991{
992 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200993 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
994 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
995 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200996
Victor Stinnera849a4b2011-10-03 12:12:11 +0200997 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200998 {
999 if (ascii->state.ascii)
1000 data = (ascii + 1);
1001 else
1002 data = (compact + 1);
1003 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001004 else
1005 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
1007
Victor Stinnera849a4b2011-10-03 12:12:11 +02001008 if (ascii->wstr == data)
1009 printf("shared ");
1010 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001011
Victor Stinnera3b334d2011-10-03 13:53:37 +02001012 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +02001013 printf(" (%zu), ", compact->wstr_length);
1014 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1015 printf("shared ");
1016 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001017 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001018 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001019}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001020#endif
1021
1022PyObject *
1023PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1024{
1025 PyObject *obj;
1026 PyCompactUnicodeObject *unicode;
1027 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001028 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001029 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030 Py_ssize_t char_size;
1031 Py_ssize_t struct_size;
1032
1033 /* Optimization for empty strings */
1034 if (size == 0 && unicode_empty != NULL) {
1035 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001036 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001037 }
1038
Victor Stinner9e9d6892011-10-04 01:02:02 +02001039 is_ascii = 0;
1040 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001041 struct_size = sizeof(PyCompactUnicodeObject);
1042 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001043 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 char_size = 1;
1045 is_ascii = 1;
1046 struct_size = sizeof(PyASCIIObject);
1047 }
1048 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001049 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 char_size = 1;
1051 }
1052 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001053 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 char_size = 2;
1055 if (sizeof(wchar_t) == 2)
1056 is_sharing = 1;
1057 }
1058 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001059 if (maxchar > MAX_UNICODE) {
1060 PyErr_SetString(PyExc_SystemError,
1061 "invalid maximum character passed to PyUnicode_New");
1062 return NULL;
1063 }
Victor Stinner8f825062012-04-27 13:55:39 +02001064 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001065 char_size = 4;
1066 if (sizeof(wchar_t) == 4)
1067 is_sharing = 1;
1068 }
1069
1070 /* Ensure we won't overflow the size. */
1071 if (size < 0) {
1072 PyErr_SetString(PyExc_SystemError,
1073 "Negative size passed to PyUnicode_New");
1074 return NULL;
1075 }
1076 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1077 return PyErr_NoMemory();
1078
1079 /* Duplicated allocation code from _PyObject_New() instead of a call to
1080 * PyObject_New() so we are able to allocate space for the object and
1081 * it's data buffer.
1082 */
1083 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1084 if (obj == NULL)
1085 return PyErr_NoMemory();
1086 obj = PyObject_INIT(obj, &PyUnicode_Type);
1087 if (obj == NULL)
1088 return NULL;
1089
1090 unicode = (PyCompactUnicodeObject *)obj;
1091 if (is_ascii)
1092 data = ((PyASCIIObject*)obj) + 1;
1093 else
1094 data = unicode + 1;
1095 _PyUnicode_LENGTH(unicode) = size;
1096 _PyUnicode_HASH(unicode) = -1;
1097 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001098 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099 _PyUnicode_STATE(unicode).compact = 1;
1100 _PyUnicode_STATE(unicode).ready = 1;
1101 _PyUnicode_STATE(unicode).ascii = is_ascii;
1102 if (is_ascii) {
1103 ((char*)data)[size] = 0;
1104 _PyUnicode_WSTR(unicode) = NULL;
1105 }
Victor Stinner8f825062012-04-27 13:55:39 +02001106 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107 ((char*)data)[size] = 0;
1108 _PyUnicode_WSTR(unicode) = NULL;
1109 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001111 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001112 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001113 else {
1114 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001115 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001116 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001118 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 ((Py_UCS4*)data)[size] = 0;
1120 if (is_sharing) {
1121 _PyUnicode_WSTR_LENGTH(unicode) = size;
1122 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1123 }
1124 else {
1125 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1126 _PyUnicode_WSTR(unicode) = NULL;
1127 }
1128 }
Victor Stinner8f825062012-04-27 13:55:39 +02001129#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001130 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001131#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001132 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001133 return obj;
1134}
1135
1136#if SIZEOF_WCHAR_T == 2
1137/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1138 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001139 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001140
1141 This function assumes that unicode can hold one more code point than wstr
1142 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001143static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001145 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146{
1147 const wchar_t *iter;
1148 Py_UCS4 *ucs4_out;
1149
Victor Stinner910337b2011-10-03 03:20:16 +02001150 assert(unicode != NULL);
1151 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1153 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1154
1155 for (iter = begin; iter < end; ) {
1156 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1157 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001158 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1159 && (iter+1) < end
1160 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161 {
Victor Stinner551ac952011-11-29 22:58:13 +01001162 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001163 iter += 2;
1164 }
1165 else {
1166 *ucs4_out++ = *iter;
1167 iter++;
1168 }
1169 }
1170 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1171 _PyUnicode_GET_LENGTH(unicode)));
1172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173}
1174#endif
1175
Victor Stinnercd9950f2011-10-02 00:34:53 +02001176static int
Victor Stinner488fa492011-12-12 00:01:39 +01001177unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001178{
Victor Stinner488fa492011-12-12 00:01:39 +01001179 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001180 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001181 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001182 return -1;
1183 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001184 return 0;
1185}
1186
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001187static int
1188_copy_characters(PyObject *to, Py_ssize_t to_start,
1189 PyObject *from, Py_ssize_t from_start,
1190 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001191{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001192 unsigned int from_kind, to_kind;
1193 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001194
Victor Stinneree4544c2012-05-09 22:24:08 +02001195 assert(0 <= how_many);
1196 assert(0 <= from_start);
1197 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001198 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001199 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001200 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201
Victor Stinnerd3f08822012-05-29 12:57:52 +02001202 assert(PyUnicode_Check(to));
1203 assert(PyUnicode_IS_READY(to));
1204 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1205
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001206 if (how_many == 0)
1207 return 0;
1208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001210 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001212 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001213
Victor Stinnerf1852262012-06-16 16:38:26 +02001214#ifdef Py_DEBUG
1215 if (!check_maxchar
1216 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1217 {
1218 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1219 Py_UCS4 ch;
1220 Py_ssize_t i;
1221 for (i=0; i < how_many; i++) {
1222 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1223 assert(ch <= to_maxchar);
1224 }
1225 }
1226#endif
1227
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001228 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001229 if (check_maxchar
1230 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1231 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001232 /* Writing Latin-1 characters into an ASCII string requires to
1233 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001234 Py_UCS4 max_char;
1235 max_char = ucs1lib_find_max_char(from_data,
1236 (Py_UCS1*)from_data + how_many);
1237 if (max_char >= 128)
1238 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001239 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001240 Py_MEMCPY((char*)to_data + to_kind * to_start,
1241 (char*)from_data + from_kind * from_start,
1242 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001243 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001244 else if (from_kind == PyUnicode_1BYTE_KIND
1245 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001246 {
1247 _PyUnicode_CONVERT_BYTES(
1248 Py_UCS1, Py_UCS2,
1249 PyUnicode_1BYTE_DATA(from) + from_start,
1250 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1251 PyUnicode_2BYTE_DATA(to) + to_start
1252 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001253 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001254 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001255 && to_kind == PyUnicode_4BYTE_KIND)
1256 {
1257 _PyUnicode_CONVERT_BYTES(
1258 Py_UCS1, Py_UCS4,
1259 PyUnicode_1BYTE_DATA(from) + from_start,
1260 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1261 PyUnicode_4BYTE_DATA(to) + to_start
1262 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001263 }
1264 else if (from_kind == PyUnicode_2BYTE_KIND
1265 && to_kind == PyUnicode_4BYTE_KIND)
1266 {
1267 _PyUnicode_CONVERT_BYTES(
1268 Py_UCS2, Py_UCS4,
1269 PyUnicode_2BYTE_DATA(from) + from_start,
1270 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1271 PyUnicode_4BYTE_DATA(to) + to_start
1272 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001273 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001274 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001275 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1276
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001277 if (!check_maxchar) {
1278 if (from_kind == PyUnicode_2BYTE_KIND
1279 && to_kind == PyUnicode_1BYTE_KIND)
1280 {
1281 _PyUnicode_CONVERT_BYTES(
1282 Py_UCS2, Py_UCS1,
1283 PyUnicode_2BYTE_DATA(from) + from_start,
1284 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1285 PyUnicode_1BYTE_DATA(to) + to_start
1286 );
1287 }
1288 else if (from_kind == PyUnicode_4BYTE_KIND
1289 && to_kind == PyUnicode_1BYTE_KIND)
1290 {
1291 _PyUnicode_CONVERT_BYTES(
1292 Py_UCS4, Py_UCS1,
1293 PyUnicode_4BYTE_DATA(from) + from_start,
1294 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1295 PyUnicode_1BYTE_DATA(to) + to_start
1296 );
1297 }
1298 else if (from_kind == PyUnicode_4BYTE_KIND
1299 && to_kind == PyUnicode_2BYTE_KIND)
1300 {
1301 _PyUnicode_CONVERT_BYTES(
1302 Py_UCS4, Py_UCS2,
1303 PyUnicode_4BYTE_DATA(from) + from_start,
1304 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1305 PyUnicode_2BYTE_DATA(to) + to_start
1306 );
1307 }
1308 else {
1309 assert(0);
1310 return -1;
1311 }
1312 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001313 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001314 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001315 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001316 Py_ssize_t i;
1317
Victor Stinnera0702ab2011-09-29 14:14:38 +02001318 for (i=0; i < how_many; i++) {
1319 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001320 if (ch > to_maxchar)
1321 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001322 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1323 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 }
1325 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001326 return 0;
1327}
1328
Victor Stinnerd3f08822012-05-29 12:57:52 +02001329void
1330_PyUnicode_FastCopyCharacters(
1331 PyObject *to, Py_ssize_t to_start,
1332 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001333{
1334 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1335}
1336
1337Py_ssize_t
1338PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1339 PyObject *from, Py_ssize_t from_start,
1340 Py_ssize_t how_many)
1341{
1342 int err;
1343
1344 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1345 PyErr_BadInternalCall();
1346 return -1;
1347 }
1348
Benjamin Petersonbac79492012-01-14 13:34:47 -05001349 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001350 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001351 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001352 return -1;
1353
Victor Stinnerd3f08822012-05-29 12:57:52 +02001354 if (from_start < 0) {
1355 PyErr_SetString(PyExc_IndexError, "string index out of range");
1356 return -1;
1357 }
1358 if (to_start < 0) {
1359 PyErr_SetString(PyExc_IndexError, "string index out of range");
1360 return -1;
1361 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001362 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1363 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1364 PyErr_Format(PyExc_SystemError,
1365 "Cannot write %zi characters at %zi "
1366 "in a string of %zi characters",
1367 how_many, to_start, PyUnicode_GET_LENGTH(to));
1368 return -1;
1369 }
1370
1371 if (how_many == 0)
1372 return 0;
1373
Victor Stinner488fa492011-12-12 00:01:39 +01001374 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001375 return -1;
1376
1377 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1378 if (err) {
1379 PyErr_Format(PyExc_SystemError,
1380 "Cannot copy %s characters "
1381 "into a string of %s characters",
1382 unicode_kind_name(from),
1383 unicode_kind_name(to));
1384 return -1;
1385 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001386 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387}
1388
Victor Stinner17222162011-09-28 22:15:37 +02001389/* Find the maximum code point and count the number of surrogate pairs so a
1390 correct string length can be computed before converting a string to UCS4.
1391 This function counts single surrogates as a character and not as a pair.
1392
1393 Return 0 on success, or -1 on error. */
1394static int
1395find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1396 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397{
1398 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001399 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400
Victor Stinnerc53be962011-10-02 21:33:54 +02001401 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402 *num_surrogates = 0;
1403 *maxchar = 0;
1404
1405 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001407 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1408 && (iter+1) < end
1409 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1410 {
1411 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1412 ++(*num_surrogates);
1413 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 }
1415 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001417 {
1418 ch = *iter;
1419 iter++;
1420 }
1421 if (ch > *maxchar) {
1422 *maxchar = ch;
1423 if (*maxchar > MAX_UNICODE) {
1424 PyErr_Format(PyExc_ValueError,
1425 "character U+%x is not in range [U+0000; U+10ffff]",
1426 ch);
1427 return -1;
1428 }
1429 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 }
1431 return 0;
1432}
1433
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001434int
1435_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001436{
1437 wchar_t *end;
1438 Py_UCS4 maxchar = 0;
1439 Py_ssize_t num_surrogates;
1440#if SIZEOF_WCHAR_T == 2
1441 Py_ssize_t length_wo_surrogates;
1442#endif
1443
Georg Brandl7597add2011-10-05 16:36:47 +02001444 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001445 strings were created using _PyObject_New() and where no canonical
1446 representation (the str field) has been set yet aka strings
1447 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001448 assert(_PyUnicode_CHECK(unicode));
1449 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001451 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001453 /* Actually, it should neither be interned nor be anything else: */
1454 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001457 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001458 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460
1461 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1463 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 PyErr_NoMemory();
1465 return -1;
1466 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001467 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 _PyUnicode_WSTR(unicode), end,
1469 PyUnicode_1BYTE_DATA(unicode));
1470 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1471 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1472 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1473 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001474 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001475 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001476 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 }
1478 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001479 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001480 _PyUnicode_UTF8(unicode) = NULL;
1481 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001482 }
1483 PyObject_FREE(_PyUnicode_WSTR(unicode));
1484 _PyUnicode_WSTR(unicode) = NULL;
1485 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1486 }
1487 /* In this case we might have to convert down from 4-byte native
1488 wchar_t to 2-byte unicode. */
1489 else if (maxchar < 65536) {
1490 assert(num_surrogates == 0 &&
1491 "FindMaxCharAndNumSurrogatePairs() messed up");
1492
Victor Stinner506f5922011-09-28 22:34:18 +02001493#if SIZEOF_WCHAR_T == 2
1494 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001495 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001496 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1497 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1498 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001499 _PyUnicode_UTF8(unicode) = NULL;
1500 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001501#else
1502 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001503 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001504 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001505 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001506 PyErr_NoMemory();
1507 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001508 }
Victor Stinner506f5922011-09-28 22:34:18 +02001509 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1510 _PyUnicode_WSTR(unicode), end,
1511 PyUnicode_2BYTE_DATA(unicode));
1512 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1513 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1514 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001515 _PyUnicode_UTF8(unicode) = NULL;
1516 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001517 PyObject_FREE(_PyUnicode_WSTR(unicode));
1518 _PyUnicode_WSTR(unicode) = NULL;
1519 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1520#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 }
1522 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1523 else {
1524#if SIZEOF_WCHAR_T == 2
1525 /* in case the native representation is 2-bytes, we need to allocate a
1526 new normalized 4-byte version. */
1527 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001528 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1529 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001530 PyErr_NoMemory();
1531 return -1;
1532 }
1533 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1534 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001535 _PyUnicode_UTF8(unicode) = NULL;
1536 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001537 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1538 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001539 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyObject_FREE(_PyUnicode_WSTR(unicode));
1541 _PyUnicode_WSTR(unicode) = NULL;
1542 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1543#else
1544 assert(num_surrogates == 0);
1545
Victor Stinnerc3c74152011-10-02 20:39:55 +02001546 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001547 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001548 _PyUnicode_UTF8(unicode) = NULL;
1549 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1551#endif
1552 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1553 }
1554 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001555 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001556 return 0;
1557}
1558
Alexander Belopolsky40018472011-02-26 01:02:56 +00001559static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001560unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001561{
Walter Dörwald16807132007-05-25 13:52:07 +00001562 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001563 case SSTATE_NOT_INTERNED:
1564 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001565
Benjamin Peterson29060642009-01-31 22:14:21 +00001566 case SSTATE_INTERNED_MORTAL:
1567 /* revive dead object temporarily for DelItem */
1568 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001569 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001570 Py_FatalError(
1571 "deletion of interned string failed");
1572 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001573
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 case SSTATE_INTERNED_IMMORTAL:
1575 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001576
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 default:
1578 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001579 }
1580
Victor Stinner03490912011-10-03 23:45:12 +02001581 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001582 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001583 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001584 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001585 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1586 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001587
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001588 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001589}
1590
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001591#ifdef Py_DEBUG
1592static int
1593unicode_is_singleton(PyObject *unicode)
1594{
1595 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1596 if (unicode == unicode_empty)
1597 return 1;
1598 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1599 {
1600 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1601 if (ch < 256 && unicode_latin1[ch] == unicode)
1602 return 1;
1603 }
1604 return 0;
1605}
1606#endif
1607
Alexander Belopolsky40018472011-02-26 01:02:56 +00001608static int
Victor Stinner488fa492011-12-12 00:01:39 +01001609unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001610{
Victor Stinner488fa492011-12-12 00:01:39 +01001611 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001612 if (Py_REFCNT(unicode) != 1)
1613 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001614 if (_PyUnicode_HASH(unicode) != -1)
1615 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001616 if (PyUnicode_CHECK_INTERNED(unicode))
1617 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001618 if (!PyUnicode_CheckExact(unicode))
1619 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001620#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001621 /* singleton refcount is greater than 1 */
1622 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001623#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001624 return 1;
1625}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001626
Victor Stinnerfe226c02011-10-03 03:52:20 +02001627static int
1628unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1629{
1630 PyObject *unicode;
1631 Py_ssize_t old_length;
1632
1633 assert(p_unicode != NULL);
1634 unicode = *p_unicode;
1635
1636 assert(unicode != NULL);
1637 assert(PyUnicode_Check(unicode));
1638 assert(0 <= length);
1639
Victor Stinner910337b2011-10-03 03:20:16 +02001640 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641 old_length = PyUnicode_WSTR_LENGTH(unicode);
1642 else
1643 old_length = PyUnicode_GET_LENGTH(unicode);
1644 if (old_length == length)
1645 return 0;
1646
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001647 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001648 _Py_INCREF_UNICODE_EMPTY();
1649 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001650 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001651 Py_DECREF(*p_unicode);
1652 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001653 return 0;
1654 }
1655
Victor Stinner488fa492011-12-12 00:01:39 +01001656 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001657 PyObject *copy = resize_copy(unicode, length);
1658 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001659 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001660 Py_DECREF(*p_unicode);
1661 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001662 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001663 }
1664
Victor Stinnerfe226c02011-10-03 03:52:20 +02001665 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001666 PyObject *new_unicode = resize_compact(unicode, length);
1667 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001668 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001669 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001671 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001672 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673}
1674
Alexander Belopolsky40018472011-02-26 01:02:56 +00001675int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001676PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001677{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 PyObject *unicode;
1679 if (p_unicode == NULL) {
1680 PyErr_BadInternalCall();
1681 return -1;
1682 }
1683 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001684 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001685 {
1686 PyErr_BadInternalCall();
1687 return -1;
1688 }
1689 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001690}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001691
Victor Stinnerc5166102012-02-22 13:55:02 +01001692/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001693
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001694 WARNING: The function doesn't copy the terminating null character and
1695 doesn't check the maximum character (may write a latin1 character in an
1696 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001697static void
1698unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1699 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001700{
1701 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1702 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001703 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001704
1705 switch (kind) {
1706 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001707 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001708#ifdef Py_DEBUG
1709 if (PyUnicode_IS_ASCII(unicode)) {
1710 Py_UCS4 maxchar = ucs1lib_find_max_char(
1711 (const Py_UCS1*)str,
1712 (const Py_UCS1*)str + len);
1713 assert(maxchar < 128);
1714 }
1715#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001716 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001717 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001718 }
1719 case PyUnicode_2BYTE_KIND: {
1720 Py_UCS2 *start = (Py_UCS2 *)data + index;
1721 Py_UCS2 *ucs2 = start;
1722 assert(index <= PyUnicode_GET_LENGTH(unicode));
1723
Victor Stinner184252a2012-06-16 02:57:41 +02001724 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001725 *ucs2 = (Py_UCS2)*str;
1726
1727 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001728 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001729 }
1730 default: {
1731 Py_UCS4 *start = (Py_UCS4 *)data + index;
1732 Py_UCS4 *ucs4 = start;
1733 assert(kind == PyUnicode_4BYTE_KIND);
1734 assert(index <= PyUnicode_GET_LENGTH(unicode));
1735
Victor Stinner184252a2012-06-16 02:57:41 +02001736 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001737 *ucs4 = (Py_UCS4)*str;
1738
1739 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001740 }
1741 }
1742}
1743
1744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745static PyObject*
1746get_latin1_char(unsigned char ch)
1747{
Victor Stinnera464fc12011-10-02 20:39:30 +02001748 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001749 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001750 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 if (!unicode)
1752 return NULL;
1753 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001754 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 unicode_latin1[ch] = unicode;
1756 }
1757 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001758 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759}
1760
Alexander Belopolsky40018472011-02-26 01:02:56 +00001761PyObject *
1762PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001763{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001764 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765 Py_UCS4 maxchar = 0;
1766 Py_ssize_t num_surrogates;
1767
1768 if (u == NULL)
1769 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001770
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001771 /* If the Unicode data is known at construction time, we can apply
1772 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001774 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001775 if (size == 0)
1776 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 /* Single character Unicode objects in the Latin-1 range are
1779 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001780 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001781 return get_latin1_char((unsigned char)*u);
1782
1783 /* If not empty and not single character, copy the Unicode data
1784 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001785 if (find_maxchar_surrogates(u, u + size,
1786 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 return NULL;
1788
Victor Stinner8faf8212011-12-08 22:14:11 +01001789 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001790 if (!unicode)
1791 return NULL;
1792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793 switch (PyUnicode_KIND(unicode)) {
1794 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001795 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1797 break;
1798 case PyUnicode_2BYTE_KIND:
1799#if Py_UNICODE_SIZE == 2
1800 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1801#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001802 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001803 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1804#endif
1805 break;
1806 case PyUnicode_4BYTE_KIND:
1807#if SIZEOF_WCHAR_T == 2
1808 /* This is the only case which has to process surrogates, thus
1809 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001810 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811#else
1812 assert(num_surrogates == 0);
1813 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1814#endif
1815 break;
1816 default:
1817 assert(0 && "Impossible state");
1818 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001819
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001820 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001821}
1822
Alexander Belopolsky40018472011-02-26 01:02:56 +00001823PyObject *
1824PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001825{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001826 if (size < 0) {
1827 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001828 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001829 return NULL;
1830 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001831 if (u != NULL)
1832 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1833 else
1834 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001835}
1836
Alexander Belopolsky40018472011-02-26 01:02:56 +00001837PyObject *
1838PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001839{
1840 size_t size = strlen(u);
1841 if (size > PY_SSIZE_T_MAX) {
1842 PyErr_SetString(PyExc_OverflowError, "input too long");
1843 return NULL;
1844 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001845 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001846}
1847
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001848PyObject *
1849_PyUnicode_FromId(_Py_Identifier *id)
1850{
1851 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001852 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1853 strlen(id->string),
1854 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001855 if (!id->object)
1856 return NULL;
1857 PyUnicode_InternInPlace(&id->object);
1858 assert(!id->next);
1859 id->next = static_strings;
1860 static_strings = id;
1861 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001862 return id->object;
1863}
1864
1865void
1866_PyUnicode_ClearStaticStrings()
1867{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001868 _Py_Identifier *tmp, *s = static_strings;
1869 while (s) {
1870 Py_DECREF(s->object);
1871 s->object = NULL;
1872 tmp = s->next;
1873 s->next = NULL;
1874 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001875 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001876 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001877}
1878
Benjamin Peterson0df54292012-03-26 14:50:32 -04001879/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001880
Victor Stinnerd3f08822012-05-29 12:57:52 +02001881PyObject*
1882_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001883{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001884 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001885 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001886 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001887#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001888 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001889#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001890 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001891 }
Victor Stinner785938e2011-12-11 20:09:03 +01001892 unicode = PyUnicode_New(size, 127);
1893 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001894 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001895 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1896 assert(_PyUnicode_CheckConsistency(unicode, 1));
1897 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001898}
1899
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001900static Py_UCS4
1901kind_maxchar_limit(unsigned int kind)
1902{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001903 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001904 case PyUnicode_1BYTE_KIND:
1905 return 0x80;
1906 case PyUnicode_2BYTE_KIND:
1907 return 0x100;
1908 case PyUnicode_4BYTE_KIND:
1909 return 0x10000;
1910 default:
1911 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001912 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001913 }
1914}
1915
Victor Stinnere6abb482012-05-02 01:15:40 +02001916Py_LOCAL_INLINE(Py_UCS4)
1917align_maxchar(Py_UCS4 maxchar)
1918{
1919 if (maxchar <= 127)
1920 return 127;
1921 else if (maxchar <= 255)
1922 return 255;
1923 else if (maxchar <= 65535)
1924 return 65535;
1925 else
1926 return MAX_UNICODE;
1927}
1928
Victor Stinner702c7342011-10-05 13:50:52 +02001929static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001930_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001932 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001933 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001934
Serhiy Storchaka678db842013-01-26 12:16:36 +02001935 if (size == 0)
1936 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001937 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001938 if (size == 1)
1939 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001940
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001941 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001942 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 if (!res)
1944 return NULL;
1945 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001946 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001948}
1949
Victor Stinnere57b1c02011-09-28 22:20:48 +02001950static PyObject*
1951_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952{
1953 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001954 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001955
Serhiy Storchaka678db842013-01-26 12:16:36 +02001956 if (size == 0)
1957 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001958 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001959 if (size == 1) {
1960 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001961 int kind;
1962 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001963 if (ch < 256)
1964 return get_latin1_char((unsigned char)ch);
1965
1966 res = PyUnicode_New(1, ch);
1967 if (res == NULL)
1968 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02001969 kind = PyUnicode_KIND(res);
1970 data = PyUnicode_DATA(res);
1971 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001972 assert(_PyUnicode_CheckConsistency(res, 1));
1973 return res;
1974 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001975
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001976 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001977 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 if (!res)
1979 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001980 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001981 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001982 else {
1983 _PyUnicode_CONVERT_BYTES(
1984 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1985 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001986 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987 return res;
1988}
1989
Victor Stinnere57b1c02011-09-28 22:20:48 +02001990static PyObject*
1991_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992{
1993 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001995
Serhiy Storchaka678db842013-01-26 12:16:36 +02001996 if (size == 0)
1997 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001998 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001999 if (size == 1) {
2000 Py_UCS4 ch = u[0];
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002001 int kind;
2002 void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002003 if (ch < 256)
2004 return get_latin1_char((unsigned char)ch);
2005
2006 res = PyUnicode_New(1, ch);
2007 if (res == NULL)
2008 return NULL;
Victor Stinnerf50a4e92013-04-09 22:38:52 +02002009 kind = PyUnicode_KIND(res);
2010 data = PyUnicode_DATA(res);
2011 PyUnicode_WRITE(kind, data, 0, ch);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02002012 assert(_PyUnicode_CheckConsistency(res, 1));
2013 return res;
2014 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002015
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002016 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 if (!res)
2019 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002020 if (max_char < 256)
2021 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2022 PyUnicode_1BYTE_DATA(res));
2023 else if (max_char < 0x10000)
2024 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2025 PyUnicode_2BYTE_DATA(res));
2026 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002027 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002028 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 return res;
2030}
2031
2032PyObject*
2033PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2034{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002035 if (size < 0) {
2036 PyErr_SetString(PyExc_ValueError, "size must be positive");
2037 return NULL;
2038 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002039 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002041 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002042 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002043 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002045 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002046 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002047 PyErr_SetString(PyExc_SystemError, "invalid kind");
2048 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050}
2051
Victor Stinnerece58de2012-04-23 23:36:38 +02002052Py_UCS4
2053_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2054{
2055 enum PyUnicode_Kind kind;
2056 void *startptr, *endptr;
2057
2058 assert(PyUnicode_IS_READY(unicode));
2059 assert(0 <= start);
2060 assert(end <= PyUnicode_GET_LENGTH(unicode));
2061 assert(start <= end);
2062
2063 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2064 return PyUnicode_MAX_CHAR_VALUE(unicode);
2065
2066 if (start == end)
2067 return 127;
2068
Victor Stinner94d558b2012-04-27 22:26:58 +02002069 if (PyUnicode_IS_ASCII(unicode))
2070 return 127;
2071
Victor Stinnerece58de2012-04-23 23:36:38 +02002072 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002073 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002074 endptr = (char *)startptr + end * kind;
2075 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002076 switch(kind) {
2077 case PyUnicode_1BYTE_KIND:
2078 return ucs1lib_find_max_char(startptr, endptr);
2079 case PyUnicode_2BYTE_KIND:
2080 return ucs2lib_find_max_char(startptr, endptr);
2081 case PyUnicode_4BYTE_KIND:
2082 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002083 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 assert(0);
2085 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002086 }
2087}
2088
Victor Stinner25a4b292011-10-06 12:31:55 +02002089/* Ensure that a string uses the most efficient storage, if it is not the
2090 case: create a new string with of the right kind. Write NULL into *p_unicode
2091 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002092static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002093unicode_adjust_maxchar(PyObject **p_unicode)
2094{
2095 PyObject *unicode, *copy;
2096 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002097 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002098 unsigned int kind;
2099
2100 assert(p_unicode != NULL);
2101 unicode = *p_unicode;
2102 assert(PyUnicode_IS_READY(unicode));
2103 if (PyUnicode_IS_ASCII(unicode))
2104 return;
2105
2106 len = PyUnicode_GET_LENGTH(unicode);
2107 kind = PyUnicode_KIND(unicode);
2108 if (kind == PyUnicode_1BYTE_KIND) {
2109 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002110 max_char = ucs1lib_find_max_char(u, u + len);
2111 if (max_char >= 128)
2112 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002113 }
2114 else if (kind == PyUnicode_2BYTE_KIND) {
2115 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002116 max_char = ucs2lib_find_max_char(u, u + len);
2117 if (max_char >= 256)
2118 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002119 }
2120 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002121 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002122 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002123 max_char = ucs4lib_find_max_char(u, u + len);
2124 if (max_char >= 0x10000)
2125 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002126 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002128 if (copy != NULL)
2129 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 Py_DECREF(unicode);
2131 *p_unicode = copy;
2132}
2133
Victor Stinner034f6cf2011-09-30 02:26:44 +02002134PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002135_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002136{
Victor Stinner87af4f22011-11-21 23:03:47 +01002137 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002138 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002139
Victor Stinner034f6cf2011-09-30 02:26:44 +02002140 if (!PyUnicode_Check(unicode)) {
2141 PyErr_BadInternalCall();
2142 return NULL;
2143 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002144 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002145 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146
Victor Stinner87af4f22011-11-21 23:03:47 +01002147 length = PyUnicode_GET_LENGTH(unicode);
2148 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002149 if (!copy)
2150 return NULL;
2151 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2152
Victor Stinner87af4f22011-11-21 23:03:47 +01002153 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2154 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002155 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002156 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002157}
2158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002159
Victor Stinnerbc603d12011-10-02 01:00:40 +02002160/* Widen Unicode objects to larger buffers. Don't write terminating null
2161 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162
2163void*
2164_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2165{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002166 Py_ssize_t len;
2167 void *result;
2168 unsigned int skind;
2169
Benjamin Petersonbac79492012-01-14 13:34:47 -05002170 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002171 return NULL;
2172
2173 len = PyUnicode_GET_LENGTH(s);
2174 skind = PyUnicode_KIND(s);
2175 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002176 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 return NULL;
2178 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002179 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002180 case PyUnicode_2BYTE_KIND:
2181 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2182 if (!result)
2183 return PyErr_NoMemory();
2184 assert(skind == PyUnicode_1BYTE_KIND);
2185 _PyUnicode_CONVERT_BYTES(
2186 Py_UCS1, Py_UCS2,
2187 PyUnicode_1BYTE_DATA(s),
2188 PyUnicode_1BYTE_DATA(s) + len,
2189 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002191 case PyUnicode_4BYTE_KIND:
2192 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2193 if (!result)
2194 return PyErr_NoMemory();
2195 if (skind == PyUnicode_2BYTE_KIND) {
2196 _PyUnicode_CONVERT_BYTES(
2197 Py_UCS2, Py_UCS4,
2198 PyUnicode_2BYTE_DATA(s),
2199 PyUnicode_2BYTE_DATA(s) + len,
2200 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002202 else {
2203 assert(skind == PyUnicode_1BYTE_KIND);
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS1, Py_UCS4,
2206 PyUnicode_1BYTE_DATA(s),
2207 PyUnicode_1BYTE_DATA(s) + len,
2208 result);
2209 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002211 default:
2212 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002213 }
Victor Stinner01698042011-10-04 00:04:26 +02002214 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 return NULL;
2216}
2217
2218static Py_UCS4*
2219as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2220 int copy_null)
2221{
2222 int kind;
2223 void *data;
2224 Py_ssize_t len, targetlen;
2225 if (PyUnicode_READY(string) == -1)
2226 return NULL;
2227 kind = PyUnicode_KIND(string);
2228 data = PyUnicode_DATA(string);
2229 len = PyUnicode_GET_LENGTH(string);
2230 targetlen = len;
2231 if (copy_null)
2232 targetlen++;
2233 if (!target) {
2234 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2235 PyErr_NoMemory();
2236 return NULL;
2237 }
2238 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2239 if (!target) {
2240 PyErr_NoMemory();
2241 return NULL;
2242 }
2243 }
2244 else {
2245 if (targetsize < targetlen) {
2246 PyErr_Format(PyExc_SystemError,
2247 "string is longer than the buffer");
2248 if (copy_null && 0 < targetsize)
2249 target[0] = 0;
2250 return NULL;
2251 }
2252 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002253 if (kind == PyUnicode_1BYTE_KIND) {
2254 Py_UCS1 *start = (Py_UCS1 *) data;
2255 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002256 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002257 else if (kind == PyUnicode_2BYTE_KIND) {
2258 Py_UCS2 *start = (Py_UCS2 *) data;
2259 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2260 }
2261 else {
2262 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002263 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002264 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 if (copy_null)
2266 target[len] = 0;
2267 return target;
2268}
2269
2270Py_UCS4*
2271PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2272 int copy_null)
2273{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002274 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 PyErr_BadInternalCall();
2276 return NULL;
2277 }
2278 return as_ucs4(string, target, targetsize, copy_null);
2279}
2280
2281Py_UCS4*
2282PyUnicode_AsUCS4Copy(PyObject *string)
2283{
2284 return as_ucs4(string, NULL, 0, 1);
2285}
2286
2287#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002288
Alexander Belopolsky40018472011-02-26 01:02:56 +00002289PyObject *
2290PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002291{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002292 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002293 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002294 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002295 PyErr_BadInternalCall();
2296 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002297 }
2298
Martin v. Löwis790465f2008-04-05 20:41:37 +00002299 if (size == -1) {
2300 size = wcslen(w);
2301 }
2302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002303 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304}
2305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002306#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002307
Walter Dörwald346737f2007-05-31 10:44:43 +00002308static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002309makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002310 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002311{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002312 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002313 if (longflag)
2314 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002315 else if (longlongflag) {
2316 /* longlongflag should only ever be nonzero on machines with
2317 HAVE_LONG_LONG defined */
2318#ifdef HAVE_LONG_LONG
2319 char *f = PY_FORMAT_LONG_LONG;
2320 while (*f)
2321 *fmt++ = *f++;
2322#else
2323 /* we shouldn't ever get here */
2324 assert(0);
2325 *fmt++ = 'l';
2326#endif
2327 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002328 else if (size_tflag) {
2329 char *f = PY_FORMAT_SIZE_T;
2330 while (*f)
2331 *fmt++ = *f++;
2332 }
2333 *fmt++ = c;
2334 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002335}
2336
Victor Stinner15a11362012-10-06 23:48:20 +02002337/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002338 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2339 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2340#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002341
2342static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002343unicode_fromformat_arg(_PyUnicodeWriter *writer,
2344 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002345{
Victor Stinnere215d962012-10-06 23:03:36 +02002346 const char *p;
2347 Py_ssize_t len;
2348 int zeropad;
2349 int width;
2350 int precision;
2351 int longflag;
2352 int longlongflag;
2353 int size_tflag;
2354 int fill;
2355
2356 p = f;
2357 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002358 zeropad = 0;
2359 if (*f == '0') {
2360 zeropad = 1;
2361 f++;
2362 }
Victor Stinner96865452011-03-01 23:44:09 +00002363
2364 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner96865452011-03-01 23:44:09 +00002365 width = 0;
Victor Stinnere215d962012-10-06 23:03:36 +02002366 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner3921e902012-10-06 23:05:00 +02002367 if (width > (INT_MAX - ((int)*f - '0')) / 10) {
2368 PyErr_SetString(PyExc_ValueError,
2369 "width too big");
2370 return NULL;
2371 }
Victor Stinnere215d962012-10-06 23:03:36 +02002372 width = (width*10) + (*f - '0');
2373 f++;
2374 }
Victor Stinner96865452011-03-01 23:44:09 +00002375 precision = 0;
2376 if (*f == '.') {
2377 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002378 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner3921e902012-10-06 23:05:00 +02002379 if (precision > (INT_MAX - ((int)*f - '0')) / 10) {
2380 PyErr_SetString(PyExc_ValueError,
2381 "precision too big");
2382 return NULL;
2383 }
Victor Stinnere215d962012-10-06 23:03:36 +02002384 precision = (precision*10) + (*f - '0');
2385 f++;
2386 }
Victor Stinner96865452011-03-01 23:44:09 +00002387 if (*f == '%') {
2388 /* "%.3%s" => f points to "3" */
2389 f--;
2390 }
2391 }
2392 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002393 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002394 f--;
2395 }
Victor Stinner96865452011-03-01 23:44:09 +00002396
2397 /* Handle %ld, %lu, %lld and %llu. */
2398 longflag = 0;
2399 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002400 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002401 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002402 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002403 longflag = 1;
2404 ++f;
2405 }
2406#ifdef HAVE_LONG_LONG
2407 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002408 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002409 longlongflag = 1;
2410 f += 2;
2411 }
2412#endif
2413 }
2414 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002415 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002416 size_tflag = 1;
2417 ++f;
2418 }
Victor Stinnere215d962012-10-06 23:03:36 +02002419
2420 if (f[1] == '\0')
2421 writer->overallocate = 0;
2422
2423 switch (*f) {
2424 case 'c':
2425 {
2426 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002427 if (ordinal < 0 || ordinal > MAX_UNICODE) {
2428 PyErr_SetString(PyExc_ValueError,
2429 "character argument not in range(0x110000)");
2430 return NULL;
2431 }
Victor Stinnere215d962012-10-06 23:03:36 +02002432 if (_PyUnicodeWriter_Prepare(writer, 1, ordinal) == -1)
2433 return NULL;
2434 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ordinal);
2435 writer->pos++;
2436 break;
2437 }
2438
2439 case 'i':
2440 case 'd':
2441 case 'u':
2442 case 'x':
2443 {
2444 /* used by sprintf */
2445 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002446 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinnere215d962012-10-06 23:03:36 +02002447
2448 if (*f == 'u') {
2449 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2450
2451 if (longflag)
2452 len = sprintf(buffer, fmt,
2453 va_arg(*vargs, unsigned long));
2454#ifdef HAVE_LONG_LONG
2455 else if (longlongflag)
2456 len = sprintf(buffer, fmt,
2457 va_arg(*vargs, unsigned PY_LONG_LONG));
2458#endif
2459 else if (size_tflag)
2460 len = sprintf(buffer, fmt,
2461 va_arg(*vargs, size_t));
2462 else
2463 len = sprintf(buffer, fmt,
2464 va_arg(*vargs, unsigned int));
2465 }
2466 else if (*f == 'x') {
2467 makefmt(fmt, 0, 0, 0, 'x');
2468 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2469 }
2470 else {
2471 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2472
2473 if (longflag)
2474 len = sprintf(buffer, fmt,
2475 va_arg(*vargs, long));
2476#ifdef HAVE_LONG_LONG
2477 else if (longlongflag)
2478 len = sprintf(buffer, fmt,
2479 va_arg(*vargs, PY_LONG_LONG));
2480#endif
2481 else if (size_tflag)
2482 len = sprintf(buffer, fmt,
2483 va_arg(*vargs, Py_ssize_t));
2484 else
2485 len = sprintf(buffer, fmt,
2486 va_arg(*vargs, int));
2487 }
2488 assert(len >= 0);
2489
Victor Stinnere215d962012-10-06 23:03:36 +02002490 if (precision < len)
2491 precision = len;
2492 if (width > precision) {
2493 Py_UCS4 fillchar;
2494 fill = width - precision;
2495 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002496 if (_PyUnicodeWriter_Prepare(writer, fill, fillchar) == -1)
2497 return NULL;
2498 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2499 return NULL;
2500 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002501 }
Victor Stinner15a11362012-10-06 23:48:20 +02002502 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002503 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002504 if (_PyUnicodeWriter_Prepare(writer, fill, '0') == -1)
2505 return NULL;
2506 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2507 return NULL;
2508 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002509 }
Victor Stinner15a11362012-10-06 23:48:20 +02002510 if (_PyUnicodeWriter_WriteCstr(writer, buffer, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002511 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002512 break;
2513 }
2514
2515 case 'p':
2516 {
2517 char number[MAX_LONG_LONG_CHARS];
2518
2519 len = sprintf(number, "%p", va_arg(*vargs, void*));
2520 assert(len >= 0);
2521
2522 /* %p is ill-defined: ensure leading 0x. */
2523 if (number[1] == 'X')
2524 number[1] = 'x';
2525 else if (number[1] != 'x') {
2526 memmove(number + 2, number,
2527 strlen(number) + 1);
2528 number[0] = '0';
2529 number[1] = 'x';
2530 len += 2;
2531 }
2532
2533 if (_PyUnicodeWriter_WriteCstr(writer, number, len) == -1)
2534 return NULL;
2535 break;
2536 }
2537
2538 case 's':
2539 {
2540 /* UTF-8 */
2541 const char *s = va_arg(*vargs, const char*);
2542 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
2543 if (!str)
2544 return NULL;
2545 if (_PyUnicodeWriter_WriteStr(writer, str) == -1) {
2546 Py_DECREF(str);
2547 return NULL;
2548 }
2549 Py_DECREF(str);
2550 break;
2551 }
2552
2553 case 'U':
2554 {
2555 PyObject *obj = va_arg(*vargs, PyObject *);
2556 assert(obj && _PyUnicode_CHECK(obj));
2557
2558 if (_PyUnicodeWriter_WriteStr(writer, obj) == -1)
2559 return NULL;
2560 break;
2561 }
2562
2563 case 'V':
2564 {
2565 PyObject *obj = va_arg(*vargs, PyObject *);
2566 const char *str = va_arg(*vargs, const char *);
2567 PyObject *str_obj;
2568 assert(obj || str);
2569 if (obj) {
2570 assert(_PyUnicode_CHECK(obj));
2571 if (_PyUnicodeWriter_WriteStr(writer, obj) == -1)
2572 return NULL;
2573 }
2574 else {
2575 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
2576 if (!str_obj)
2577 return NULL;
2578 if (_PyUnicodeWriter_WriteStr(writer, str_obj) == -1) {
2579 Py_DECREF(str_obj);
2580 return NULL;
2581 }
2582 Py_DECREF(str_obj);
2583 }
2584 break;
2585 }
2586
2587 case 'S':
2588 {
2589 PyObject *obj = va_arg(*vargs, PyObject *);
2590 PyObject *str;
2591 assert(obj);
2592 str = PyObject_Str(obj);
2593 if (!str)
2594 return NULL;
2595 if (_PyUnicodeWriter_WriteStr(writer, str) == -1) {
2596 Py_DECREF(str);
2597 return NULL;
2598 }
2599 Py_DECREF(str);
2600 break;
2601 }
2602
2603 case 'R':
2604 {
2605 PyObject *obj = va_arg(*vargs, PyObject *);
2606 PyObject *repr;
2607 assert(obj);
2608 repr = PyObject_Repr(obj);
2609 if (!repr)
2610 return NULL;
2611 if (_PyUnicodeWriter_WriteStr(writer, repr) == -1) {
2612 Py_DECREF(repr);
2613 return NULL;
2614 }
2615 Py_DECREF(repr);
2616 break;
2617 }
2618
2619 case 'A':
2620 {
2621 PyObject *obj = va_arg(*vargs, PyObject *);
2622 PyObject *ascii;
2623 assert(obj);
2624 ascii = PyObject_ASCII(obj);
2625 if (!ascii)
2626 return NULL;
2627 if (_PyUnicodeWriter_WriteStr(writer, ascii) == -1) {
2628 Py_DECREF(ascii);
2629 return NULL;
2630 }
2631 Py_DECREF(ascii);
2632 break;
2633 }
2634
2635 case '%':
2636 if (_PyUnicodeWriter_Prepare(writer, 1, '%') == 1)
2637 return NULL;
2638 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '%');
2639 writer->pos++;
2640 break;
2641
2642 default:
2643 /* if we stumble upon an unknown formatting code, copy the rest
2644 of the format string to the output string. (we cannot just
2645 skip the code, since there's no way to know what's in the
2646 argument list) */
2647 len = strlen(p);
2648 if (_PyUnicodeWriter_WriteCstr(writer, p, len) == -1)
2649 return NULL;
2650 f = p+len;
2651 return f;
2652 }
2653
2654 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002655 return f;
2656}
2657
Walter Dörwaldd2034312007-05-18 16:29:38 +00002658PyObject *
2659PyUnicode_FromFormatV(const char *format, va_list vargs)
2660{
Victor Stinnere215d962012-10-06 23:03:36 +02002661 va_list vargs2;
2662 const char *f;
2663 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002664
Victor Stinnere215d962012-10-06 23:03:36 +02002665 _PyUnicodeWriter_Init(&writer, strlen(format) + 100);
2666
2667 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2668 Copy it to be able to pass a reference to a subfunction. */
2669 Py_VA_COPY(vargs2, vargs);
2670
2671 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002672 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002673 f = unicode_fromformat_arg(&writer, f, &vargs2);
2674 if (f == NULL)
2675 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002677 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002678 const char *p;
2679 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002680
Victor Stinnere215d962012-10-06 23:03:36 +02002681 p = f;
2682 do
2683 {
2684 if ((unsigned char)*p > 127) {
2685 PyErr_Format(PyExc_ValueError,
2686 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2687 "string, got a non-ASCII byte: 0x%02x",
2688 (unsigned char)*p);
2689 return NULL;
2690 }
2691 p++;
2692 }
2693 while (*p != '\0' && *p != '%');
2694 len = p - f;
2695
2696 if (*p == '\0')
2697 writer.overallocate = 0;
2698 if (_PyUnicodeWriter_Prepare(&writer, len, 127) == -1)
2699 goto fail;
2700 unicode_write_cstr(writer.buffer, writer.pos, f, len);
2701 writer.pos += len;
2702
2703 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002704 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002705 }
Victor Stinnere215d962012-10-06 23:03:36 +02002706 return _PyUnicodeWriter_Finish(&writer);
2707
2708 fail:
2709 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002710 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002711}
2712
Walter Dörwaldd2034312007-05-18 16:29:38 +00002713PyObject *
2714PyUnicode_FromFormat(const char *format, ...)
2715{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002716 PyObject* ret;
2717 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002718
2719#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002721#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002722 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002723#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 ret = PyUnicode_FromFormatV(format, vargs);
2725 va_end(vargs);
2726 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002727}
2728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002729#ifdef HAVE_WCHAR_H
2730
Victor Stinner5593d8a2010-10-02 11:11:27 +00002731/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2732 convert a Unicode object to a wide character string.
2733
Victor Stinnerd88d9832011-09-06 02:00:05 +02002734 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002735 character) required to convert the unicode object. Ignore size argument.
2736
Victor Stinnerd88d9832011-09-06 02:00:05 +02002737 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002738 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002739 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002740static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002741unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002742 wchar_t *w,
2743 Py_ssize_t size)
2744{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002745 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002746 const wchar_t *wstr;
2747
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002748 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (wstr == NULL)
2750 return -1;
2751
Victor Stinner5593d8a2010-10-02 11:11:27 +00002752 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002753 if (size > res)
2754 size = res + 1;
2755 else
2756 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002758 return res;
2759 }
2760 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002761 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002762}
2763
2764Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002765PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002766 wchar_t *w,
2767 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002768{
2769 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002770 PyErr_BadInternalCall();
2771 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002772 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002773 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002774}
2775
Victor Stinner137c34c2010-09-29 10:25:54 +00002776wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002777PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002778 Py_ssize_t *size)
2779{
2780 wchar_t* buffer;
2781 Py_ssize_t buflen;
2782
2783 if (unicode == NULL) {
2784 PyErr_BadInternalCall();
2785 return NULL;
2786 }
2787
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002788 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 if (buflen == -1)
2790 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002791 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002792 PyErr_NoMemory();
2793 return NULL;
2794 }
2795
Victor Stinner137c34c2010-09-29 10:25:54 +00002796 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2797 if (buffer == NULL) {
2798 PyErr_NoMemory();
2799 return NULL;
2800 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002801 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002802 if (buflen == -1) {
2803 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002804 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002805 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002806 if (size != NULL)
2807 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002808 return buffer;
2809}
2810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002811#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002812
Alexander Belopolsky40018472011-02-26 01:02:56 +00002813PyObject *
2814PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002815{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002816 PyObject *v;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002817 void *data;
2818 int kind;
2819
Victor Stinner8faf8212011-12-08 22:14:11 +01002820 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002821 PyErr_SetString(PyExc_ValueError,
2822 "chr() arg not in range(0x110000)");
2823 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002824 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002825
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002826 if ((Py_UCS4)ordinal < 256)
2827 return get_latin1_char((unsigned char)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002829 v = PyUnicode_New(1, ordinal);
2830 if (v == NULL)
2831 return NULL;
Victor Stinner69ed0f42013-04-09 21:48:24 +02002832 kind = PyUnicode_KIND(v);
2833 data = PyUnicode_DATA(v);
2834 PyUnicode_WRITE(kind, data, 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002835 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002836 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002837}
2838
Alexander Belopolsky40018472011-02-26 01:02:56 +00002839PyObject *
2840PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002841{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002842 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002843 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002844 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002845 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002846 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002847 Py_INCREF(obj);
2848 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002849 }
2850 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002851 /* For a Unicode subtype that's not a Unicode object,
2852 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002853 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002854 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002855 PyErr_Format(PyExc_TypeError,
2856 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002857 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002858 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002859}
2860
Alexander Belopolsky40018472011-02-26 01:02:56 +00002861PyObject *
2862PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002863 const char *encoding,
2864 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002865{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002866 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002867 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002868
Guido van Rossumd57fd912000-03-10 22:53:23 +00002869 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002870 PyErr_BadInternalCall();
2871 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002872 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002873
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002874 /* Decoding bytes objects is the most common case and should be fast */
2875 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002876 if (PyBytes_GET_SIZE(obj) == 0)
2877 _Py_RETURN_UNICODE_EMPTY();
2878 v = PyUnicode_Decode(
2879 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2880 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002881 return v;
2882 }
2883
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002884 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 PyErr_SetString(PyExc_TypeError,
2886 "decoding str is not supported");
2887 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002888 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002889
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002890 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2891 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2892 PyErr_Format(PyExc_TypeError,
2893 "coercing to str: need bytes, bytearray "
2894 "or buffer-like object, %.80s found",
2895 Py_TYPE(obj)->tp_name);
2896 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002897 }
Tim Petersced69f82003-09-16 20:30:58 +00002898
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002899 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002900 PyBuffer_Release(&buffer);
2901 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002902 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002903
Serhiy Storchaka05997252013-01-26 12:14:02 +02002904 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002905 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002906 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907}
2908
Victor Stinner600d3be2010-06-10 12:00:55 +00002909/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002910 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2911 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002912int
2913_Py_normalize_encoding(const char *encoding,
2914 char *lower,
2915 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002916{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002917 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002918 char *l;
2919 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002920
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002921 if (encoding == NULL) {
2922 strcpy(lower, "utf-8");
2923 return 1;
2924 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002925 e = encoding;
2926 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002927 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002928 while (*e) {
2929 if (l == l_end)
2930 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002931 if (Py_ISUPPER(*e)) {
2932 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002933 }
2934 else if (*e == '_') {
2935 *l++ = '-';
2936 e++;
2937 }
2938 else {
2939 *l++ = *e++;
2940 }
2941 }
2942 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002943 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002944}
2945
Alexander Belopolsky40018472011-02-26 01:02:56 +00002946PyObject *
2947PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002948 Py_ssize_t size,
2949 const char *encoding,
2950 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002951{
2952 PyObject *buffer = NULL, *unicode;
2953 Py_buffer info;
2954 char lower[11]; /* Enough for any encoding shortcut */
2955
Fred Drakee4315f52000-05-09 19:53:39 +00002956 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002957 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002958 if ((strcmp(lower, "utf-8") == 0) ||
2959 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002960 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002961 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002962 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002963 (strcmp(lower, "iso-8859-1") == 0))
2964 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002965#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002966 else if (strcmp(lower, "mbcs") == 0)
2967 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002968#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002969 else if (strcmp(lower, "ascii") == 0)
2970 return PyUnicode_DecodeASCII(s, size, errors);
2971 else if (strcmp(lower, "utf-16") == 0)
2972 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2973 else if (strcmp(lower, "utf-32") == 0)
2974 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2975 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002976
2977 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002978 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002979 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002980 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002981 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982 if (buffer == NULL)
2983 goto onError;
2984 unicode = PyCodec_Decode(buffer, encoding, errors);
2985 if (unicode == NULL)
2986 goto onError;
2987 if (!PyUnicode_Check(unicode)) {
2988 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002989 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002990 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002991 Py_DECREF(unicode);
2992 goto onError;
2993 }
2994 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002995 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002996
Benjamin Peterson29060642009-01-31 22:14:21 +00002997 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002998 Py_XDECREF(buffer);
2999 return NULL;
3000}
3001
Alexander Belopolsky40018472011-02-26 01:02:56 +00003002PyObject *
3003PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003004 const char *encoding,
3005 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003006{
3007 PyObject *v;
3008
3009 if (!PyUnicode_Check(unicode)) {
3010 PyErr_BadArgument();
3011 goto onError;
3012 }
3013
3014 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003015 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003016
3017 /* Decode via the codec registry */
3018 v = PyCodec_Decode(unicode, encoding, errors);
3019 if (v == NULL)
3020 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003021 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003022
Benjamin Peterson29060642009-01-31 22:14:21 +00003023 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003024 return NULL;
3025}
3026
Alexander Belopolsky40018472011-02-26 01:02:56 +00003027PyObject *
3028PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003029 const char *encoding,
3030 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003031{
3032 PyObject *v;
3033
3034 if (!PyUnicode_Check(unicode)) {
3035 PyErr_BadArgument();
3036 goto onError;
3037 }
3038
3039 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003040 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003041
3042 /* Decode via the codec registry */
3043 v = PyCodec_Decode(unicode, encoding, errors);
3044 if (v == NULL)
3045 goto onError;
3046 if (!PyUnicode_Check(v)) {
3047 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003048 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003049 Py_TYPE(v)->tp_name);
3050 Py_DECREF(v);
3051 goto onError;
3052 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003053 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003054
Benjamin Peterson29060642009-01-31 22:14:21 +00003055 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003056 return NULL;
3057}
3058
Alexander Belopolsky40018472011-02-26 01:02:56 +00003059PyObject *
3060PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003061 Py_ssize_t size,
3062 const char *encoding,
3063 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003064{
3065 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003066
Guido van Rossumd57fd912000-03-10 22:53:23 +00003067 unicode = PyUnicode_FromUnicode(s, size);
3068 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003069 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003070 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3071 Py_DECREF(unicode);
3072 return v;
3073}
3074
Alexander Belopolsky40018472011-02-26 01:02:56 +00003075PyObject *
3076PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003077 const char *encoding,
3078 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003079{
3080 PyObject *v;
3081
3082 if (!PyUnicode_Check(unicode)) {
3083 PyErr_BadArgument();
3084 goto onError;
3085 }
3086
3087 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003088 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003089
3090 /* Encode via the codec registry */
3091 v = PyCodec_Encode(unicode, encoding, errors);
3092 if (v == NULL)
3093 goto onError;
3094 return v;
3095
Benjamin Peterson29060642009-01-31 22:14:21 +00003096 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003097 return NULL;
3098}
3099
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003100static size_t
3101wcstombs_errorpos(const wchar_t *wstr)
3102{
3103 size_t len;
3104#if SIZEOF_WCHAR_T == 2
3105 wchar_t buf[3];
3106#else
3107 wchar_t buf[2];
3108#endif
3109 char outbuf[MB_LEN_MAX];
3110 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003111
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003112#if SIZEOF_WCHAR_T == 2
3113 buf[2] = 0;
3114#else
3115 buf[1] = 0;
3116#endif
3117 start = wstr;
3118 while (*wstr != L'\0')
3119 {
3120 previous = wstr;
3121#if SIZEOF_WCHAR_T == 2
3122 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3123 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3124 {
3125 buf[0] = wstr[0];
3126 buf[1] = wstr[1];
3127 wstr += 2;
3128 }
3129 else {
3130 buf[0] = *wstr;
3131 buf[1] = 0;
3132 wstr++;
3133 }
3134#else
3135 buf[0] = *wstr;
3136 wstr++;
3137#endif
3138 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003139 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003140 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003141 }
3142
3143 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003144 return 0;
3145}
3146
Victor Stinner1b579672011-12-17 05:47:23 +01003147static int
3148locale_error_handler(const char *errors, int *surrogateescape)
3149{
3150 if (errors == NULL) {
3151 *surrogateescape = 0;
3152 return 0;
3153 }
3154
3155 if (strcmp(errors, "strict") == 0) {
3156 *surrogateescape = 0;
3157 return 0;
3158 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003159 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003160 *surrogateescape = 1;
3161 return 0;
3162 }
3163 PyErr_Format(PyExc_ValueError,
3164 "only 'strict' and 'surrogateescape' error handlers "
3165 "are supported, not '%s'",
3166 errors);
3167 return -1;
3168}
3169
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003170PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003171PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003172{
3173 Py_ssize_t wlen, wlen2;
3174 wchar_t *wstr;
3175 PyObject *bytes = NULL;
3176 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003177 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003178 PyObject *exc;
3179 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003180 int surrogateescape;
3181
3182 if (locale_error_handler(errors, &surrogateescape) < 0)
3183 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003184
3185 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3186 if (wstr == NULL)
3187 return NULL;
3188
3189 wlen2 = wcslen(wstr);
3190 if (wlen2 != wlen) {
3191 PyMem_Free(wstr);
3192 PyErr_SetString(PyExc_TypeError, "embedded null character");
3193 return NULL;
3194 }
3195
3196 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003197 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 char *str;
3199
3200 str = _Py_wchar2char(wstr, &error_pos);
3201 if (str == NULL) {
3202 if (error_pos == (size_t)-1) {
3203 PyErr_NoMemory();
3204 PyMem_Free(wstr);
3205 return NULL;
3206 }
3207 else {
3208 goto encode_error;
3209 }
3210 }
3211 PyMem_Free(wstr);
3212
3213 bytes = PyBytes_FromString(str);
3214 PyMem_Free(str);
3215 }
3216 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003217 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003218 size_t len, len2;
3219
3220 len = wcstombs(NULL, wstr, 0);
3221 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003222 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223 goto encode_error;
3224 }
3225
3226 bytes = PyBytes_FromStringAndSize(NULL, len);
3227 if (bytes == NULL) {
3228 PyMem_Free(wstr);
3229 return NULL;
3230 }
3231
3232 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3233 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003234 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003235 goto encode_error;
3236 }
3237 PyMem_Free(wstr);
3238 }
3239 return bytes;
3240
3241encode_error:
3242 errmsg = strerror(errno);
3243 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003244
3245 if (error_pos == (size_t)-1)
3246 error_pos = wcstombs_errorpos(wstr);
3247
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003248 PyMem_Free(wstr);
3249 Py_XDECREF(bytes);
3250
Victor Stinner2f197072011-12-17 07:08:30 +01003251 if (errmsg != NULL) {
3252 size_t errlen;
3253 wstr = _Py_char2wchar(errmsg, &errlen);
3254 if (wstr != NULL) {
3255 reason = PyUnicode_FromWideChar(wstr, errlen);
3256 PyMem_Free(wstr);
3257 } else
3258 errmsg = NULL;
3259 }
3260 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003261 reason = PyUnicode_FromString(
3262 "wcstombs() encountered an unencodable "
3263 "wide character");
3264 if (reason == NULL)
3265 return NULL;
3266
3267 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3268 "locale", unicode,
3269 (Py_ssize_t)error_pos,
3270 (Py_ssize_t)(error_pos+1),
3271 reason);
3272 Py_DECREF(reason);
3273 if (exc != NULL) {
3274 PyCodec_StrictErrors(exc);
3275 Py_XDECREF(exc);
3276 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 return NULL;
3278}
3279
Victor Stinnerad158722010-10-27 00:25:46 +00003280PyObject *
3281PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003282{
Victor Stinner99b95382011-07-04 14:23:54 +02003283#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003284 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003285#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003286 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003287#else
Victor Stinner793b5312011-04-27 00:24:21 +02003288 PyInterpreterState *interp = PyThreadState_GET()->interp;
3289 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3290 cannot use it to encode and decode filenames before it is loaded. Load
3291 the Python codec requires to encode at least its own filename. Use the C
3292 version of the locale codec until the codec registry is initialized and
3293 the Python codec is loaded.
3294
3295 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3296 cannot only rely on it: check also interp->fscodec_initialized for
3297 subinterpreters. */
3298 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003299 return PyUnicode_AsEncodedString(unicode,
3300 Py_FileSystemDefaultEncoding,
3301 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003302 }
3303 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003304 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003305 }
Victor Stinnerad158722010-10-27 00:25:46 +00003306#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003307}
3308
Alexander Belopolsky40018472011-02-26 01:02:56 +00003309PyObject *
3310PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003311 const char *encoding,
3312 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003313{
3314 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003315 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003316
Guido van Rossumd57fd912000-03-10 22:53:23 +00003317 if (!PyUnicode_Check(unicode)) {
3318 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003319 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003320 }
Fred Drakee4315f52000-05-09 19:53:39 +00003321
Fred Drakee4315f52000-05-09 19:53:39 +00003322 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003323 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003324 if ((strcmp(lower, "utf-8") == 0) ||
3325 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003326 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003327 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003328 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003329 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003330 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003331 }
Victor Stinner37296e82010-06-10 13:36:23 +00003332 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003333 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003334 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003335 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003336#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003337 else if (strcmp(lower, "mbcs") == 0)
3338 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003339#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003340 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003342 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003343
3344 /* Encode via the codec registry */
3345 v = PyCodec_Encode(unicode, encoding, errors);
3346 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003347 return NULL;
3348
3349 /* The normal path */
3350 if (PyBytes_Check(v))
3351 return v;
3352
3353 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003354 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003355 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003356 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003357
3358 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3359 "encoder %s returned bytearray instead of bytes",
3360 encoding);
3361 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003362 Py_DECREF(v);
3363 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003364 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003365
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003366 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3367 Py_DECREF(v);
3368 return b;
3369 }
3370
3371 PyErr_Format(PyExc_TypeError,
3372 "encoder did not return a bytes object (type=%.400s)",
3373 Py_TYPE(v)->tp_name);
3374 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003375 return NULL;
3376}
3377
Alexander Belopolsky40018472011-02-26 01:02:56 +00003378PyObject *
3379PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003380 const char *encoding,
3381 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003382{
3383 PyObject *v;
3384
3385 if (!PyUnicode_Check(unicode)) {
3386 PyErr_BadArgument();
3387 goto onError;
3388 }
3389
3390 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003391 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003392
3393 /* Encode via the codec registry */
3394 v = PyCodec_Encode(unicode, encoding, errors);
3395 if (v == NULL)
3396 goto onError;
3397 if (!PyUnicode_Check(v)) {
3398 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003399 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003400 Py_TYPE(v)->tp_name);
3401 Py_DECREF(v);
3402 goto onError;
3403 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003404 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003405
Benjamin Peterson29060642009-01-31 22:14:21 +00003406 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003407 return NULL;
3408}
3409
Victor Stinner2f197072011-12-17 07:08:30 +01003410static size_t
3411mbstowcs_errorpos(const char *str, size_t len)
3412{
3413#ifdef HAVE_MBRTOWC
3414 const char *start = str;
3415 mbstate_t mbs;
3416 size_t converted;
3417 wchar_t ch;
3418
3419 memset(&mbs, 0, sizeof mbs);
3420 while (len)
3421 {
3422 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3423 if (converted == 0)
3424 /* Reached end of string */
3425 break;
3426 if (converted == (size_t)-1 || converted == (size_t)-2) {
3427 /* Conversion error or incomplete character */
3428 return str - start;
3429 }
3430 else {
3431 str += converted;
3432 len -= converted;
3433 }
3434 }
3435 /* failed to find the undecodable byte sequence */
3436 return 0;
3437#endif
3438 return 0;
3439}
3440
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003441PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003442PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003443 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003444{
3445 wchar_t smallbuf[256];
3446 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3447 wchar_t *wstr;
3448 size_t wlen, wlen2;
3449 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003450 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003451 size_t error_pos;
3452 char *errmsg;
3453 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003454
3455 if (locale_error_handler(errors, &surrogateescape) < 0)
3456 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003457
3458 if (str[len] != '\0' || len != strlen(str)) {
3459 PyErr_SetString(PyExc_TypeError, "embedded null character");
3460 return NULL;
3461 }
3462
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003463 if (surrogateescape) {
3464 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003465 wstr = _Py_char2wchar(str, &wlen);
3466 if (wstr == NULL) {
3467 if (wlen == (size_t)-1)
3468 PyErr_NoMemory();
3469 else
3470 PyErr_SetFromErrno(PyExc_OSError);
3471 return NULL;
3472 }
3473
3474 unicode = PyUnicode_FromWideChar(wstr, wlen);
3475 PyMem_Free(wstr);
3476 }
3477 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003478 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003479#ifndef HAVE_BROKEN_MBSTOWCS
3480 wlen = mbstowcs(NULL, str, 0);
3481#else
3482 wlen = len;
3483#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003484 if (wlen == (size_t)-1)
3485 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003486 if (wlen+1 <= smallbuf_len) {
3487 wstr = smallbuf;
3488 }
3489 else {
3490 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3491 return PyErr_NoMemory();
3492
3493 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3494 if (!wstr)
3495 return PyErr_NoMemory();
3496 }
3497
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003498 wlen2 = mbstowcs(wstr, str, wlen+1);
3499 if (wlen2 == (size_t)-1) {
3500 if (wstr != smallbuf)
3501 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003502 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003503 }
3504#ifdef HAVE_BROKEN_MBSTOWCS
3505 assert(wlen2 == wlen);
3506#endif
3507 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3508 if (wstr != smallbuf)
3509 PyMem_Free(wstr);
3510 }
3511 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003512
3513decode_error:
3514 errmsg = strerror(errno);
3515 assert(errmsg != NULL);
3516
3517 error_pos = mbstowcs_errorpos(str, len);
3518 if (errmsg != NULL) {
3519 size_t errlen;
3520 wstr = _Py_char2wchar(errmsg, &errlen);
3521 if (wstr != NULL) {
3522 reason = PyUnicode_FromWideChar(wstr, errlen);
3523 PyMem_Free(wstr);
3524 } else
3525 errmsg = NULL;
3526 }
3527 if (errmsg == NULL)
3528 reason = PyUnicode_FromString(
3529 "mbstowcs() encountered an invalid multibyte sequence");
3530 if (reason == NULL)
3531 return NULL;
3532
3533 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3534 "locale", str, len,
3535 (Py_ssize_t)error_pos,
3536 (Py_ssize_t)(error_pos+1),
3537 reason);
3538 Py_DECREF(reason);
3539 if (exc != NULL) {
3540 PyCodec_StrictErrors(exc);
3541 Py_XDECREF(exc);
3542 }
3543 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003544}
3545
3546PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003547PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003548{
3549 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003550 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003551}
3552
3553
3554PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003555PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003556 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003557 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3558}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003559
Christian Heimes5894ba72007-11-04 11:43:14 +00003560PyObject*
3561PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3562{
Victor Stinner99b95382011-07-04 14:23:54 +02003563#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003564 return PyUnicode_DecodeMBCS(s, size, NULL);
3565#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003566 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003567#else
Victor Stinner793b5312011-04-27 00:24:21 +02003568 PyInterpreterState *interp = PyThreadState_GET()->interp;
3569 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3570 cannot use it to encode and decode filenames before it is loaded. Load
3571 the Python codec requires to encode at least its own filename. Use the C
3572 version of the locale codec until the codec registry is initialized and
3573 the Python codec is loaded.
3574
3575 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3576 cannot only rely on it: check also interp->fscodec_initialized for
3577 subinterpreters. */
3578 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003579 return PyUnicode_Decode(s, size,
3580 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003581 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003582 }
3583 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003584 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003585 }
Victor Stinnerad158722010-10-27 00:25:46 +00003586#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003587}
3588
Martin v. Löwis011e8422009-05-05 04:43:17 +00003589
3590int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003591_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003592{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003593 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003594
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003595 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003596 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003597 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3598 PyUnicode_GET_LENGTH(str), '\0', 1);
3599 if (pos == -1)
3600 return 0;
3601 else
3602 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003603}
3604
Antoine Pitrou13348842012-01-29 18:36:34 +01003605int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003606PyUnicode_FSConverter(PyObject* arg, void* addr)
3607{
3608 PyObject *output = NULL;
3609 Py_ssize_t size;
3610 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003611 if (arg == NULL) {
3612 Py_DECREF(*(PyObject**)addr);
3613 return 1;
3614 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003615 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003616 output = arg;
3617 Py_INCREF(output);
3618 }
3619 else {
3620 arg = PyUnicode_FromObject(arg);
3621 if (!arg)
3622 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003623 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003624 Py_DECREF(arg);
3625 if (!output)
3626 return 0;
3627 if (!PyBytes_Check(output)) {
3628 Py_DECREF(output);
3629 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3630 return 0;
3631 }
3632 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003633 size = PyBytes_GET_SIZE(output);
3634 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003635 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003636 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003637 Py_DECREF(output);
3638 return 0;
3639 }
3640 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003641 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003642}
3643
3644
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003645int
3646PyUnicode_FSDecoder(PyObject* arg, void* addr)
3647{
3648 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003649 if (arg == NULL) {
3650 Py_DECREF(*(PyObject**)addr);
3651 return 1;
3652 }
3653 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003654 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003655 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003656 output = arg;
3657 Py_INCREF(output);
3658 }
3659 else {
3660 arg = PyBytes_FromObject(arg);
3661 if (!arg)
3662 return 0;
3663 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3664 PyBytes_GET_SIZE(arg));
3665 Py_DECREF(arg);
3666 if (!output)
3667 return 0;
3668 if (!PyUnicode_Check(output)) {
3669 Py_DECREF(output);
3670 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3671 return 0;
3672 }
3673 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003674 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003675 Py_DECREF(output);
3676 return 0;
3677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003678 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003679 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003680 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3681 Py_DECREF(output);
3682 return 0;
3683 }
3684 *(PyObject**)addr = output;
3685 return Py_CLEANUP_SUPPORTED;
3686}
3687
3688
Martin v. Löwis5b222132007-06-10 09:51:05 +00003689char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003690PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003691{
Christian Heimesf3863112007-11-22 07:46:41 +00003692 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003693
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003694 if (!PyUnicode_Check(unicode)) {
3695 PyErr_BadArgument();
3696 return NULL;
3697 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003698 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003699 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003700
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003701 if (PyUnicode_UTF8(unicode) == NULL) {
3702 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003703 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3704 if (bytes == NULL)
3705 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003706 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3707 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003708 Py_DECREF(bytes);
3709 return NULL;
3710 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003711 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3712 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3713 PyBytes_AS_STRING(bytes),
3714 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003715 Py_DECREF(bytes);
3716 }
3717
3718 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003719 *psize = PyUnicode_UTF8_LENGTH(unicode);
3720 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003721}
3722
3723char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003724PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3727}
3728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003729Py_UNICODE *
3730PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003732 const unsigned char *one_byte;
3733#if SIZEOF_WCHAR_T == 4
3734 const Py_UCS2 *two_bytes;
3735#else
3736 const Py_UCS4 *four_bytes;
3737 const Py_UCS4 *ucs4_end;
3738 Py_ssize_t num_surrogates;
3739#endif
3740 wchar_t *w;
3741 wchar_t *wchar_end;
3742
3743 if (!PyUnicode_Check(unicode)) {
3744 PyErr_BadArgument();
3745 return NULL;
3746 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003747 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003748 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003749 assert(_PyUnicode_KIND(unicode) != 0);
3750 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003752 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003753#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003754 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3755 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756 num_surrogates = 0;
3757
3758 for (; four_bytes < ucs4_end; ++four_bytes) {
3759 if (*four_bytes > 0xFFFF)
3760 ++num_surrogates;
3761 }
3762
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003763 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3764 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3765 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 PyErr_NoMemory();
3767 return NULL;
3768 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003769 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003770
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003771 w = _PyUnicode_WSTR(unicode);
3772 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3773 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003774 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3775 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003776 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003778 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3779 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780 }
3781 else
3782 *w = *four_bytes;
3783
3784 if (w > wchar_end) {
3785 assert(0 && "Miscalculated string end");
3786 }
3787 }
3788 *w = 0;
3789#else
3790 /* sizeof(wchar_t) == 4 */
3791 Py_FatalError("Impossible unicode object state, wstr and str "
3792 "should share memory already.");
3793 return NULL;
3794#endif
3795 }
3796 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003797 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3798 (_PyUnicode_LENGTH(unicode) + 1));
3799 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003800 PyErr_NoMemory();
3801 return NULL;
3802 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003803 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3804 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3805 w = _PyUnicode_WSTR(unicode);
3806 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003807
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3809 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003810 for (; w < wchar_end; ++one_byte, ++w)
3811 *w = *one_byte;
3812 /* null-terminate the wstr */
3813 *w = 0;
3814 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003815 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003817 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818 for (; w < wchar_end; ++two_bytes, ++w)
3819 *w = *two_bytes;
3820 /* null-terminate the wstr */
3821 *w = 0;
3822#else
3823 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003824 PyObject_FREE(_PyUnicode_WSTR(unicode));
3825 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826 Py_FatalError("Impossible unicode object state, wstr "
3827 "and str should share memory already.");
3828 return NULL;
3829#endif
3830 }
3831 else {
3832 assert(0 && "This should never happen.");
3833 }
3834 }
3835 }
3836 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003837 *size = PyUnicode_WSTR_LENGTH(unicode);
3838 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003839}
3840
Alexander Belopolsky40018472011-02-26 01:02:56 +00003841Py_UNICODE *
3842PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003843{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003845}
3846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003847
Alexander Belopolsky40018472011-02-26 01:02:56 +00003848Py_ssize_t
3849PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003850{
3851 if (!PyUnicode_Check(unicode)) {
3852 PyErr_BadArgument();
3853 goto onError;
3854 }
3855 return PyUnicode_GET_SIZE(unicode);
3856
Benjamin Peterson29060642009-01-31 22:14:21 +00003857 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003858 return -1;
3859}
3860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861Py_ssize_t
3862PyUnicode_GetLength(PyObject *unicode)
3863{
Victor Stinner07621332012-06-16 04:53:46 +02003864 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 PyErr_BadArgument();
3866 return -1;
3867 }
Victor Stinner07621332012-06-16 04:53:46 +02003868 if (PyUnicode_READY(unicode) == -1)
3869 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003870 return PyUnicode_GET_LENGTH(unicode);
3871}
3872
3873Py_UCS4
3874PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3875{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003876 void *data;
3877 int kind;
3878
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003879 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3880 PyErr_BadArgument();
3881 return (Py_UCS4)-1;
3882 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003883 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003884 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885 return (Py_UCS4)-1;
3886 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003887 data = PyUnicode_DATA(unicode);
3888 kind = PyUnicode_KIND(unicode);
3889 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890}
3891
3892int
3893PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3894{
3895 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003896 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003897 return -1;
3898 }
Victor Stinner488fa492011-12-12 00:01:39 +01003899 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003900 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003901 PyErr_SetString(PyExc_IndexError, "string index out of range");
3902 return -1;
3903 }
Victor Stinner488fa492011-12-12 00:01:39 +01003904 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003905 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003906 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3907 PyErr_SetString(PyExc_ValueError, "character out of range");
3908 return -1;
3909 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3911 index, ch);
3912 return 0;
3913}
3914
Alexander Belopolsky40018472011-02-26 01:02:56 +00003915const char *
3916PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003917{
Victor Stinner42cb4622010-09-01 19:39:01 +00003918 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003919}
3920
Victor Stinner554f3f02010-06-16 23:33:54 +00003921/* create or adjust a UnicodeDecodeError */
3922static void
3923make_decode_exception(PyObject **exceptionObject,
3924 const char *encoding,
3925 const char *input, Py_ssize_t length,
3926 Py_ssize_t startpos, Py_ssize_t endpos,
3927 const char *reason)
3928{
3929 if (*exceptionObject == NULL) {
3930 *exceptionObject = PyUnicodeDecodeError_Create(
3931 encoding, input, length, startpos, endpos, reason);
3932 }
3933 else {
3934 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3935 goto onError;
3936 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3937 goto onError;
3938 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3939 goto onError;
3940 }
3941 return;
3942
3943onError:
3944 Py_DECREF(*exceptionObject);
3945 *exceptionObject = NULL;
3946}
3947
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003948#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003949/* error handling callback helper:
3950 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003951 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003952 and adjust various state variables.
3953 return 0 on success, -1 on error
3954*/
3955
Alexander Belopolsky40018472011-02-26 01:02:56 +00003956static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003957unicode_decode_call_errorhandler_wchar(
3958 const char *errors, PyObject **errorHandler,
3959 const char *encoding, const char *reason,
3960 const char **input, const char **inend, Py_ssize_t *startinpos,
3961 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3962 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003963{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003964 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003965
3966 PyObject *restuple = NULL;
3967 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003968 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003969 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003970 Py_ssize_t requiredsize;
3971 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003972 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003973 wchar_t *repwstr;
3974 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003975
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003976 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3977 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01003978
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003979 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003980 *errorHandler = PyCodec_LookupError(errors);
3981 if (*errorHandler == NULL)
3982 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003983 }
3984
Victor Stinner554f3f02010-06-16 23:33:54 +00003985 make_decode_exception(exceptionObject,
3986 encoding,
3987 *input, *inend - *input,
3988 *startinpos, *endinpos,
3989 reason);
3990 if (*exceptionObject == NULL)
3991 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003992
3993 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3994 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003995 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003996 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003997 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003998 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003999 }
4000 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004001 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004002
4003 /* Copy back the bytes variables, which might have been modified by the
4004 callback */
4005 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4006 if (!inputobj)
4007 goto onError;
4008 if (!PyBytes_Check(inputobj)) {
4009 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4010 }
4011 *input = PyBytes_AS_STRING(inputobj);
4012 insize = PyBytes_GET_SIZE(inputobj);
4013 *inend = *input + insize;
4014 /* we can DECREF safely, as the exception has another reference,
4015 so the object won't go away. */
4016 Py_DECREF(inputobj);
4017
4018 if (newpos<0)
4019 newpos = insize+newpos;
4020 if (newpos<0 || newpos>insize) {
4021 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4022 goto onError;
4023 }
4024
4025 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4026 if (repwstr == NULL)
4027 goto onError;
4028 /* need more space? (at least enough for what we
4029 have+the replacement+the rest of the string (starting
4030 at the new input position), so we won't have to check space
4031 when there are no errors in the rest of the string) */
4032 requiredsize = *outpos + repwlen + insize-newpos;
4033 if (requiredsize > outsize) {
4034 if (requiredsize < 2*outsize)
4035 requiredsize = 2*outsize;
4036 if (unicode_resize(output, requiredsize) < 0)
4037 goto onError;
4038 }
4039 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4040 *outpos += repwlen;
4041
4042 *endinpos = newpos;
4043 *inptr = *input + newpos;
4044
4045 /* we made it! */
4046 Py_XDECREF(restuple);
4047 return 0;
4048
4049 onError:
4050 Py_XDECREF(restuple);
4051 return -1;
4052}
4053#endif /* HAVE_MBCS */
4054
4055static int
4056unicode_decode_call_errorhandler_writer(
4057 const char *errors, PyObject **errorHandler,
4058 const char *encoding, const char *reason,
4059 const char **input, const char **inend, Py_ssize_t *startinpos,
4060 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4061 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4062{
4063 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4064
4065 PyObject *restuple = NULL;
4066 PyObject *repunicode = NULL;
4067 Py_ssize_t insize;
4068 Py_ssize_t newpos;
4069 PyObject *inputobj = NULL;
4070
4071 if (*errorHandler == NULL) {
4072 *errorHandler = PyCodec_LookupError(errors);
4073 if (*errorHandler == NULL)
4074 goto onError;
4075 }
4076
4077 make_decode_exception(exceptionObject,
4078 encoding,
4079 *input, *inend - *input,
4080 *startinpos, *endinpos,
4081 reason);
4082 if (*exceptionObject == NULL)
4083 goto onError;
4084
4085 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4086 if (restuple == NULL)
4087 goto onError;
4088 if (!PyTuple_Check(restuple)) {
4089 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4090 goto onError;
4091 }
4092 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004093 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004094
4095 /* Copy back the bytes variables, which might have been modified by the
4096 callback */
4097 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4098 if (!inputobj)
4099 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004100 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004101 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004102 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004103 *input = PyBytes_AS_STRING(inputobj);
4104 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004105 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004106 /* we can DECREF safely, as the exception has another reference,
4107 so the object won't go away. */
4108 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004112 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004113 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4114 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004115 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004116
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004117 writer->overallocate = 1;
4118 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4119 return
4120
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004121 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004122 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004123
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004124 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004125 Py_XDECREF(restuple);
4126 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004127
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004129 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004130 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004131}
4132
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004133/* --- UTF-7 Codec -------------------------------------------------------- */
4134
Antoine Pitrou244651a2009-05-04 18:56:13 +00004135/* See RFC2152 for details. We encode conservatively and decode liberally. */
4136
4137/* Three simple macros defining base-64. */
4138
4139/* Is c a base-64 character? */
4140
4141#define IS_BASE64(c) \
4142 (((c) >= 'A' && (c) <= 'Z') || \
4143 ((c) >= 'a' && (c) <= 'z') || \
4144 ((c) >= '0' && (c) <= '9') || \
4145 (c) == '+' || (c) == '/')
4146
4147/* given that c is a base-64 character, what is its base-64 value? */
4148
4149#define FROM_BASE64(c) \
4150 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4151 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4152 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4153 (c) == '+' ? 62 : 63)
4154
4155/* What is the base-64 character of the bottom 6 bits of n? */
4156
4157#define TO_BASE64(n) \
4158 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4159
4160/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4161 * decoded as itself. We are permissive on decoding; the only ASCII
4162 * byte not decoding to itself is the + which begins a base64
4163 * string. */
4164
4165#define DECODE_DIRECT(c) \
4166 ((c) <= 127 && (c) != '+')
4167
4168/* The UTF-7 encoder treats ASCII characters differently according to
4169 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4170 * the above). See RFC2152. This array identifies these different
4171 * sets:
4172 * 0 : "Set D"
4173 * alphanumeric and '(),-./:?
4174 * 1 : "Set O"
4175 * !"#$%&*;<=>@[]^_`{|}
4176 * 2 : "whitespace"
4177 * ht nl cr sp
4178 * 3 : special (must be base64 encoded)
4179 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4180 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004181
Tim Petersced69f82003-09-16 20:30:58 +00004182static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004183char utf7_category[128] = {
4184/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4185 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4186/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4187 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4188/* sp ! " # $ % & ' ( ) * + , - . / */
4189 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4190/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4191 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4192/* @ A B C D E F G H I J K L M N O */
4193 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4194/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4195 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4196/* ` a b c d e f g h i j k l m n o */
4197 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4198/* p q r s t u v w x y z { | } ~ del */
4199 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004200};
4201
Antoine Pitrou244651a2009-05-04 18:56:13 +00004202/* ENCODE_DIRECT: this character should be encoded as itself. The
4203 * answer depends on whether we are encoding set O as itself, and also
4204 * on whether we are encoding whitespace as itself. RFC2152 makes it
4205 * clear that the answers to these questions vary between
4206 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004207
Antoine Pitrou244651a2009-05-04 18:56:13 +00004208#define ENCODE_DIRECT(c, directO, directWS) \
4209 ((c) < 128 && (c) > 0 && \
4210 ((utf7_category[(c)] == 0) || \
4211 (directWS && (utf7_category[(c)] == 2)) || \
4212 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004213
Alexander Belopolsky40018472011-02-26 01:02:56 +00004214PyObject *
4215PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004216 Py_ssize_t size,
4217 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004218{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004219 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4220}
4221
Antoine Pitrou244651a2009-05-04 18:56:13 +00004222/* The decoder. The only state we preserve is our read position,
4223 * i.e. how many characters we have consumed. So if we end in the
4224 * middle of a shift sequence we have to back off the read position
4225 * and the output to the beginning of the sequence, otherwise we lose
4226 * all the shift state (seen bits, number of bits seen, high
4227 * surrogate). */
4228
Alexander Belopolsky40018472011-02-26 01:02:56 +00004229PyObject *
4230PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004231 Py_ssize_t size,
4232 const char *errors,
4233 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004234{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004235 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004236 Py_ssize_t startinpos;
4237 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004239 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004240 const char *errmsg = "";
4241 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004242 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004243 unsigned int base64bits = 0;
4244 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004245 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004246 PyObject *errorHandler = NULL;
4247 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004248
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004249 if (size == 0) {
4250 if (consumed)
4251 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004252 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004253 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004254
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004255 /* Start off assuming it's all ASCII. Widen later as necessary. */
4256 _PyUnicodeWriter_Init(&writer, 0);
4257 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
4258 goto onError;
4259
4260 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261 e = s + size;
4262
4263 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004264 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004265 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004266 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004267
Antoine Pitrou244651a2009-05-04 18:56:13 +00004268 if (inShift) { /* in a base-64 section */
4269 if (IS_BASE64(ch)) { /* consume a base-64 character */
4270 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4271 base64bits += 6;
4272 s++;
4273 if (base64bits >= 16) {
4274 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004275 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276 base64bits -= 16;
4277 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4278 if (surrogate) {
4279 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004280 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4281 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004282 if (_PyUnicodeWriter_Prepare(&writer, 1, ch2) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004283 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004284 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch2);
4285 writer.pos++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004287 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288 }
4289 else {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004290 if (_PyUnicodeWriter_Prepare(&writer, 1, surrogate) == -1)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004291 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004292 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, surrogate);
4293 writer.pos++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004295 }
4296 }
Victor Stinner551ac952011-11-29 22:58:13 +01004297 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004298 /* first surrogate */
4299 surrogate = outCh;
4300 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301 else {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004302 if (_PyUnicodeWriter_Prepare(&writer, 1, outCh) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004303 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004304 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, outCh);
4305 writer.pos++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004306 }
4307 }
4308 }
4309 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 inShift = 0;
4311 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004312 if (surrogate) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313 if (_PyUnicodeWriter_Prepare(&writer, 1, surrogate) == -1)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004314 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, surrogate);
4316 writer.pos++;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004317 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004319 if (base64bits > 0) { /* left-over bits */
4320 if (base64bits >= 6) {
4321 /* We've seen at least one base-64 character */
4322 errmsg = "partial character in shift sequence";
4323 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 else {
4326 /* Some bits remain; they should be zero */
4327 if (base64buffer != 0) {
4328 errmsg = "non-zero padding bits in shift sequence";
4329 goto utf7Error;
4330 }
4331 }
4332 }
4333 if (ch != '-') {
4334 /* '-' is absorbed; other terminating
4335 characters are preserved */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004336 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004337 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004338 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
4339 writer.pos++;
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 Stinnerfc009ef2012-11-07 00:36:38 +01004348 if (_PyUnicodeWriter_Prepare(&writer, 1, '+') == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004349 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004350 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '+');
4351 writer.pos++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 }
4353 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004354 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004355 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004357 }
4358 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004360 s++;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004361 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
4362 goto onError;
4363 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
4364 writer.pos++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004365 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 else {
4367 startinpos = s-starts;
4368 s++;
4369 errmsg = "unexpected special character";
4370 goto utf7Error;
4371 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004372 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004374 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004375 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004376 errors, &errorHandler,
4377 "utf7", errmsg,
4378 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004379 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004380 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
4382
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 /* end of string */
4384
4385 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4386 /* if we're in an inconsistent state, that's an error */
4387 if (surrogate ||
4388 (base64bits >= 6) ||
4389 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004390 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004391 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004392 errors, &errorHandler,
4393 "utf7", "unterminated shift sequence",
4394 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004395 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004396 goto onError;
4397 if (s < e)
4398 goto restart;
4399 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004401
4402 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004403 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004404 if (inShift) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004405 writer.pos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004406 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004407 }
4408 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004409 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004411 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004413 Py_XDECREF(errorHandler);
4414 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004415 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416
Benjamin Peterson29060642009-01-31 22:14:21 +00004417 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004418 Py_XDECREF(errorHandler);
4419 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 return NULL;
4422}
4423
4424
Alexander Belopolsky40018472011-02-26 01:02:56 +00004425PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004426_PyUnicode_EncodeUTF7(PyObject *str,
4427 int base64SetO,
4428 int base64WhiteSpace,
4429 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004431 int kind;
4432 void *data;
4433 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004434 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004436 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437 unsigned int base64bits = 0;
4438 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439 char * out;
4440 char * start;
4441
Benjamin Petersonbac79492012-01-14 13:34:47 -05004442 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004443 return NULL;
4444 kind = PyUnicode_KIND(str);
4445 data = PyUnicode_DATA(str);
4446 len = PyUnicode_GET_LENGTH(str);
4447
4448 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004449 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004451 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004452 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004453 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004454 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004455 if (v == NULL)
4456 return NULL;
4457
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004458 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004459 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004460 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004461
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 if (inShift) {
4463 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4464 /* shifting out */
4465 if (base64bits) { /* output remaining bits */
4466 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4467 base64buffer = 0;
4468 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004469 }
4470 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004471 /* Characters not in the BASE64 set implicitly unshift the sequence
4472 so no '-' is required, except if the character is itself a '-' */
4473 if (IS_BASE64(ch) || ch == '-') {
4474 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004475 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 *out++ = (char) ch;
4477 }
4478 else {
4479 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004480 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004482 else { /* not in a shift sequence */
4483 if (ch == '+') {
4484 *out++ = '+';
4485 *out++ = '-';
4486 }
4487 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4488 *out++ = (char) ch;
4489 }
4490 else {
4491 *out++ = '+';
4492 inShift = 1;
4493 goto encode_char;
4494 }
4495 }
4496 continue;
4497encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004499 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004500
Antoine Pitrou244651a2009-05-04 18:56:13 +00004501 /* code first surrogate */
4502 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004503 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504 while (base64bits >= 6) {
4505 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4506 base64bits -= 6;
4507 }
4508 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004509 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004510 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004511 base64bits += 16;
4512 base64buffer = (base64buffer << 16) | ch;
4513 while (base64bits >= 6) {
4514 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4515 base64bits -= 6;
4516 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004517 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518 if (base64bits)
4519 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4520 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004521 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004522 if (_PyBytes_Resize(&v, out - start) < 0)
4523 return NULL;
4524 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004526PyObject *
4527PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4528 Py_ssize_t size,
4529 int base64SetO,
4530 int base64WhiteSpace,
4531 const char *errors)
4532{
4533 PyObject *result;
4534 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4535 if (tmp == NULL)
4536 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004537 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004538 base64WhiteSpace, errors);
4539 Py_DECREF(tmp);
4540 return result;
4541}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543#undef IS_BASE64
4544#undef FROM_BASE64
4545#undef TO_BASE64
4546#undef DECODE_DIRECT
4547#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548
Guido van Rossumd57fd912000-03-10 22:53:23 +00004549/* --- UTF-8 Codec -------------------------------------------------------- */
4550
Alexander Belopolsky40018472011-02-26 01:02:56 +00004551PyObject *
4552PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004553 Py_ssize_t size,
4554 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004555{
Walter Dörwald69652032004-09-07 20:24:22 +00004556 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4557}
4558
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004559#include "stringlib/asciilib.h"
4560#include "stringlib/codecs.h"
4561#include "stringlib/undef.h"
4562
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004563#include "stringlib/ucs1lib.h"
4564#include "stringlib/codecs.h"
4565#include "stringlib/undef.h"
4566
4567#include "stringlib/ucs2lib.h"
4568#include "stringlib/codecs.h"
4569#include "stringlib/undef.h"
4570
4571#include "stringlib/ucs4lib.h"
4572#include "stringlib/codecs.h"
4573#include "stringlib/undef.h"
4574
Antoine Pitrouab868312009-01-10 15:40:25 +00004575/* Mask to quickly check whether a C 'long' contains a
4576 non-ASCII, UTF8-encoded char. */
4577#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004578# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004579#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004580# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004581#else
4582# error C 'long' size should be either 4 or 8!
4583#endif
4584
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004585static Py_ssize_t
4586ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004587{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004588 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004589 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004590
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004591#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004592 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4593 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004594 /* Fast path, see in STRINGLIB(utf8_decode) for
4595 an explanation. */
4596 /* Help register allocation */
4597 register const char *_p = p;
4598 register Py_UCS1 * q = dest;
4599 while (_p < aligned_end) {
4600 unsigned long value = *(const unsigned long *) _p;
4601 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004602 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004603 *((unsigned long *)q) = value;
4604 _p += SIZEOF_LONG;
4605 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004606 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004607 p = _p;
4608 while (p < end) {
4609 if ((unsigned char)*p & 0x80)
4610 break;
4611 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004613 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004614 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004615#endif
4616 while (p < end) {
4617 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4618 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004619 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004620 /* Help register allocation */
4621 register const char *_p = p;
4622 while (_p < aligned_end) {
4623 unsigned long value = *(unsigned long *) _p;
4624 if (value & ASCII_CHAR_MASK)
4625 break;
4626 _p += SIZEOF_LONG;
4627 }
4628 p = _p;
4629 if (_p == end)
4630 break;
4631 }
4632 if ((unsigned char)*p & 0x80)
4633 break;
4634 ++p;
4635 }
4636 memcpy(dest, start, p - start);
4637 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004638}
Antoine Pitrouab868312009-01-10 15:40:25 +00004639
Victor Stinner785938e2011-12-11 20:09:03 +01004640PyObject *
4641PyUnicode_DecodeUTF8Stateful(const char *s,
4642 Py_ssize_t size,
4643 const char *errors,
4644 Py_ssize_t *consumed)
4645{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004646 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004647 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004648 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004649
4650 Py_ssize_t startinpos;
4651 Py_ssize_t endinpos;
4652 const char *errmsg = "";
4653 PyObject *errorHandler = NULL;
4654 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004655
4656 if (size == 0) {
4657 if (consumed)
4658 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004659 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004660 }
4661
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004662 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4663 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004664 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004665 *consumed = 1;
4666 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004667 }
4668
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004669 _PyUnicodeWriter_Init(&writer, 0);
4670 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
4671 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004672
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004673 writer.pos = ascii_decode(s, end, writer.data);
4674 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675 while (s < end) {
4676 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004677 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004679 if (PyUnicode_IS_ASCII(writer.buffer))
4680 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004681 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004682 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004683 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004684 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004685 } else {
4686 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004687 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 }
4689
4690 switch (ch) {
4691 case 0:
4692 if (s == end || consumed)
4693 goto End;
4694 errmsg = "unexpected end of data";
4695 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004696 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004697 break;
4698 case 1:
4699 errmsg = "invalid start byte";
4700 startinpos = s - starts;
4701 endinpos = startinpos + 1;
4702 break;
4703 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004704 case 3:
4705 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004706 errmsg = "invalid continuation byte";
4707 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004708 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004709 break;
4710 default:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004711 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004713 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
4714 writer.pos++;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004715 continue;
4716 }
4717
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004718 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004719 errors, &errorHandler,
4720 "utf-8", errmsg,
4721 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004722 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004724 }
4725
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 if (consumed)
4728 *consumed = s - starts;
4729
4730 Py_XDECREF(errorHandler);
4731 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004732 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004733
4734onError:
4735 Py_XDECREF(errorHandler);
4736 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004737 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004739}
4740
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004741#ifdef __APPLE__
4742
4743/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004744 used to decode the command line arguments on Mac OS X.
4745
4746 Return a pointer to a newly allocated wide character string (use
4747 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004748
4749wchar_t*
4750_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4751{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004752 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 wchar_t *unicode;
4754 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004755
4756 /* Note: size will always be longer than the resulting Unicode
4757 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004758 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004759 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004760 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4761 if (!unicode)
4762 return NULL;
4763
4764 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004765 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004767 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004769#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004770 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004771#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004773#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774 if (ch > 0xFF) {
4775#if SIZEOF_WCHAR_T == 4
4776 assert(0);
4777#else
4778 assert(Py_UNICODE_IS_SURROGATE(ch));
4779 /* compute and append the two surrogates: */
4780 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4781 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4782#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004783 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784 else {
4785 if (!ch && s == e)
4786 break;
4787 /* surrogateescape */
4788 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4789 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004790 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004792 return unicode;
4793}
4794
4795#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797/* Primary internal function which creates utf8 encoded bytes objects.
4798
4799 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004800 and allocate exactly as much space needed at the end. Else allocate the
4801 maximum possible needed (4 result bytes per Unicode character), and return
4802 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004803*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004804PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004805_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004806{
Victor Stinner6099a032011-12-18 14:22:26 +01004807 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004808 void *data;
4809 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004811 if (!PyUnicode_Check(unicode)) {
4812 PyErr_BadArgument();
4813 return NULL;
4814 }
4815
4816 if (PyUnicode_READY(unicode) == -1)
4817 return NULL;
4818
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004819 if (PyUnicode_UTF8(unicode))
4820 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4821 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004822
4823 kind = PyUnicode_KIND(unicode);
4824 data = PyUnicode_DATA(unicode);
4825 size = PyUnicode_GET_LENGTH(unicode);
4826
Benjamin Petersonead6b532011-12-20 17:23:42 -06004827 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004828 default:
4829 assert(0);
4830 case PyUnicode_1BYTE_KIND:
4831 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4832 assert(!PyUnicode_IS_ASCII(unicode));
4833 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4834 case PyUnicode_2BYTE_KIND:
4835 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4836 case PyUnicode_4BYTE_KIND:
4837 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004838 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004839}
4840
Alexander Belopolsky40018472011-02-26 01:02:56 +00004841PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004842PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4843 Py_ssize_t size,
4844 const char *errors)
4845{
4846 PyObject *v, *unicode;
4847
4848 unicode = PyUnicode_FromUnicode(s, size);
4849 if (unicode == NULL)
4850 return NULL;
4851 v = _PyUnicode_AsUTF8String(unicode, errors);
4852 Py_DECREF(unicode);
4853 return v;
4854}
4855
4856PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004857PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004859 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004860}
4861
Walter Dörwald41980ca2007-08-16 21:55:45 +00004862/* --- UTF-32 Codec ------------------------------------------------------- */
4863
4864PyObject *
4865PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004866 Py_ssize_t size,
4867 const char *errors,
4868 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004869{
4870 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4871}
4872
4873PyObject *
4874PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004875 Py_ssize_t size,
4876 const char *errors,
4877 int *byteorder,
4878 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004879{
4880 const char *starts = s;
4881 Py_ssize_t startinpos;
4882 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004883 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004884 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004885 int le, bo = 0; /* assume native ordering by default */
Walter Dörwald41980ca2007-08-16 21:55:45 +00004886 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004887 PyObject *errorHandler = NULL;
4888 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004889
Walter Dörwald41980ca2007-08-16 21:55:45 +00004890 q = (unsigned char *)s;
4891 e = q + size;
4892
4893 if (byteorder)
4894 bo = *byteorder;
4895
4896 /* Check for BOM marks (U+FEFF) in the input and adjust current
4897 byte order setting accordingly. In native mode, the leading BOM
4898 mark is skipped, in all other modes, it is copied to the output
4899 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004900 if (bo == 0 && size >= 4) {
4901 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4902 if (bom == 0x0000FEFF) {
4903 bo = -1;
4904 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004905 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004906 else if (bom == 0xFFFE0000) {
4907 bo = 1;
4908 q += 4;
4909 }
4910 if (byteorder)
4911 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004912 }
4913
Victor Stinnere64322e2012-10-30 23:12:47 +01004914 if (q == e) {
4915 if (consumed)
4916 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004917 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004918 }
4919
Victor Stinnere64322e2012-10-30 23:12:47 +01004920#ifdef WORDS_BIGENDIAN
4921 le = bo < 0;
4922#else
4923 le = bo <= 0;
4924#endif
4925
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004926 _PyUnicodeWriter_Init(&writer, 0);
4927 if (_PyUnicodeWriter_Prepare(&writer, (e - q + 3) / 4, 127) == -1)
4928 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004929
Victor Stinnere64322e2012-10-30 23:12:47 +01004930 while (1) {
4931 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004932 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004933
Victor Stinnere64322e2012-10-30 23:12:47 +01004934 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004935 enum PyUnicode_Kind kind = writer.kind;
4936 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004937 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004938 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004939 if (le) {
4940 do {
4941 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4942 if (ch > maxch)
4943 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004944 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004945 q += 4;
4946 } while (q <= last);
4947 }
4948 else {
4949 do {
4950 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
4951 if (ch > maxch)
4952 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004953 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004954 q += 4;
4955 } while (q <= last);
4956 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004957 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004958 }
4959
4960 if (ch <= maxch) {
4961 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004962 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01004963 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00004964 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01004965 startinpos = ((const char *)q) - starts;
4966 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00004967 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004968 else {
4969 if (ch < 0x110000) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004970 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
Victor Stinnere64322e2012-10-30 23:12:47 +01004971 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004972 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
4973 writer.pos++;
Victor Stinnere64322e2012-10-30 23:12:47 +01004974 q += 4;
4975 continue;
4976 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004977 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01004978 startinpos = ((const char *)q) - starts;
4979 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004980 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004981
4982 /* The remaining input chars are ignored if the callback
4983 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004985 errors, &errorHandler,
4986 "utf32", errmsg,
4987 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004988 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004989 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004990 }
4991
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004993 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004994
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995 Py_XDECREF(errorHandler);
4996 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004997 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998
Benjamin Peterson29060642009-01-31 22:14:21 +00004999 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005000 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005001 Py_XDECREF(errorHandler);
5002 Py_XDECREF(exc);
5003 return NULL;
5004}
5005
5006PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005007_PyUnicode_EncodeUTF32(PyObject *str,
5008 const char *errors,
5009 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005010{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005011 int kind;
5012 void *data;
5013 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005014 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005015 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005016 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005017 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005018#if PY_LITTLE_ENDIAN
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019 int iorder[] = {0, 1, 2, 3};
5020#else
5021 int iorder[] = {3, 2, 1, 0};
5022#endif
5023
Benjamin Peterson29060642009-01-31 22:14:21 +00005024#define STORECHAR(CH) \
5025 do { \
5026 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5027 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5028 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5029 p[iorder[0]] = (CH) & 0xff; \
5030 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005031 } while(0)
5032
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005033 if (!PyUnicode_Check(str)) {
5034 PyErr_BadArgument();
5035 return NULL;
5036 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005037 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005038 return NULL;
5039 kind = PyUnicode_KIND(str);
5040 data = PyUnicode_DATA(str);
5041 len = PyUnicode_GET_LENGTH(str);
5042
5043 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005044 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005046 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047 if (v == NULL)
5048 return NULL;
5049
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005050 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005053 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005054 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055
5056 if (byteorder == -1) {
5057 /* force LE */
5058 iorder[0] = 0;
5059 iorder[1] = 1;
5060 iorder[2] = 2;
5061 iorder[3] = 3;
5062 }
5063 else if (byteorder == 1) {
5064 /* force BE */
5065 iorder[0] = 3;
5066 iorder[1] = 2;
5067 iorder[2] = 1;
5068 iorder[3] = 0;
5069 }
5070
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005071 for (i = 0; i < len; i++)
5072 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005073
5074 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005075 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076#undef STORECHAR
5077}
5078
Alexander Belopolsky40018472011-02-26 01:02:56 +00005079PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005080PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5081 Py_ssize_t size,
5082 const char *errors,
5083 int byteorder)
5084{
5085 PyObject *result;
5086 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5087 if (tmp == NULL)
5088 return NULL;
5089 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5090 Py_DECREF(tmp);
5091 return result;
5092}
5093
5094PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005095PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096{
Victor Stinnerb960b342011-11-20 19:12:52 +01005097 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098}
5099
Guido van Rossumd57fd912000-03-10 22:53:23 +00005100/* --- UTF-16 Codec ------------------------------------------------------- */
5101
Tim Peters772747b2001-08-09 22:21:55 +00005102PyObject *
5103PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005104 Py_ssize_t size,
5105 const char *errors,
5106 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005107{
Walter Dörwald69652032004-09-07 20:24:22 +00005108 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5109}
5110
5111PyObject *
5112PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005113 Py_ssize_t size,
5114 const char *errors,
5115 int *byteorder,
5116 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005117{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005118 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005119 Py_ssize_t startinpos;
5120 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005121 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005122 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005123 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005124 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005125 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005126 PyObject *errorHandler = NULL;
5127 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005128
Tim Peters772747b2001-08-09 22:21:55 +00005129 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005130 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005131
5132 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005133 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005134
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005135 /* Check for BOM marks (U+FEFF) in the input and adjust current
5136 byte order setting accordingly. In native mode, the leading BOM
5137 mark is skipped, in all other modes, it is copied to the output
5138 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005139 if (bo == 0 && size >= 2) {
5140 const Py_UCS4 bom = (q[1] << 8) | q[0];
5141 if (bom == 0xFEFF) {
5142 q += 2;
5143 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005144 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005145 else if (bom == 0xFFFE) {
5146 q += 2;
5147 bo = 1;
5148 }
5149 if (byteorder)
5150 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005151 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005152
Antoine Pitrou63065d72012-05-15 23:48:04 +02005153 if (q == e) {
5154 if (consumed)
5155 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005156 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005157 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005158
Christian Heimes743e0cd2012-10-17 23:52:17 +02005159#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005160 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005161#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005162 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005163#endif
Tim Peters772747b2001-08-09 22:21:55 +00005164
Antoine Pitrou63065d72012-05-15 23:48:04 +02005165 /* Note: size will always be longer than the resulting Unicode
5166 character count */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005167 _PyUnicodeWriter_Init(&writer, 0);
5168 if (_PyUnicodeWriter_Prepare(&writer, (e - q + 1) / 2, 127) == -1)
5169 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005170
Antoine Pitrou63065d72012-05-15 23:48:04 +02005171 while (1) {
5172 Py_UCS4 ch = 0;
5173 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005174 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005175 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005176 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005177 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005178 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005179 native_ordering);
5180 else
5181 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005182 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005183 native_ordering);
5184 } else if (kind == PyUnicode_2BYTE_KIND) {
5185 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005186 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005187 native_ordering);
5188 } else {
5189 assert(kind == PyUnicode_4BYTE_KIND);
5190 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005191 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005192 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005193 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005194 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005195
Antoine Pitrou63065d72012-05-15 23:48:04 +02005196 switch (ch)
5197 {
5198 case 0:
5199 /* remaining byte at the end? (size should be even) */
5200 if (q == e || consumed)
5201 goto End;
5202 errmsg = "truncated data";
5203 startinpos = ((const char *)q) - starts;
5204 endinpos = ((const char *)e) - starts;
5205 break;
5206 /* The remaining input chars are ignored if the callback
5207 chooses to skip the input */
5208 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005209 q -= 2;
5210 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005211 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005212 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005213 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005214 endinpos = ((const char *)e) - starts;
5215 break;
5216 case 2:
5217 errmsg = "illegal encoding";
5218 startinpos = ((const char *)q) - 2 - starts;
5219 endinpos = startinpos + 2;
5220 break;
5221 case 3:
5222 errmsg = "illegal UTF-16 surrogate";
5223 startinpos = ((const char *)q) - 4 - starts;
5224 endinpos = startinpos + 2;
5225 break;
5226 default:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005227 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005228 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005229 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
5230 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 continue;
5232 }
5233
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005234 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005235 errors,
5236 &errorHandler,
5237 "utf16", errmsg,
5238 &starts,
5239 (const char **)&e,
5240 &startinpos,
5241 &endinpos,
5242 &exc,
5243 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005244 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005246 }
5247
Antoine Pitrou63065d72012-05-15 23:48:04 +02005248End:
Walter Dörwald69652032004-09-07 20:24:22 +00005249 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005250 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005251
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005252 Py_XDECREF(errorHandler);
5253 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005254 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005255
Benjamin Peterson29060642009-01-31 22:14:21 +00005256 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005257 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005258 Py_XDECREF(errorHandler);
5259 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005260 return NULL;
5261}
5262
Tim Peters772747b2001-08-09 22:21:55 +00005263PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005264_PyUnicode_EncodeUTF16(PyObject *str,
5265 const char *errors,
5266 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005267{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005268 enum PyUnicode_Kind kind;
5269 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005270 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005271 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005272 unsigned short *out;
5273 Py_ssize_t bytesize;
5274 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005275#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005276 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005277#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005278 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005279#endif
5280
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005281 if (!PyUnicode_Check(str)) {
5282 PyErr_BadArgument();
5283 return NULL;
5284 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005285 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005286 return NULL;
5287 kind = PyUnicode_KIND(str);
5288 data = PyUnicode_DATA(str);
5289 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005290
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005291 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005292 if (kind == PyUnicode_4BYTE_KIND) {
5293 const Py_UCS4 *in = (const Py_UCS4 *)data;
5294 const Py_UCS4 *end = in + len;
5295 while (in < end)
5296 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005297 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005298 }
5299 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005300 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005301 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005302 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005303 if (v == NULL)
5304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005305
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005306 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005307 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005308 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005309 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005310 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005311 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005312 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005313
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005314 switch (kind) {
5315 case PyUnicode_1BYTE_KIND: {
5316 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5317 break;
Tim Peters772747b2001-08-09 22:21:55 +00005318 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005319 case PyUnicode_2BYTE_KIND: {
5320 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5321 break;
Tim Peters772747b2001-08-09 22:21:55 +00005322 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005323 case PyUnicode_4BYTE_KIND: {
5324 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5325 break;
5326 }
5327 default:
5328 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005329 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005330
5331 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005332 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005333}
5334
Alexander Belopolsky40018472011-02-26 01:02:56 +00005335PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005336PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5337 Py_ssize_t size,
5338 const char *errors,
5339 int byteorder)
5340{
5341 PyObject *result;
5342 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5343 if (tmp == NULL)
5344 return NULL;
5345 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5346 Py_DECREF(tmp);
5347 return result;
5348}
5349
5350PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005351PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005352{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005353 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005354}
5355
5356/* --- Unicode Escape Codec ----------------------------------------------- */
5357
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005358/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5359 if all the escapes in the string make it still a valid ASCII string.
5360 Returns -1 if any escapes were found which cause the string to
5361 pop out of ASCII range. Otherwise returns the length of the
5362 required buffer to hold the string.
5363 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005364static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005365length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5366{
5367 const unsigned char *p = (const unsigned char *)s;
5368 const unsigned char *end = p + size;
5369 Py_ssize_t length = 0;
5370
5371 if (size < 0)
5372 return -1;
5373
5374 for (; p < end; ++p) {
5375 if (*p > 127) {
5376 /* Non-ASCII */
5377 return -1;
5378 }
5379 else if (*p != '\\') {
5380 /* Normal character */
5381 ++length;
5382 }
5383 else {
5384 /* Backslash-escape, check next char */
5385 ++p;
5386 /* Escape sequence reaches till end of string or
5387 non-ASCII follow-up. */
5388 if (p >= end || *p > 127)
5389 return -1;
5390 switch (*p) {
5391 case '\n':
5392 /* backslash + \n result in zero characters */
5393 break;
5394 case '\\': case '\'': case '\"':
5395 case 'b': case 'f': case 't':
5396 case 'n': case 'r': case 'v': case 'a':
5397 ++length;
5398 break;
5399 case '0': case '1': case '2': case '3':
5400 case '4': case '5': case '6': case '7':
5401 case 'x': case 'u': case 'U': case 'N':
5402 /* these do not guarantee ASCII characters */
5403 return -1;
5404 default:
5405 /* count the backslash + the other character */
5406 length += 2;
5407 }
5408 }
5409 }
5410 return length;
5411}
5412
Fredrik Lundh06d12682001-01-24 07:59:11 +00005413static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005414
Alexander Belopolsky40018472011-02-26 01:02:56 +00005415PyObject *
5416PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005417 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005418 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005420 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005421 Py_ssize_t startinpos;
5422 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005423 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005425 char* message;
5426 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005427 PyObject *errorHandler = NULL;
5428 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005429 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005430
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005431 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005432 if (len == 0)
5433 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005434
5435 /* After length_of_escaped_ascii_string() there are two alternatives,
5436 either the string is pure ASCII with named escapes like \n, etc.
5437 and we determined it's exact size (common case)
5438 or it contains \x, \u, ... escape sequences. then we create a
5439 legacy wchar string and resize it at the end of this function. */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005440 _PyUnicodeWriter_Init(&writer, 0);
5441 if (len > 0) {
5442 if (_PyUnicodeWriter_Prepare(&writer, len, 127) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005443 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005444 assert(writer.kind == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005445 }
5446 else {
5447 /* Escaped strings will always be longer than the resulting
5448 Unicode string, so we start with size here and then reduce the
5449 length after conversion to the true value.
5450 (but if the error callback returns a long replacement string
5451 we'll have to allocate more space) */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005452 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005453 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005454 }
5455
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005457 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005458 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005459
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460 while (s < end) {
5461 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005462 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005463 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005464
5465 /* Non-escape characters are interpreted as Unicode ordinals */
5466 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005467 x = (unsigned char)*s;
5468 s++;
5469 if (_PyUnicodeWriter_Prepare(&writer, 1, x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005470 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005471 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, x);
5472 writer.pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005473 continue;
5474 }
5475
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005476 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005477 /* \ - Escapes */
5478 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005479 c = *s++;
5480 if (s > end)
5481 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005482
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005483 /* The only case in which i == ascii_length is a backslash
5484 followed by a newline. */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005485 assert(writer.pos < writer.size || (writer.pos == writer.size && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005486
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005487 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005488
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005490#define WRITECHAR(ch) \
5491 do { \
5492 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1) \
5493 goto onError; \
5494 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch); \
5495 writer.pos++; \
5496 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005497
Guido van Rossumd57fd912000-03-10 22:53:23 +00005498 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005499 case '\\': WRITECHAR('\\'); break;
5500 case '\'': WRITECHAR('\''); break;
5501 case '\"': WRITECHAR('\"'); break;
5502 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005503 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005504 case 'f': WRITECHAR('\014'); break;
5505 case 't': WRITECHAR('\t'); break;
5506 case 'n': WRITECHAR('\n'); break;
5507 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005508 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005509 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005510 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005511 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005512
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005514 case '0': case '1': case '2': case '3':
5515 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005516 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005517 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005518 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005519 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005520 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005521 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005522 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523 break;
5524
Benjamin Peterson29060642009-01-31 22:14:21 +00005525 /* hex escapes */
5526 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005527 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005528 digits = 2;
5529 message = "truncated \\xXX escape";
5530 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531
Benjamin Peterson29060642009-01-31 22:14:21 +00005532 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005534 digits = 4;
5535 message = "truncated \\uXXXX escape";
5536 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005537
Benjamin Peterson29060642009-01-31 22:14:21 +00005538 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005539 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005540 digits = 8;
5541 message = "truncated \\UXXXXXXXX escape";
5542 hexescape:
5543 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005544 if (end - s < digits) {
5545 /* count only hex digits */
5546 for (; s < end; ++s) {
5547 c = (unsigned char)*s;
5548 if (!Py_ISXDIGIT(c))
5549 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005550 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005551 goto error;
5552 }
5553 for (; digits--; ++s) {
5554 c = (unsigned char)*s;
5555 if (!Py_ISXDIGIT(c))
5556 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005557 chr = (chr<<4) & ~0xF;
5558 if (c >= '0' && c <= '9')
5559 chr += c - '0';
5560 else if (c >= 'a' && c <= 'f')
5561 chr += 10 + c - 'a';
5562 else
5563 chr += 10 + c - 'A';
5564 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005565 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005566 /* _decoding_error will have already written into the
5567 target buffer. */
5568 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005569 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005570 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005571 message = "illegal Unicode character";
5572 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005573 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005574 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005575 break;
5576
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005578 case 'N':
5579 message = "malformed \\N character escape";
5580 if (ucnhash_CAPI == NULL) {
5581 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005582 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5583 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005584 if (ucnhash_CAPI == NULL)
5585 goto ucnhashError;
5586 }
5587 if (*s == '{') {
5588 const char *start = s+1;
5589 /* look for the closing brace */
5590 while (*s != '}' && s < end)
5591 s++;
5592 if (s > start && s < end && *s == '}') {
5593 /* found a name. look it up in the unicode database */
5594 message = "unknown Unicode character name";
5595 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005596 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005597 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005598 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005599 goto store;
5600 }
5601 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005602 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005603
5604 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005605 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005606 message = "\\ at end of string";
5607 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005608 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005609 }
5610 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005611 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005612 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005613 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005614 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005616 continue;
5617
5618 error:
5619 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005620 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005621 errors, &errorHandler,
5622 "unicodeescape", message,
5623 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005624 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005625 goto onError;
5626 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005627 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005628#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005629
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005630 Py_XDECREF(errorHandler);
5631 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005632 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005633
Benjamin Peterson29060642009-01-31 22:14:21 +00005634 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005635 PyErr_SetString(
5636 PyExc_UnicodeError,
5637 "\\N escapes not supported (can't load unicodedata module)"
5638 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005639 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005640 Py_XDECREF(errorHandler);
5641 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005642 return NULL;
5643
Benjamin Peterson29060642009-01-31 22:14:21 +00005644 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005645 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646 Py_XDECREF(errorHandler);
5647 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005648 return NULL;
5649}
5650
5651/* Return a Unicode-Escape string version of the Unicode object.
5652
5653 If quotes is true, the string is enclosed in u"" or u'' quotes as
5654 appropriate.
5655
5656*/
5657
Alexander Belopolsky40018472011-02-26 01:02:56 +00005658PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005659PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005660{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005661 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005662 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005664 int kind;
5665 void *data;
5666 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667
Ezio Melottie7f90372012-10-05 03:33:31 +03005668 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005669 escape.
5670
Ezio Melottie7f90372012-10-05 03:33:31 +03005671 For UCS1 strings it's '\xxx', 4 bytes per source character.
5672 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5673 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005674 */
5675
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005676 if (!PyUnicode_Check(unicode)) {
5677 PyErr_BadArgument();
5678 return NULL;
5679 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005680 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005681 return NULL;
5682 len = PyUnicode_GET_LENGTH(unicode);
5683 kind = PyUnicode_KIND(unicode);
5684 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005685 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005686 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5687 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5688 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5689 }
5690
5691 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005692 return PyBytes_FromStringAndSize(NULL, 0);
5693
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005694 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005695 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005696
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005697 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005698 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005699 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005700 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701 if (repr == NULL)
5702 return NULL;
5703
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005704 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005705
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005706 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005707 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005708
Walter Dörwald79e913e2007-05-12 11:08:06 +00005709 /* Escape backslashes */
5710 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005711 *p++ = '\\';
5712 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005713 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005714 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005715
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005716 /* Map 21-bit characters to '\U00xxxxxx' */
5717 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005718 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005719 *p++ = '\\';
5720 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005721 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5722 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5723 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5724 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5725 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5726 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5727 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5728 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005729 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005730 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005731
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005733 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734 *p++ = '\\';
5735 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005736 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5737 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5738 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5739 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005741
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005742 /* Map special whitespace to '\t', \n', '\r' */
5743 else if (ch == '\t') {
5744 *p++ = '\\';
5745 *p++ = 't';
5746 }
5747 else if (ch == '\n') {
5748 *p++ = '\\';
5749 *p++ = 'n';
5750 }
5751 else if (ch == '\r') {
5752 *p++ = '\\';
5753 *p++ = 'r';
5754 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005755
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005756 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005757 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005758 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005759 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005760 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5761 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005762 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005763
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764 /* Copy everything else as-is */
5765 else
5766 *p++ = (char) ch;
5767 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005768
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005769 assert(p - PyBytes_AS_STRING(repr) > 0);
5770 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5771 return NULL;
5772 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773}
5774
Alexander Belopolsky40018472011-02-26 01:02:56 +00005775PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005776PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5777 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005779 PyObject *result;
5780 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5781 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005782 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005783 result = PyUnicode_AsUnicodeEscapeString(tmp);
5784 Py_DECREF(tmp);
5785 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786}
5787
5788/* --- Raw Unicode Escape Codec ------------------------------------------- */
5789
Alexander Belopolsky40018472011-02-26 01:02:56 +00005790PyObject *
5791PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005792 Py_ssize_t size,
5793 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005795 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005796 Py_ssize_t startinpos;
5797 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005798 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005799 const char *end;
5800 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005801 PyObject *errorHandler = NULL;
5802 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005803
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005804 if (size == 0)
5805 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005806
Guido van Rossumd57fd912000-03-10 22:53:23 +00005807 /* Escaped strings will always be longer than the resulting
5808 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005809 length after conversion to the true value. (But decoding error
5810 handler might have to resize the string) */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005811 _PyUnicodeWriter_Init(&writer, 1);
5812 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00005813 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005814
Guido van Rossumd57fd912000-03-10 22:53:23 +00005815 end = s + size;
5816 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005817 unsigned char c;
5818 Py_UCS4 x;
5819 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005820 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005821
Benjamin Peterson29060642009-01-31 22:14:21 +00005822 /* Non-escape characters are interpreted as Unicode ordinals */
5823 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005824 x = (unsigned char)*s++;
5825 if (_PyUnicodeWriter_Prepare(&writer, 1, x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005826 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005827 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, x);
5828 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00005829 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005830 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005831 startinpos = s-starts;
5832
5833 /* \u-escapes are only interpreted iff the number of leading
5834 backslashes if odd */
5835 bs = s;
5836 for (;s < end;) {
5837 if (*s != '\\')
5838 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005839 x = (unsigned char)*s++;
5840 if (_PyUnicodeWriter_Prepare(&writer, 1, x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005841 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005842 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, x);
5843 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00005844 }
5845 if (((s - bs) & 1) == 0 ||
5846 s >= end ||
5847 (*s != 'u' && *s != 'U')) {
5848 continue;
5849 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005850 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005851 count = *s=='u' ? 4 : 8;
5852 s++;
5853
5854 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005855 for (x = 0, i = 0; i < count; ++i, ++s) {
5856 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005857 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005858 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005859 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005860 errors, &errorHandler,
5861 "rawunicodeescape", "truncated \\uXXXX",
5862 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005863 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005864 goto onError;
5865 goto nextByte;
5866 }
5867 x = (x<<4) & ~0xF;
5868 if (c >= '0' && c <= '9')
5869 x += c - '0';
5870 else if (c >= 'a' && c <= 'f')
5871 x += 10 + c - 'a';
5872 else
5873 x += 10 + c - 'A';
5874 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005875 if (x <= MAX_UNICODE) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005876 if (_PyUnicodeWriter_Prepare(&writer, 1, x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005877 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005878 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, x);
5879 writer.pos++;
5880 }
5881 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00005882 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005883 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005884 errors, &errorHandler,
5885 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005886 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005887 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005888 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005889 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005890 nextByte:
5891 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005893 Py_XDECREF(errorHandler);
5894 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005895 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00005896
Benjamin Peterson29060642009-01-31 22:14:21 +00005897 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005898 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005899 Py_XDECREF(errorHandler);
5900 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901 return NULL;
5902}
5903
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904
Alexander Belopolsky40018472011-02-26 01:02:56 +00005905PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005906PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005908 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909 char *p;
5910 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005911 Py_ssize_t expandsize, pos;
5912 int kind;
5913 void *data;
5914 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005915
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916 if (!PyUnicode_Check(unicode)) {
5917 PyErr_BadArgument();
5918 return NULL;
5919 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005920 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 return NULL;
5922 kind = PyUnicode_KIND(unicode);
5923 data = PyUnicode_DATA(unicode);
5924 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06005925 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
5926 bytes, and 1 byte characters 4. */
5927 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01005928
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005931
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005932 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 if (repr == NULL)
5934 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005935 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005936 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005938 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005939 for (pos = 0; pos < len; pos++) {
5940 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 /* Map 32-bit characters to '\Uxxxxxxxx' */
5942 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005943 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005944 *p++ = '\\';
5945 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005946 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
5947 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
5948 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
5949 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
5950 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5951 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5952 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5953 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005954 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005956 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957 *p++ = '\\';
5958 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005959 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5960 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5961 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5962 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005963 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 /* Copy everything else as-is */
5965 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 *p++ = (char) ch;
5967 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005968
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005969 assert(p > q);
5970 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005971 return NULL;
5972 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973}
5974
Alexander Belopolsky40018472011-02-26 01:02:56 +00005975PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005976PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
5977 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005979 PyObject *result;
5980 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5981 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00005982 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005983 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
5984 Py_DECREF(tmp);
5985 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986}
5987
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005988/* --- Unicode Internal Codec ------------------------------------------- */
5989
Alexander Belopolsky40018472011-02-26 01:02:56 +00005990PyObject *
5991_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005992 Py_ssize_t size,
5993 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005994{
5995 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005996 Py_ssize_t startinpos;
5997 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005998 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005999 const char *end;
6000 const char *reason;
6001 PyObject *errorHandler = NULL;
6002 PyObject *exc = NULL;
6003
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006004 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006005 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006006 1))
6007 return NULL;
6008
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006009 if (size == 0)
6010 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006011
Thomas Wouters89f507f2006-12-13 04:49:30 +00006012 /* XXX overflow detection missing */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006013 _PyUnicodeWriter_Init(&writer, 0);
6014 if (_PyUnicodeWriter_Prepare(&writer, (size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00006015 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006016 end = s + size;
6017
6018 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006019 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006020 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006021 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006022 endinpos = end-starts;
6023 reason = "truncated input";
6024 goto error;
6025 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006026 /* We copy the raw representation one byte at a time because the
6027 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006028 ((char *) &uch)[0] = s[0];
6029 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006030#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006031 ((char *) &uch)[2] = s[2];
6032 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006033#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006034 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006035#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006036 /* We have to sanity check the raw data, otherwise doom looms for
6037 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006038 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006039 endinpos = s - starts + Py_UNICODE_SIZE;
6040 reason = "illegal code point (> 0x10FFFF)";
6041 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006042 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006043#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006044 s += Py_UNICODE_SIZE;
6045#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006046 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006047 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006048 Py_UNICODE uch2;
6049 ((char *) &uch2)[0] = s[0];
6050 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006051 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006052 {
Victor Stinner551ac952011-11-29 22:58:13 +01006053 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006054 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006055 }
6056 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006057#endif
6058
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006059 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006060 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006061 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
6062 writer.pos++;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006063 continue;
6064
6065 error:
6066 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006067 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006068 errors, &errorHandler,
6069 "unicode_internal", reason,
6070 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006071 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006072 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006073 }
6074
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006075 Py_XDECREF(errorHandler);
6076 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006077 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006078
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006080 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006081 Py_XDECREF(errorHandler);
6082 Py_XDECREF(exc);
6083 return NULL;
6084}
6085
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086/* --- Latin-1 Codec ------------------------------------------------------ */
6087
Alexander Belopolsky40018472011-02-26 01:02:56 +00006088PyObject *
6089PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006090 Py_ssize_t size,
6091 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006094 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095}
6096
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006097/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006098static void
6099make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006100 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006101 PyObject *unicode,
6102 Py_ssize_t startpos, Py_ssize_t endpos,
6103 const char *reason)
6104{
6105 if (*exceptionObject == NULL) {
6106 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006107 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006108 encoding, unicode, startpos, endpos, reason);
6109 }
6110 else {
6111 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6112 goto onError;
6113 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6114 goto onError;
6115 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6116 goto onError;
6117 return;
6118 onError:
6119 Py_DECREF(*exceptionObject);
6120 *exceptionObject = NULL;
6121 }
6122}
6123
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006124/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006125static void
6126raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006127 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006128 PyObject *unicode,
6129 Py_ssize_t startpos, Py_ssize_t endpos,
6130 const char *reason)
6131{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006132 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006133 encoding, unicode, startpos, endpos, reason);
6134 if (*exceptionObject != NULL)
6135 PyCodec_StrictErrors(*exceptionObject);
6136}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006137
6138/* error handling callback helper:
6139 build arguments, call the callback and check the arguments,
6140 put the result into newpos and return the replacement string, which
6141 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006142static PyObject *
6143unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006144 PyObject **errorHandler,
6145 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006146 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006147 Py_ssize_t startpos, Py_ssize_t endpos,
6148 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006149{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006150 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006151 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006152 PyObject *restuple;
6153 PyObject *resunicode;
6154
6155 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006157 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006159 }
6160
Benjamin Petersonbac79492012-01-14 13:34:47 -05006161 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006162 return NULL;
6163 len = PyUnicode_GET_LENGTH(unicode);
6164
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006165 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006166 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006167 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006168 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006169
6170 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006171 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006172 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006173 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006174 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006175 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 Py_DECREF(restuple);
6177 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006178 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006179 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 &resunicode, newpos)) {
6181 Py_DECREF(restuple);
6182 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006183 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006184 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6185 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6186 Py_DECREF(restuple);
6187 return NULL;
6188 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006189 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006190 *newpos = len + *newpos;
6191 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006192 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6193 Py_DECREF(restuple);
6194 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006195 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006196 Py_INCREF(resunicode);
6197 Py_DECREF(restuple);
6198 return resunicode;
6199}
6200
Alexander Belopolsky40018472011-02-26 01:02:56 +00006201static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006202unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006203 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006204 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006205{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006206 /* input state */
6207 Py_ssize_t pos=0, size;
6208 int kind;
6209 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006210 /* output object */
6211 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212 /* pointer into the output */
6213 char *str;
6214 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006215 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006216 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6217 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006218 PyObject *errorHandler = NULL;
6219 PyObject *exc = NULL;
6220 /* the following variable is used for caching string comparisons
6221 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6222 int known_errorHandler = -1;
6223
Benjamin Petersonbac79492012-01-14 13:34:47 -05006224 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006225 return NULL;
6226 size = PyUnicode_GET_LENGTH(unicode);
6227 kind = PyUnicode_KIND(unicode);
6228 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006229 /* allocate enough for a simple encoding without
6230 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006231 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006232 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006233 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006234 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006235 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006236 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006237 ressize = size;
6238
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006239 while (pos < size) {
6240 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006241
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 /* can we encode this? */
6243 if (c<limit) {
6244 /* no overflow check, because we know that the space is enough */
6245 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006246 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006248 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006249 Py_ssize_t requiredsize;
6250 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006251 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006252 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006253 Py_ssize_t collstart = pos;
6254 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006256 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006257 ++collend;
6258 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6259 if (known_errorHandler==-1) {
6260 if ((errors==NULL) || (!strcmp(errors, "strict")))
6261 known_errorHandler = 1;
6262 else if (!strcmp(errors, "replace"))
6263 known_errorHandler = 2;
6264 else if (!strcmp(errors, "ignore"))
6265 known_errorHandler = 3;
6266 else if (!strcmp(errors, "xmlcharrefreplace"))
6267 known_errorHandler = 4;
6268 else
6269 known_errorHandler = 0;
6270 }
6271 switch (known_errorHandler) {
6272 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006273 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 goto onError;
6275 case 2: /* replace */
6276 while (collstart++<collend)
6277 *str++ = '?'; /* fall through */
6278 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006279 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 break;
6281 case 4: /* xmlcharrefreplace */
6282 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006283 /* determine replacement size */
6284 for (i = collstart, repsize = 0; i < collend; ++i) {
6285 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6286 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006288 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006290 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006292 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006293 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006294 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006296 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006298 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006299 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006301 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006303 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006304 if (requiredsize > ressize) {
6305 if (requiredsize<2*ressize)
6306 requiredsize = 2*ressize;
6307 if (_PyBytes_Resize(&res, requiredsize))
6308 goto onError;
6309 str = PyBytes_AS_STRING(res) + respos;
6310 ressize = requiredsize;
6311 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006312 /* generate replacement */
6313 for (i = collstart; i < collend; ++i) {
6314 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006316 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 break;
6318 default:
6319 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006320 encoding, reason, unicode, &exc,
6321 collstart, collend, &newpos);
6322 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006323 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006324 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006325 if (PyBytes_Check(repunicode)) {
6326 /* Directly copy bytes result to output. */
6327 repsize = PyBytes_Size(repunicode);
6328 if (repsize > 1) {
6329 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006330 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006331 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6332 Py_DECREF(repunicode);
6333 goto onError;
6334 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006335 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006336 ressize += repsize-1;
6337 }
6338 memcpy(str, PyBytes_AsString(repunicode), repsize);
6339 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006340 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006341 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006342 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006343 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006344 /* need more space? (at least enough for what we
6345 have+the replacement+the rest of the string, so
6346 we won't have to check space for encodable characters) */
6347 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006348 repsize = PyUnicode_GET_LENGTH(repunicode);
6349 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006350 if (requiredsize > ressize) {
6351 if (requiredsize<2*ressize)
6352 requiredsize = 2*ressize;
6353 if (_PyBytes_Resize(&res, requiredsize)) {
6354 Py_DECREF(repunicode);
6355 goto onError;
6356 }
6357 str = PyBytes_AS_STRING(res) + respos;
6358 ressize = requiredsize;
6359 }
6360 /* check if there is anything unencodable in the replacement
6361 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006362 for (i = 0; repsize-->0; ++i, ++str) {
6363 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006364 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006365 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006366 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006367 Py_DECREF(repunicode);
6368 goto onError;
6369 }
6370 *str = (char)c;
6371 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006372 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006373 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006374 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006375 }
6376 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006377 /* Resize if we allocated to much */
6378 size = str - PyBytes_AS_STRING(res);
6379 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006380 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006381 if (_PyBytes_Resize(&res, size) < 0)
6382 goto onError;
6383 }
6384
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006385 Py_XDECREF(errorHandler);
6386 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006387 return res;
6388
6389 onError:
6390 Py_XDECREF(res);
6391 Py_XDECREF(errorHandler);
6392 Py_XDECREF(exc);
6393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394}
6395
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006397PyObject *
6398PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006399 Py_ssize_t size,
6400 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 PyObject *result;
6403 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6404 if (unicode == NULL)
6405 return NULL;
6406 result = unicode_encode_ucs1(unicode, errors, 256);
6407 Py_DECREF(unicode);
6408 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409}
6410
Alexander Belopolsky40018472011-02-26 01:02:56 +00006411PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006412_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413{
6414 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 PyErr_BadArgument();
6416 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006417 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006418 if (PyUnicode_READY(unicode) == -1)
6419 return NULL;
6420 /* Fast path: if it is a one-byte string, construct
6421 bytes object directly. */
6422 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6423 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6424 PyUnicode_GET_LENGTH(unicode));
6425 /* Non-Latin-1 characters present. Defer to above function to
6426 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006427 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006428}
6429
6430PyObject*
6431PyUnicode_AsLatin1String(PyObject *unicode)
6432{
6433 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434}
6435
6436/* --- 7-bit ASCII Codec -------------------------------------------------- */
6437
Alexander Belopolsky40018472011-02-26 01:02:56 +00006438PyObject *
6439PyUnicode_DecodeASCII(const char *s,
6440 Py_ssize_t size,
6441 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006442{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006443 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006444 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006445 int kind;
6446 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006447 Py_ssize_t startinpos;
6448 Py_ssize_t endinpos;
6449 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006450 const char *e;
6451 PyObject *errorHandler = NULL;
6452 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006453
Guido van Rossumd57fd912000-03-10 22:53:23 +00006454 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006455 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006456
Guido van Rossumd57fd912000-03-10 22:53:23 +00006457 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006458 if (size == 1 && (unsigned char)s[0] < 128)
6459 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006460
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006461 _PyUnicodeWriter_Init(&writer, 0);
6462 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006463 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006465 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006466 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006467 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006468 writer.pos = outpos;
6469 if (writer.pos == size)
6470 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006471
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006472 s += writer.pos;
6473 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006474 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 register unsigned char c = (unsigned char)*s;
6476 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006477 PyUnicode_WRITE(kind, data, writer.pos, c);
6478 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 ++s;
6480 }
6481 else {
6482 startinpos = s-starts;
6483 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006484 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 errors, &errorHandler,
6486 "ascii", "ordinal not in range(128)",
6487 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006488 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006489 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006490 kind = writer.kind;
6491 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006492 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006493 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494 Py_XDECREF(errorHandler);
6495 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006496 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006497
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006499 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006500 Py_XDECREF(errorHandler);
6501 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502 return NULL;
6503}
6504
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006506PyObject *
6507PyUnicode_EncodeASCII(const Py_UNICODE *p,
6508 Py_ssize_t size,
6509 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006510{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 PyObject *result;
6512 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6513 if (unicode == NULL)
6514 return NULL;
6515 result = unicode_encode_ucs1(unicode, errors, 128);
6516 Py_DECREF(unicode);
6517 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518}
6519
Alexander Belopolsky40018472011-02-26 01:02:56 +00006520PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006521_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522{
6523 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 PyErr_BadArgument();
6525 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006526 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006527 if (PyUnicode_READY(unicode) == -1)
6528 return NULL;
6529 /* Fast path: if it is an ASCII-only string, construct bytes object
6530 directly. Else defer to above function to raise the exception. */
6531 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6532 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6533 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006534 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006535}
6536
6537PyObject *
6538PyUnicode_AsASCIIString(PyObject *unicode)
6539{
6540 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006541}
6542
Victor Stinner99b95382011-07-04 14:23:54 +02006543#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006544
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006545/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006546
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006547#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006548#define NEED_RETRY
6549#endif
6550
Victor Stinner3a50e702011-10-18 21:21:00 +02006551#ifndef WC_ERR_INVALID_CHARS
6552# define WC_ERR_INVALID_CHARS 0x0080
6553#endif
6554
6555static char*
6556code_page_name(UINT code_page, PyObject **obj)
6557{
6558 *obj = NULL;
6559 if (code_page == CP_ACP)
6560 return "mbcs";
6561 if (code_page == CP_UTF7)
6562 return "CP_UTF7";
6563 if (code_page == CP_UTF8)
6564 return "CP_UTF8";
6565
6566 *obj = PyBytes_FromFormat("cp%u", code_page);
6567 if (*obj == NULL)
6568 return NULL;
6569 return PyBytes_AS_STRING(*obj);
6570}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006571
Alexander Belopolsky40018472011-02-26 01:02:56 +00006572static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006573is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006574{
6575 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006576 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006577
Victor Stinner3a50e702011-10-18 21:21:00 +02006578 if (!IsDBCSLeadByteEx(code_page, *curr))
6579 return 0;
6580
6581 prev = CharPrevExA(code_page, s, curr, 0);
6582 if (prev == curr)
6583 return 1;
6584 /* FIXME: This code is limited to "true" double-byte encodings,
6585 as it assumes an incomplete character consists of a single
6586 byte. */
6587 if (curr - prev == 2)
6588 return 1;
6589 if (!IsDBCSLeadByteEx(code_page, *prev))
6590 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006591 return 0;
6592}
6593
Victor Stinner3a50e702011-10-18 21:21:00 +02006594static DWORD
6595decode_code_page_flags(UINT code_page)
6596{
6597 if (code_page == CP_UTF7) {
6598 /* The CP_UTF7 decoder only supports flags=0 */
6599 return 0;
6600 }
6601 else
6602 return MB_ERR_INVALID_CHARS;
6603}
6604
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006605/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006606 * Decode a byte string from a Windows code page into unicode object in strict
6607 * mode.
6608 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006609 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6610 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006611 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006612static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006613decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006614 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006615 const char *in,
6616 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006617{
Victor Stinner3a50e702011-10-18 21:21:00 +02006618 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006619 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006620 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006621
6622 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006623 assert(insize > 0);
6624 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6625 if (outsize <= 0)
6626 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006627
6628 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006630 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006631 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006632 if (*v == NULL)
6633 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006634 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006635 }
6636 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006637 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006638 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006639 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006641 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006642 }
6643
6644 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006645 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6646 if (outsize <= 0)
6647 goto error;
6648 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006649
Victor Stinner3a50e702011-10-18 21:21:00 +02006650error:
6651 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6652 return -2;
6653 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006654 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006655}
6656
Victor Stinner3a50e702011-10-18 21:21:00 +02006657/*
6658 * Decode a byte string from a code page into unicode object with an error
6659 * handler.
6660 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006661 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006662 * UnicodeDecodeError exception and returns -1 on error.
6663 */
6664static int
6665decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006666 PyObject **v,
6667 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006668 const char *errors)
6669{
6670 const char *startin = in;
6671 const char *endin = in + size;
6672 const DWORD flags = decode_code_page_flags(code_page);
6673 /* Ideally, we should get reason from FormatMessage. This is the Windows
6674 2000 English version of the message. */
6675 const char *reason = "No mapping for the Unicode character exists "
6676 "in the target code page.";
6677 /* each step cannot decode more than 1 character, but a character can be
6678 represented as a surrogate pair */
6679 wchar_t buffer[2], *startout, *out;
6680 int insize, outsize;
6681 PyObject *errorHandler = NULL;
6682 PyObject *exc = NULL;
6683 PyObject *encoding_obj = NULL;
6684 char *encoding;
6685 DWORD err;
6686 int ret = -1;
6687
6688 assert(size > 0);
6689
6690 encoding = code_page_name(code_page, &encoding_obj);
6691 if (encoding == NULL)
6692 return -1;
6693
6694 if (errors == NULL || strcmp(errors, "strict") == 0) {
6695 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6696 UnicodeDecodeError. */
6697 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6698 if (exc != NULL) {
6699 PyCodec_StrictErrors(exc);
6700 Py_CLEAR(exc);
6701 }
6702 goto error;
6703 }
6704
6705 if (*v == NULL) {
6706 /* Create unicode object */
6707 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6708 PyErr_NoMemory();
6709 goto error;
6710 }
Victor Stinnerab595942011-12-17 04:59:06 +01006711 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006712 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006713 if (*v == NULL)
6714 goto error;
6715 startout = PyUnicode_AS_UNICODE(*v);
6716 }
6717 else {
6718 /* Extend unicode object */
6719 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6720 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6721 PyErr_NoMemory();
6722 goto error;
6723 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006724 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006725 goto error;
6726 startout = PyUnicode_AS_UNICODE(*v) + n;
6727 }
6728
6729 /* Decode the byte string character per character */
6730 out = startout;
6731 while (in < endin)
6732 {
6733 /* Decode a character */
6734 insize = 1;
6735 do
6736 {
6737 outsize = MultiByteToWideChar(code_page, flags,
6738 in, insize,
6739 buffer, Py_ARRAY_LENGTH(buffer));
6740 if (outsize > 0)
6741 break;
6742 err = GetLastError();
6743 if (err != ERROR_NO_UNICODE_TRANSLATION
6744 && err != ERROR_INSUFFICIENT_BUFFER)
6745 {
6746 PyErr_SetFromWindowsErr(0);
6747 goto error;
6748 }
6749 insize++;
6750 }
6751 /* 4=maximum length of a UTF-8 sequence */
6752 while (insize <= 4 && (in + insize) <= endin);
6753
6754 if (outsize <= 0) {
6755 Py_ssize_t startinpos, endinpos, outpos;
6756
6757 startinpos = in - startin;
6758 endinpos = startinpos + 1;
6759 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006760 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006761 errors, &errorHandler,
6762 encoding, reason,
6763 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006764 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006765 {
6766 goto error;
6767 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006768 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006769 }
6770 else {
6771 in += insize;
6772 memcpy(out, buffer, outsize * sizeof(wchar_t));
6773 out += outsize;
6774 }
6775 }
6776
6777 /* write a NUL character at the end */
6778 *out = 0;
6779
6780 /* Extend unicode object */
6781 outsize = out - startout;
6782 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006783 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006784 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006785 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006786
6787error:
6788 Py_XDECREF(encoding_obj);
6789 Py_XDECREF(errorHandler);
6790 Py_XDECREF(exc);
6791 return ret;
6792}
6793
Victor Stinner3a50e702011-10-18 21:21:00 +02006794static PyObject *
6795decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006796 const char *s, Py_ssize_t size,
6797 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006798{
Victor Stinner76a31a62011-11-04 00:05:13 +01006799 PyObject *v = NULL;
6800 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006801
Victor Stinner3a50e702011-10-18 21:21:00 +02006802 if (code_page < 0) {
6803 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6804 return NULL;
6805 }
6806
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006807 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006808 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006809
Victor Stinner76a31a62011-11-04 00:05:13 +01006810 do
6811 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006812#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006813 if (size > INT_MAX) {
6814 chunk_size = INT_MAX;
6815 final = 0;
6816 done = 0;
6817 }
6818 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006819#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006820 {
6821 chunk_size = (int)size;
6822 final = (consumed == NULL);
6823 done = 1;
6824 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006825
Victor Stinner76a31a62011-11-04 00:05:13 +01006826 /* Skip trailing lead-byte unless 'final' is set */
6827 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6828 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006829
Victor Stinner76a31a62011-11-04 00:05:13 +01006830 if (chunk_size == 0 && done) {
6831 if (v != NULL)
6832 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006833 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006834 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006835
Victor Stinner76a31a62011-11-04 00:05:13 +01006836
6837 converted = decode_code_page_strict(code_page, &v,
6838 s, chunk_size);
6839 if (converted == -2)
6840 converted = decode_code_page_errors(code_page, &v,
6841 s, chunk_size,
6842 errors);
6843 assert(converted != 0);
6844
6845 if (converted < 0) {
6846 Py_XDECREF(v);
6847 return NULL;
6848 }
6849
6850 if (consumed)
6851 *consumed += converted;
6852
6853 s += converted;
6854 size -= converted;
6855 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006856
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006857 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006858}
6859
Alexander Belopolsky40018472011-02-26 01:02:56 +00006860PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006861PyUnicode_DecodeCodePageStateful(int code_page,
6862 const char *s,
6863 Py_ssize_t size,
6864 const char *errors,
6865 Py_ssize_t *consumed)
6866{
6867 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6868}
6869
6870PyObject *
6871PyUnicode_DecodeMBCSStateful(const char *s,
6872 Py_ssize_t size,
6873 const char *errors,
6874 Py_ssize_t *consumed)
6875{
6876 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6877}
6878
6879PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006880PyUnicode_DecodeMBCS(const char *s,
6881 Py_ssize_t size,
6882 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006883{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006884 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6885}
6886
Victor Stinner3a50e702011-10-18 21:21:00 +02006887static DWORD
6888encode_code_page_flags(UINT code_page, const char *errors)
6889{
6890 if (code_page == CP_UTF8) {
6891 if (winver.dwMajorVersion >= 6)
6892 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6893 and later */
6894 return WC_ERR_INVALID_CHARS;
6895 else
6896 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
6897 return 0;
6898 }
6899 else if (code_page == CP_UTF7) {
6900 /* CP_UTF7 only supports flags=0 */
6901 return 0;
6902 }
6903 else {
6904 if (errors != NULL && strcmp(errors, "replace") == 0)
6905 return 0;
6906 else
6907 return WC_NO_BEST_FIT_CHARS;
6908 }
6909}
6910
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006911/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006912 * Encode a Unicode string to a Windows code page into a byte string in strict
6913 * mode.
6914 *
6915 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006916 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006917 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006918static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006919encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01006920 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02006921 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006922{
Victor Stinner554f3f02010-06-16 23:33:54 +00006923 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02006924 BOOL *pusedDefaultChar = &usedDefaultChar;
6925 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006926 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01006927 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006928 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006929 const DWORD flags = encode_code_page_flags(code_page, NULL);
6930 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006931 /* Create a substring so that we can get the UTF-16 representation
6932 of just the slice under consideration. */
6933 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006934
Martin v. Löwis3d325192011-11-04 18:23:06 +01006935 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006936
Victor Stinner3a50e702011-10-18 21:21:00 +02006937 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00006938 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02006939 else
Victor Stinner554f3f02010-06-16 23:33:54 +00006940 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00006941
Victor Stinner2fc507f2011-11-04 20:06:39 +01006942 substring = PyUnicode_Substring(unicode, offset, offset+len);
6943 if (substring == NULL)
6944 return -1;
6945 p = PyUnicode_AsUnicodeAndSize(substring, &size);
6946 if (p == NULL) {
6947 Py_DECREF(substring);
6948 return -1;
6949 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01006950
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006951 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006952 outsize = WideCharToMultiByte(code_page, flags,
6953 p, size,
6954 NULL, 0,
6955 NULL, pusedDefaultChar);
6956 if (outsize <= 0)
6957 goto error;
6958 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01006959 if (pusedDefaultChar && *pusedDefaultChar) {
6960 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006962 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006963
Victor Stinner3a50e702011-10-18 21:21:00 +02006964 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006966 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006967 if (*outbytes == NULL) {
6968 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00006969 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006970 }
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006972 }
6973 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006975 const Py_ssize_t n = PyBytes_Size(*outbytes);
6976 if (outsize > PY_SSIZE_T_MAX - n) {
6977 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01006978 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006980 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01006981 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
6982 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006983 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006984 }
Victor Stinner3a50e702011-10-18 21:21:00 +02006985 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006986 }
6987
6988 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006989 outsize = WideCharToMultiByte(code_page, flags,
6990 p, size,
6991 out, outsize,
6992 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006993 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006994 if (outsize <= 0)
6995 goto error;
6996 if (pusedDefaultChar && *pusedDefaultChar)
6997 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006998 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006999
Victor Stinner3a50e702011-10-18 21:21:00 +02007000error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007001 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007002 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7003 return -2;
7004 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007005 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007006}
7007
Victor Stinner3a50e702011-10-18 21:21:00 +02007008/*
7009 * Encode a Unicode string to a Windows code page into a byte string using a
7010 * error handler.
7011 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007012 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 * -1 on other error.
7014 */
7015static int
7016encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007017 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007018 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007019{
Victor Stinner3a50e702011-10-18 21:21:00 +02007020 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007021 Py_ssize_t pos = unicode_offset;
7022 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007023 /* Ideally, we should get reason from FormatMessage. This is the Windows
7024 2000 English version of the message. */
7025 const char *reason = "invalid character";
7026 /* 4=maximum length of a UTF-8 sequence */
7027 char buffer[4];
7028 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7029 Py_ssize_t outsize;
7030 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007031 PyObject *errorHandler = NULL;
7032 PyObject *exc = NULL;
7033 PyObject *encoding_obj = NULL;
7034 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007035 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007036 PyObject *rep;
7037 int ret = -1;
7038
7039 assert(insize > 0);
7040
7041 encoding = code_page_name(code_page, &encoding_obj);
7042 if (encoding == NULL)
7043 return -1;
7044
7045 if (errors == NULL || strcmp(errors, "strict") == 0) {
7046 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7047 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007048 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 if (exc != NULL) {
7050 PyCodec_StrictErrors(exc);
7051 Py_DECREF(exc);
7052 }
7053 Py_XDECREF(encoding_obj);
7054 return -1;
7055 }
7056
7057 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7058 pusedDefaultChar = &usedDefaultChar;
7059 else
7060 pusedDefaultChar = NULL;
7061
7062 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7063 PyErr_NoMemory();
7064 goto error;
7065 }
7066 outsize = insize * Py_ARRAY_LENGTH(buffer);
7067
7068 if (*outbytes == NULL) {
7069 /* Create string object */
7070 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7071 if (*outbytes == NULL)
7072 goto error;
7073 out = PyBytes_AS_STRING(*outbytes);
7074 }
7075 else {
7076 /* Extend string object */
7077 Py_ssize_t n = PyBytes_Size(*outbytes);
7078 if (n > PY_SSIZE_T_MAX - outsize) {
7079 PyErr_NoMemory();
7080 goto error;
7081 }
7082 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7083 goto error;
7084 out = PyBytes_AS_STRING(*outbytes) + n;
7085 }
7086
7087 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007088 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007089 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007090 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7091 wchar_t chars[2];
7092 int charsize;
7093 if (ch < 0x10000) {
7094 chars[0] = (wchar_t)ch;
7095 charsize = 1;
7096 }
7097 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007098 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7099 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007100 charsize = 2;
7101 }
7102
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007104 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007105 buffer, Py_ARRAY_LENGTH(buffer),
7106 NULL, pusedDefaultChar);
7107 if (outsize > 0) {
7108 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7109 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007110 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 memcpy(out, buffer, outsize);
7112 out += outsize;
7113 continue;
7114 }
7115 }
7116 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7117 PyErr_SetFromWindowsErr(0);
7118 goto error;
7119 }
7120
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 rep = unicode_encode_call_errorhandler(
7122 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007123 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007124 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007125 if (rep == NULL)
7126 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007127 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007128
7129 if (PyBytes_Check(rep)) {
7130 outsize = PyBytes_GET_SIZE(rep);
7131 if (outsize != 1) {
7132 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7133 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7134 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7135 Py_DECREF(rep);
7136 goto error;
7137 }
7138 out = PyBytes_AS_STRING(*outbytes) + offset;
7139 }
7140 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7141 out += outsize;
7142 }
7143 else {
7144 Py_ssize_t i;
7145 enum PyUnicode_Kind kind;
7146 void *data;
7147
Benjamin Petersonbac79492012-01-14 13:34:47 -05007148 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 Py_DECREF(rep);
7150 goto error;
7151 }
7152
7153 outsize = PyUnicode_GET_LENGTH(rep);
7154 if (outsize != 1) {
7155 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7156 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7157 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7158 Py_DECREF(rep);
7159 goto error;
7160 }
7161 out = PyBytes_AS_STRING(*outbytes) + offset;
7162 }
7163 kind = PyUnicode_KIND(rep);
7164 data = PyUnicode_DATA(rep);
7165 for (i=0; i < outsize; i++) {
7166 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7167 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007168 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007169 encoding, unicode,
7170 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 "unable to encode error handler result to ASCII");
7172 Py_DECREF(rep);
7173 goto error;
7174 }
7175 *out = (unsigned char)ch;
7176 out++;
7177 }
7178 }
7179 Py_DECREF(rep);
7180 }
7181 /* write a NUL byte */
7182 *out = 0;
7183 outsize = out - PyBytes_AS_STRING(*outbytes);
7184 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7185 if (_PyBytes_Resize(outbytes, outsize) < 0)
7186 goto error;
7187 ret = 0;
7188
7189error:
7190 Py_XDECREF(encoding_obj);
7191 Py_XDECREF(errorHandler);
7192 Py_XDECREF(exc);
7193 return ret;
7194}
7195
Victor Stinner3a50e702011-10-18 21:21:00 +02007196static PyObject *
7197encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007198 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 const char *errors)
7200{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007201 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007203 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007204 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007205
Benjamin Petersonbac79492012-01-14 13:34:47 -05007206 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007207 return NULL;
7208 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007209
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 if (code_page < 0) {
7211 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7212 return NULL;
7213 }
7214
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007216 return PyBytes_FromStringAndSize(NULL, 0);
7217
Victor Stinner7581cef2011-11-03 22:32:33 +01007218 offset = 0;
7219 do
7220 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007221#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007223 chunks. */
7224 if (len > INT_MAX/2) {
7225 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007226 done = 0;
7227 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007228 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007229#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007230 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007231 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007232 done = 1;
7233 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007234
Victor Stinner76a31a62011-11-04 00:05:13 +01007235 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007236 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007237 errors);
7238 if (ret == -2)
7239 ret = encode_code_page_errors(code_page, &outbytes,
7240 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007241 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007242 if (ret < 0) {
7243 Py_XDECREF(outbytes);
7244 return NULL;
7245 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007246
Victor Stinner7581cef2011-11-03 22:32:33 +01007247 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007248 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007249 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007250
Victor Stinner3a50e702011-10-18 21:21:00 +02007251 return outbytes;
7252}
7253
7254PyObject *
7255PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7256 Py_ssize_t size,
7257 const char *errors)
7258{
Victor Stinner7581cef2011-11-03 22:32:33 +01007259 PyObject *unicode, *res;
7260 unicode = PyUnicode_FromUnicode(p, size);
7261 if (unicode == NULL)
7262 return NULL;
7263 res = encode_code_page(CP_ACP, unicode, errors);
7264 Py_DECREF(unicode);
7265 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007266}
7267
7268PyObject *
7269PyUnicode_EncodeCodePage(int code_page,
7270 PyObject *unicode,
7271 const char *errors)
7272{
Victor Stinner7581cef2011-11-03 22:32:33 +01007273 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007274}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007275
Alexander Belopolsky40018472011-02-26 01:02:56 +00007276PyObject *
7277PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007278{
7279 if (!PyUnicode_Check(unicode)) {
7280 PyErr_BadArgument();
7281 return NULL;
7282 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007283 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007284}
7285
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007286#undef NEED_RETRY
7287
Victor Stinner99b95382011-07-04 14:23:54 +02007288#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007289
Guido van Rossumd57fd912000-03-10 22:53:23 +00007290/* --- Character Mapping Codec -------------------------------------------- */
7291
Alexander Belopolsky40018472011-02-26 01:02:56 +00007292PyObject *
7293PyUnicode_DecodeCharmap(const char *s,
7294 Py_ssize_t size,
7295 PyObject *mapping,
7296 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007297{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007298 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007299 Py_ssize_t startinpos;
7300 Py_ssize_t endinpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007301 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007302 _PyUnicodeWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007303 PyObject *errorHandler = NULL;
7304 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007305
Guido van Rossumd57fd912000-03-10 22:53:23 +00007306 /* Default to Latin-1 */
7307 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007308 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007309
Guido van Rossumd57fd912000-03-10 22:53:23 +00007310 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007311 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007312 _PyUnicodeWriter_Init(&writer, 0);
7313 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007314 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007315
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007316 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007317 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007318 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007319 enum PyUnicode_Kind mapkind;
7320 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007321 Py_UCS4 x;
Victor Stinner03c3e352013-04-09 21:53:09 +02007322 unsigned char ch;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007323
Benjamin Petersonbac79492012-01-14 13:34:47 -05007324 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007325 return NULL;
7326
7327 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007328 mapdata = PyUnicode_DATA(mapping);
7329 mapkind = PyUnicode_KIND(mapping);
Victor Stinner03c3e352013-04-09 21:53:09 +02007330
7331 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7332 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7333 * is disabled in encoding aliases, latin1 is preferred because
7334 * its implementation is faster. */
7335 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7336 Py_UCS1 *outdata = (Py_UCS1 *)writer.data;
7337 Py_UCS4 maxchar = writer.maxchar;
7338
7339 assert (writer.kind == PyUnicode_1BYTE_KIND);
7340 while (s < e) {
7341 ch = *s;
7342 x = mapdata_ucs1[ch];
7343 if (x > maxchar) {
7344 if (_PyUnicodeWriter_PrepareInternal(&writer, 1, 0xff) == -1)
7345 goto onError;
7346 maxchar = writer.maxchar;
7347 outdata = (Py_UCS1 *)writer.data;
7348 }
7349 outdata[writer.pos] = x;
7350 writer.pos++;
7351 ++s;
7352 }
7353 }
7354
Benjamin Peterson29060642009-01-31 22:14:21 +00007355 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007356 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007357 enum PyUnicode_Kind outkind = writer.kind;
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007358 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007359 if (outkind == PyUnicode_1BYTE_KIND) {
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007360 Py_UCS1 *outdata = (Py_UCS1 *)writer.data;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007361 Py_UCS4 maxchar = writer.maxchar;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007362 while (s < e) {
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007363 ch = *s;
7364 x = mapdata_ucs2[ch];
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007365 if (x > maxchar)
7366 goto Error;
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007367 outdata[writer.pos] = x;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007368 writer.pos++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007369 ++s;
7370 }
7371 break;
7372 }
7373 else if (outkind == PyUnicode_2BYTE_KIND) {
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007374 Py_UCS2 *outdata = (Py_UCS2 *)writer.data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007375 while (s < e) {
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007376 ch = *s;
7377 x = mapdata_ucs2[ch];
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007378 if (x == 0xFFFE)
7379 goto Error;
Victor Stinner63d5c1a2013-04-09 22:13:33 +02007380 outdata[writer.pos] = x;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007381 writer.pos++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007382 ++s;
7383 }
7384 break;
7385 }
7386 }
7387 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007388
Benjamin Peterson29060642009-01-31 22:14:21 +00007389 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007390 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007391 else
7392 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007393Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007394 if (x == 0xfffe)
7395 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007396 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007397 startinpos = s-starts;
7398 endinpos = startinpos+1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007399 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00007400 errors, &errorHandler,
7401 "charmap", "character maps to <undefined>",
7402 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007403 &writer)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007404 goto onError;
7405 }
7406 continue;
7407 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007408
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007409 if (_PyUnicodeWriter_Prepare(&writer, 1, x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007410 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007411 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, x);
7412 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007413 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007414 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007415 }
7416 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007417 while (s < e) {
7418 unsigned char ch = *s;
7419 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007420
Benjamin Peterson29060642009-01-31 22:14:21 +00007421 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7422 w = PyLong_FromLong((long)ch);
7423 if (w == NULL)
7424 goto onError;
7425 x = PyObject_GetItem(mapping, w);
7426 Py_DECREF(w);
7427 if (x == NULL) {
7428 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7429 /* No mapping found means: mapping is undefined. */
7430 PyErr_Clear();
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007431 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007432 } else
7433 goto onError;
7434 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007435
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 /* Apply mapping */
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007437 if (x == Py_None)
7438 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007439 if (PyLong_Check(x)) {
7440 long value = PyLong_AS_LONG(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007441 if (value == 0xFFFE)
7442 goto Undefined;
Antoine Pitroua1f76552012-09-23 20:00:04 +02007443 if (value < 0 || value > MAX_UNICODE) {
7444 PyErr_Format(PyExc_TypeError,
7445 "character mapping must be in range(0x%lx)",
7446 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007447 Py_DECREF(x);
7448 goto onError;
7449 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007450
Serhiy Storchaka2aee6a62013-01-29 12:16:57 +02007451 if (_PyUnicodeWriter_Prepare(&writer, 1, value) == -1) {
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007452 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007453 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007454 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007455 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, value);
7456 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007457 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007458 else if (PyUnicode_Check(x)) {
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007459 if (PyUnicode_READY(x) == -1) {
7460 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007461 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007462 }
Serhiy Storchaka55e2cb42013-01-15 15:30:04 +02007463 if (PyUnicode_GET_LENGTH(x) == 1) {
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007464 Py_UCS4 value = PyUnicode_READ_CHAR(x, 0);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007465 if (value == 0xFFFE)
7466 goto Undefined;
Serhiy Storchaka2aee6a62013-01-29 12:16:57 +02007467 if (_PyUnicodeWriter_Prepare(&writer, 1, value) == -1) {
7468 Py_DECREF(x);
Serhiy Storchaka55e2cb42013-01-15 15:30:04 +02007469 goto onError;
Serhiy Storchaka2aee6a62013-01-29 12:16:57 +02007470 }
Serhiy Storchaka55e2cb42013-01-15 15:30:04 +02007471 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, value);
7472 writer.pos++;
7473 }
7474 else {
7475 writer.overallocate = 1;
Serhiy Storchaka2aee6a62013-01-29 12:16:57 +02007476 if (_PyUnicodeWriter_WriteStr(&writer, x) == -1) {
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007477 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007478 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007479 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007480 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 }
7482 else {
7483 /* wrong return value */
7484 PyErr_SetString(PyExc_TypeError,
7485 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007486 Py_DECREF(x);
7487 goto onError;
7488 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007489 Py_DECREF(x);
7490 ++s;
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007491 continue;
7492Undefined:
7493 /* undefined mapping */
7494 Py_XDECREF(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007495 startinpos = s-starts;
7496 endinpos = startinpos+1;
Serhiy Storchaka55e2cb42013-01-15 15:30:04 +02007497 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007498 errors, &errorHandler,
7499 "charmap", "character maps to <undefined>",
7500 &starts, &e, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka55e2cb42013-01-15 15:30:04 +02007501 &writer)) {
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007502 goto onError;
7503 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007504 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007505 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007506 Py_XDECREF(errorHandler);
7507 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007508 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007509
Benjamin Peterson29060642009-01-31 22:14:21 +00007510 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007511 Py_XDECREF(errorHandler);
7512 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007513 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007514 return NULL;
7515}
7516
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007517/* Charmap encoding: the lookup table */
7518
Alexander Belopolsky40018472011-02-26 01:02:56 +00007519struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 PyObject_HEAD
7521 unsigned char level1[32];
7522 int count2, count3;
7523 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007524};
7525
7526static PyObject*
7527encoding_map_size(PyObject *obj, PyObject* args)
7528{
7529 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007530 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007531 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007532}
7533
7534static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007535 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007536 PyDoc_STR("Return the size (in bytes) of this object") },
7537 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007538};
7539
7540static void
7541encoding_map_dealloc(PyObject* o)
7542{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007543 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007544}
7545
7546static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007547 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007548 "EncodingMap", /*tp_name*/
7549 sizeof(struct encoding_map), /*tp_basicsize*/
7550 0, /*tp_itemsize*/
7551 /* methods */
7552 encoding_map_dealloc, /*tp_dealloc*/
7553 0, /*tp_print*/
7554 0, /*tp_getattr*/
7555 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007556 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007557 0, /*tp_repr*/
7558 0, /*tp_as_number*/
7559 0, /*tp_as_sequence*/
7560 0, /*tp_as_mapping*/
7561 0, /*tp_hash*/
7562 0, /*tp_call*/
7563 0, /*tp_str*/
7564 0, /*tp_getattro*/
7565 0, /*tp_setattro*/
7566 0, /*tp_as_buffer*/
7567 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7568 0, /*tp_doc*/
7569 0, /*tp_traverse*/
7570 0, /*tp_clear*/
7571 0, /*tp_richcompare*/
7572 0, /*tp_weaklistoffset*/
7573 0, /*tp_iter*/
7574 0, /*tp_iternext*/
7575 encoding_map_methods, /*tp_methods*/
7576 0, /*tp_members*/
7577 0, /*tp_getset*/
7578 0, /*tp_base*/
7579 0, /*tp_dict*/
7580 0, /*tp_descr_get*/
7581 0, /*tp_descr_set*/
7582 0, /*tp_dictoffset*/
7583 0, /*tp_init*/
7584 0, /*tp_alloc*/
7585 0, /*tp_new*/
7586 0, /*tp_free*/
7587 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007588};
7589
7590PyObject*
7591PyUnicode_BuildEncodingMap(PyObject* string)
7592{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007593 PyObject *result;
7594 struct encoding_map *mresult;
7595 int i;
7596 int need_dict = 0;
7597 unsigned char level1[32];
7598 unsigned char level2[512];
7599 unsigned char *mlevel1, *mlevel2, *mlevel3;
7600 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007601 int kind;
7602 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007603 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007604 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007605
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007606 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007607 PyErr_BadArgument();
7608 return NULL;
7609 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007610 kind = PyUnicode_KIND(string);
7611 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007612 length = PyUnicode_GET_LENGTH(string);
7613 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007614 memset(level1, 0xFF, sizeof level1);
7615 memset(level2, 0xFF, sizeof level2);
7616
7617 /* If there isn't a one-to-one mapping of NULL to \0,
7618 or if there are non-BMP characters, we need to use
7619 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007620 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007621 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007622 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007623 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007624 ch = PyUnicode_READ(kind, data, i);
7625 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007626 need_dict = 1;
7627 break;
7628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007629 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007630 /* unmapped character */
7631 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007632 l1 = ch >> 11;
7633 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007634 if (level1[l1] == 0xFF)
7635 level1[l1] = count2++;
7636 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007637 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007638 }
7639
7640 if (count2 >= 0xFF || count3 >= 0xFF)
7641 need_dict = 1;
7642
7643 if (need_dict) {
7644 PyObject *result = PyDict_New();
7645 PyObject *key, *value;
7646 if (!result)
7647 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007648 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007649 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007650 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007651 if (!key || !value)
7652 goto failed1;
7653 if (PyDict_SetItem(result, key, value) == -1)
7654 goto failed1;
7655 Py_DECREF(key);
7656 Py_DECREF(value);
7657 }
7658 return result;
7659 failed1:
7660 Py_XDECREF(key);
7661 Py_XDECREF(value);
7662 Py_DECREF(result);
7663 return NULL;
7664 }
7665
7666 /* Create a three-level trie */
7667 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7668 16*count2 + 128*count3 - 1);
7669 if (!result)
7670 return PyErr_NoMemory();
7671 PyObject_Init(result, &EncodingMapType);
7672 mresult = (struct encoding_map*)result;
7673 mresult->count2 = count2;
7674 mresult->count3 = count3;
7675 mlevel1 = mresult->level1;
7676 mlevel2 = mresult->level23;
7677 mlevel3 = mresult->level23 + 16*count2;
7678 memcpy(mlevel1, level1, 32);
7679 memset(mlevel2, 0xFF, 16*count2);
7680 memset(mlevel3, 0, 128*count3);
7681 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007682 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007683 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007684 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7685 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007686 /* unmapped character */
7687 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007688 o1 = ch>>11;
7689 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007690 i2 = 16*mlevel1[o1] + o2;
7691 if (mlevel2[i2] == 0xFF)
7692 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007693 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007694 i3 = 128*mlevel2[i2] + o3;
7695 mlevel3[i3] = i;
7696 }
7697 return result;
7698}
7699
7700static int
Victor Stinner22168992011-11-20 17:09:18 +01007701encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007702{
7703 struct encoding_map *map = (struct encoding_map*)mapping;
7704 int l1 = c>>11;
7705 int l2 = (c>>7) & 0xF;
7706 int l3 = c & 0x7F;
7707 int i;
7708
Victor Stinner22168992011-11-20 17:09:18 +01007709 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007711 if (c == 0)
7712 return 0;
7713 /* level 1*/
7714 i = map->level1[l1];
7715 if (i == 0xFF) {
7716 return -1;
7717 }
7718 /* level 2*/
7719 i = map->level23[16*i+l2];
7720 if (i == 0xFF) {
7721 return -1;
7722 }
7723 /* level 3 */
7724 i = map->level23[16*map->count2 + 128*i + l3];
7725 if (i == 0) {
7726 return -1;
7727 }
7728 return i;
7729}
7730
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007731/* Lookup the character ch in the mapping. If the character
7732 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007733 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007734static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007735charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007736{
Christian Heimes217cfd12007-12-02 14:31:20 +00007737 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007738 PyObject *x;
7739
7740 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007742 x = PyObject_GetItem(mapping, w);
7743 Py_DECREF(w);
7744 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7746 /* No mapping found means: mapping is undefined. */
7747 PyErr_Clear();
7748 x = Py_None;
7749 Py_INCREF(x);
7750 return x;
7751 } else
7752 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007754 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007755 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007756 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007757 long value = PyLong_AS_LONG(x);
7758 if (value < 0 || value > 255) {
7759 PyErr_SetString(PyExc_TypeError,
7760 "character mapping must be in range(256)");
7761 Py_DECREF(x);
7762 return NULL;
7763 }
7764 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007765 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007766 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007767 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007768 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007769 /* wrong return value */
7770 PyErr_Format(PyExc_TypeError,
7771 "character mapping must return integer, bytes or None, not %.400s",
7772 x->ob_type->tp_name);
7773 Py_DECREF(x);
7774 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007775 }
7776}
7777
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007778static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007779charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007781 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7782 /* exponentially overallocate to minimize reallocations */
7783 if (requiredsize < 2*outsize)
7784 requiredsize = 2*outsize;
7785 if (_PyBytes_Resize(outobj, requiredsize))
7786 return -1;
7787 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007788}
7789
Benjamin Peterson14339b62009-01-31 16:36:08 +00007790typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007792} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007793/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007794 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007795 space is available. Return a new reference to the object that
7796 was put in the output buffer, or Py_None, if the mapping was undefined
7797 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007798 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007799static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007800charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007801 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007802{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007803 PyObject *rep;
7804 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007805 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007806
Christian Heimes90aa7642007-12-19 02:45:37 +00007807 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007808 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007809 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007810 if (res == -1)
7811 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 if (outsize<requiredsize)
7813 if (charmapencode_resize(outobj, outpos, requiredsize))
7814 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007815 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 outstart[(*outpos)++] = (char)res;
7817 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007818 }
7819
7820 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007821 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007823 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 Py_DECREF(rep);
7825 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007826 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007827 if (PyLong_Check(rep)) {
7828 Py_ssize_t requiredsize = *outpos+1;
7829 if (outsize<requiredsize)
7830 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7831 Py_DECREF(rep);
7832 return enc_EXCEPTION;
7833 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007834 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007835 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007836 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007837 else {
7838 const char *repchars = PyBytes_AS_STRING(rep);
7839 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7840 Py_ssize_t requiredsize = *outpos+repsize;
7841 if (outsize<requiredsize)
7842 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7843 Py_DECREF(rep);
7844 return enc_EXCEPTION;
7845 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007846 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 memcpy(outstart + *outpos, repchars, repsize);
7848 *outpos += repsize;
7849 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007850 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007851 Py_DECREF(rep);
7852 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007853}
7854
7855/* handle an error in PyUnicode_EncodeCharmap
7856 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007857static int
7858charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007859 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007860 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007861 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007862 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007863{
7864 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007865 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007866 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007867 enum PyUnicode_Kind kind;
7868 void *data;
7869 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007870 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007871 Py_ssize_t collstartpos = *inpos;
7872 Py_ssize_t collendpos = *inpos+1;
7873 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007874 char *encoding = "charmap";
7875 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007876 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007877 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007878 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007879
Benjamin Petersonbac79492012-01-14 13:34:47 -05007880 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007881 return -1;
7882 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007883 /* find all unencodable characters */
7884 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007886 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007887 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007888 val = encoding_map_lookup(ch, mapping);
7889 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 break;
7891 ++collendpos;
7892 continue;
7893 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007894
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007895 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7896 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007897 if (rep==NULL)
7898 return -1;
7899 else if (rep!=Py_None) {
7900 Py_DECREF(rep);
7901 break;
7902 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007903 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007905 }
7906 /* cache callback name lookup
7907 * (if not done yet, i.e. it's the first error) */
7908 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 if ((errors==NULL) || (!strcmp(errors, "strict")))
7910 *known_errorHandler = 1;
7911 else if (!strcmp(errors, "replace"))
7912 *known_errorHandler = 2;
7913 else if (!strcmp(errors, "ignore"))
7914 *known_errorHandler = 3;
7915 else if (!strcmp(errors, "xmlcharrefreplace"))
7916 *known_errorHandler = 4;
7917 else
7918 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919 }
7920 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007921 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007922 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007923 return -1;
7924 case 2: /* replace */
7925 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 x = charmapencode_output('?', mapping, res, respos);
7927 if (x==enc_EXCEPTION) {
7928 return -1;
7929 }
7930 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007931 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 return -1;
7933 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007934 }
7935 /* fall through */
7936 case 3: /* ignore */
7937 *inpos = collendpos;
7938 break;
7939 case 4: /* xmlcharrefreplace */
7940 /* generate replacement (temporarily (mis)uses p) */
7941 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 char buffer[2+29+1+1];
7943 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007944 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00007945 for (cp = buffer; *cp; ++cp) {
7946 x = charmapencode_output(*cp, mapping, res, respos);
7947 if (x==enc_EXCEPTION)
7948 return -1;
7949 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007950 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 return -1;
7952 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007953 }
7954 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007955 *inpos = collendpos;
7956 break;
7957 default:
7958 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007959 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007961 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007962 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007963 if (PyBytes_Check(repunicode)) {
7964 /* Directly copy bytes result to output. */
7965 Py_ssize_t outsize = PyBytes_Size(*res);
7966 Py_ssize_t requiredsize;
7967 repsize = PyBytes_Size(repunicode);
7968 requiredsize = *respos + repsize;
7969 if (requiredsize > outsize)
7970 /* Make room for all additional bytes. */
7971 if (charmapencode_resize(res, respos, requiredsize)) {
7972 Py_DECREF(repunicode);
7973 return -1;
7974 }
7975 memcpy(PyBytes_AsString(*res) + *respos,
7976 PyBytes_AsString(repunicode), repsize);
7977 *respos += repsize;
7978 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007979 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007980 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007981 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007982 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05007983 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007984 Py_DECREF(repunicode);
7985 return -1;
7986 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01007987 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007988 data = PyUnicode_DATA(repunicode);
7989 kind = PyUnicode_KIND(repunicode);
7990 for (index = 0; index < repsize; index++) {
7991 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
7992 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007994 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 return -1;
7996 }
7997 else if (x==enc_FAILED) {
7998 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007999 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 return -1;
8001 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008002 }
8003 *inpos = newpos;
8004 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008005 }
8006 return 0;
8007}
8008
Alexander Belopolsky40018472011-02-26 01:02:56 +00008009PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008010_PyUnicode_EncodeCharmap(PyObject *unicode,
8011 PyObject *mapping,
8012 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008013{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008014 /* output object */
8015 PyObject *res = NULL;
8016 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008017 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008018 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008019 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008020 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021 PyObject *errorHandler = NULL;
8022 PyObject *exc = NULL;
8023 /* the following variable is used for caching string comparisons
8024 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8025 * 3=ignore, 4=xmlcharrefreplace */
8026 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008027 void *data;
8028 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008029
Benjamin Petersonbac79492012-01-14 13:34:47 -05008030 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008031 return NULL;
8032 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008033 data = PyUnicode_DATA(unicode);
8034 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008035
Guido van Rossumd57fd912000-03-10 22:53:23 +00008036 /* Default to Latin-1 */
8037 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008038 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008039
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008040 /* allocate enough for a simple encoding without
8041 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008042 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043 if (res == NULL)
8044 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008045 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008047
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008048 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008049 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008051 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 if (x==enc_EXCEPTION) /* error */
8053 goto onError;
8054 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008055 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 &exc,
8057 &known_errorHandler, &errorHandler, errors,
8058 &res, &respos)) {
8059 goto onError;
8060 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008061 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 else
8063 /* done with this character => adjust input position */
8064 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008065 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008066
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008067 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008068 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008069 if (_PyBytes_Resize(&res, respos) < 0)
8070 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008071
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008072 Py_XDECREF(exc);
8073 Py_XDECREF(errorHandler);
8074 return res;
8075
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008077 Py_XDECREF(res);
8078 Py_XDECREF(exc);
8079 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008080 return NULL;
8081}
8082
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008083/* Deprecated */
8084PyObject *
8085PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8086 Py_ssize_t size,
8087 PyObject *mapping,
8088 const char *errors)
8089{
8090 PyObject *result;
8091 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8092 if (unicode == NULL)
8093 return NULL;
8094 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8095 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008096 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008097}
8098
Alexander Belopolsky40018472011-02-26 01:02:56 +00008099PyObject *
8100PyUnicode_AsCharmapString(PyObject *unicode,
8101 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008102{
8103 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 PyErr_BadArgument();
8105 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008106 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008107 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008108}
8109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008111static void
8112make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008113 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008114 Py_ssize_t startpos, Py_ssize_t endpos,
8115 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008116{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008118 *exceptionObject = _PyUnicodeTranslateError_Create(
8119 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008120 }
8121 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8123 goto onError;
8124 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8125 goto onError;
8126 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8127 goto onError;
8128 return;
8129 onError:
8130 Py_DECREF(*exceptionObject);
8131 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008132 }
8133}
8134
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135/* error handling callback helper:
8136 build arguments, call the callback and check the arguments,
8137 put the result into newpos and return the replacement string, which
8138 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008139static PyObject *
8140unicode_translate_call_errorhandler(const char *errors,
8141 PyObject **errorHandler,
8142 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008143 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008144 Py_ssize_t startpos, Py_ssize_t endpos,
8145 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008147 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008148
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008149 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008150 PyObject *restuple;
8151 PyObject *resunicode;
8152
8153 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008155 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008157 }
8158
8159 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008160 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008161 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008163
8164 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008166 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008168 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008169 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008170 Py_DECREF(restuple);
8171 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172 }
8173 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 &resunicode, &i_newpos)) {
8175 Py_DECREF(restuple);
8176 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008177 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008178 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008179 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008180 else
8181 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008182 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8184 Py_DECREF(restuple);
8185 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008186 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008187 Py_INCREF(resunicode);
8188 Py_DECREF(restuple);
8189 return resunicode;
8190}
8191
8192/* Lookup the character ch in the mapping and put the result in result,
8193 which must be decrefed by the caller.
8194 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008195static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008196charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197{
Christian Heimes217cfd12007-12-02 14:31:20 +00008198 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 PyObject *x;
8200
8201 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008203 x = PyObject_GetItem(mapping, w);
8204 Py_DECREF(w);
8205 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008206 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8207 /* No mapping found means: use 1:1 mapping. */
8208 PyErr_Clear();
8209 *result = NULL;
8210 return 0;
8211 } else
8212 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008213 }
8214 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 *result = x;
8216 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008217 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008218 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 long value = PyLong_AS_LONG(x);
8220 long max = PyUnicode_GetMax();
8221 if (value < 0 || value > max) {
8222 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008223 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 Py_DECREF(x);
8225 return -1;
8226 }
8227 *result = x;
8228 return 0;
8229 }
8230 else if (PyUnicode_Check(x)) {
8231 *result = x;
8232 return 0;
8233 }
8234 else {
8235 /* wrong return value */
8236 PyErr_SetString(PyExc_TypeError,
8237 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 Py_DECREF(x);
8239 return -1;
8240 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241}
8242/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 if not reallocate and adjust various state variables.
8244 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008245static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008246charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008248{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008249 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008250 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008251 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 /* exponentially overallocate to minimize reallocations */
8253 if (requiredsize < 2 * oldsize)
8254 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008255 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8256 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008258 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008259 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 }
8261 return 0;
8262}
8263/* lookup the character, put the result in the output string and adjust
8264 various state variables. Return a new reference to the object that
8265 was put in the output buffer in *result, or Py_None, if the mapping was
8266 undefined (in which case no character was written).
8267 The called must decref result.
8268 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008269static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008270charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8271 PyObject *mapping, Py_UCS4 **output,
8272 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008273 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008274{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008275 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8276 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008280 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 }
8282 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008283 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008284 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008286 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 }
8288 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008289 Py_ssize_t repsize;
8290 if (PyUnicode_READY(*res) == -1)
8291 return -1;
8292 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 if (repsize==1) {
8294 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008295 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 }
8297 else if (repsize!=0) {
8298 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008299 Py_ssize_t requiredsize = *opos +
8300 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008302 Py_ssize_t i;
8303 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008305 for(i = 0; i < repsize; i++)
8306 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 }
8309 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008311 return 0;
8312}
8313
Alexander Belopolsky40018472011-02-26 01:02:56 +00008314PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008315_PyUnicode_TranslateCharmap(PyObject *input,
8316 PyObject *mapping,
8317 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008319 /* input object */
8320 char *idata;
8321 Py_ssize_t size, i;
8322 int kind;
8323 /* output buffer */
8324 Py_UCS4 *output = NULL;
8325 Py_ssize_t osize;
8326 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008328 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329 char *reason = "character maps to <undefined>";
8330 PyObject *errorHandler = NULL;
8331 PyObject *exc = NULL;
8332 /* the following variable is used for caching string comparisons
8333 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8334 * 3=ignore, 4=xmlcharrefreplace */
8335 int known_errorHandler = -1;
8336
Guido van Rossumd57fd912000-03-10 22:53:23 +00008337 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008338 PyErr_BadArgument();
8339 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342 if (PyUnicode_READY(input) == -1)
8343 return NULL;
8344 idata = (char*)PyUnicode_DATA(input);
8345 kind = PyUnicode_KIND(input);
8346 size = PyUnicode_GET_LENGTH(input);
8347 i = 0;
8348
8349 if (size == 0) {
8350 Py_INCREF(input);
8351 return input;
8352 }
8353
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 /* allocate enough for a simple 1:1 translation without
8355 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008356 osize = size;
8357 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8358 opos = 0;
8359 if (output == NULL) {
8360 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008362 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008363
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 /* try to encode it */
8366 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008367 if (charmaptranslate_output(input, i, mapping,
8368 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 Py_XDECREF(x);
8370 goto onError;
8371 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008372 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008374 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 else { /* untranslatable character */
8376 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8377 Py_ssize_t repsize;
8378 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008381 Py_ssize_t collstart = i;
8382 Py_ssize_t collend = i+1;
8383 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008384
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008386 while (collend < size) {
8387 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 goto onError;
8389 Py_XDECREF(x);
8390 if (x!=Py_None)
8391 break;
8392 ++collend;
8393 }
8394 /* cache callback name lookup
8395 * (if not done yet, i.e. it's the first error) */
8396 if (known_errorHandler==-1) {
8397 if ((errors==NULL) || (!strcmp(errors, "strict")))
8398 known_errorHandler = 1;
8399 else if (!strcmp(errors, "replace"))
8400 known_errorHandler = 2;
8401 else if (!strcmp(errors, "ignore"))
8402 known_errorHandler = 3;
8403 else if (!strcmp(errors, "xmlcharrefreplace"))
8404 known_errorHandler = 4;
8405 else
8406 known_errorHandler = 0;
8407 }
8408 switch (known_errorHandler) {
8409 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008410 make_translate_exception(&exc,
8411 input, collstart, collend, reason);
8412 if (exc != NULL)
8413 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008414 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 case 2: /* replace */
8416 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417 for (coll = collstart; coll<collend; coll++)
8418 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 /* fall through */
8420 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008421 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 break;
8423 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 /* generate replacement (temporarily (mis)uses i) */
8425 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 char buffer[2+29+1+1];
8427 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8429 if (charmaptranslate_makespace(&output, &osize,
8430 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 goto onError;
8432 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008433 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 break;
8437 default:
8438 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 reason, input, &exc,
8440 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008441 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008443 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008444 Py_DECREF(repunicode);
8445 goto onError;
8446 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008448 repsize = PyUnicode_GET_LENGTH(repunicode);
8449 if (charmaptranslate_makespace(&output, &osize,
8450 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 Py_DECREF(repunicode);
8452 goto onError;
8453 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 for (uni2 = 0; repsize-->0; ++uni2)
8455 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8456 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008458 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 }
8460 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8462 if (!res)
8463 goto onError;
8464 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 Py_XDECREF(exc);
8466 Py_XDECREF(errorHandler);
8467 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008468
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 Py_XDECREF(exc);
8472 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008473 return NULL;
8474}
8475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008476/* Deprecated. Use PyUnicode_Translate instead. */
8477PyObject *
8478PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8479 Py_ssize_t size,
8480 PyObject *mapping,
8481 const char *errors)
8482{
Christian Heimes5f520f42012-09-11 14:03:25 +02008483 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8485 if (!unicode)
8486 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008487 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8488 Py_DECREF(unicode);
8489 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490}
8491
Alexander Belopolsky40018472011-02-26 01:02:56 +00008492PyObject *
8493PyUnicode_Translate(PyObject *str,
8494 PyObject *mapping,
8495 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496{
8497 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008498
Guido van Rossumd57fd912000-03-10 22:53:23 +00008499 str = PyUnicode_FromObject(str);
8500 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008501 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008503 Py_DECREF(str);
8504 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008505}
Tim Petersced69f82003-09-16 20:30:58 +00008506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008507static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008508fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509{
8510 /* No need to call PyUnicode_READY(self) because this function is only
8511 called as a callback from fixup() which does it already. */
8512 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8513 const int kind = PyUnicode_KIND(self);
8514 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008515 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008516 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 Py_ssize_t i;
8518
8519 for (i = 0; i < len; ++i) {
8520 ch = PyUnicode_READ(kind, data, i);
8521 fixed = 0;
8522 if (ch > 127) {
8523 if (Py_UNICODE_ISSPACE(ch))
8524 fixed = ' ';
8525 else {
8526 const int decimal = Py_UNICODE_TODECIMAL(ch);
8527 if (decimal >= 0)
8528 fixed = '0' + decimal;
8529 }
8530 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008531 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008532 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533 PyUnicode_WRITE(kind, data, i, fixed);
8534 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008535 else
8536 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 }
8539
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008540 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541}
8542
8543PyObject *
8544_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8545{
8546 if (!PyUnicode_Check(unicode)) {
8547 PyErr_BadInternalCall();
8548 return NULL;
8549 }
8550 if (PyUnicode_READY(unicode) == -1)
8551 return NULL;
8552 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8553 /* If the string is already ASCII, just return the same string */
8554 Py_INCREF(unicode);
8555 return unicode;
8556 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008557 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008558}
8559
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008560PyObject *
8561PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8562 Py_ssize_t length)
8563{
Victor Stinnerf0124502011-11-21 23:12:56 +01008564 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008565 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008566 Py_UCS4 maxchar;
8567 enum PyUnicode_Kind kind;
8568 void *data;
8569
Victor Stinner99d7ad02012-02-22 13:37:39 +01008570 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008571 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008572 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008573 if (ch > 127) {
8574 int decimal = Py_UNICODE_TODECIMAL(ch);
8575 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008576 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008577 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008578 }
8579 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008580
8581 /* Copy to a new string */
8582 decimal = PyUnicode_New(length, maxchar);
8583 if (decimal == NULL)
8584 return decimal;
8585 kind = PyUnicode_KIND(decimal);
8586 data = PyUnicode_DATA(decimal);
8587 /* Iterate over code points */
8588 for (i = 0; i < length; i++) {
8589 Py_UNICODE ch = s[i];
8590 if (ch > 127) {
8591 int decimal = Py_UNICODE_TODECIMAL(ch);
8592 if (decimal >= 0)
8593 ch = '0' + decimal;
8594 }
8595 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008597 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008598}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008599/* --- Decimal Encoder ---------------------------------------------------- */
8600
Alexander Belopolsky40018472011-02-26 01:02:56 +00008601int
8602PyUnicode_EncodeDecimal(Py_UNICODE *s,
8603 Py_ssize_t length,
8604 char *output,
8605 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008606{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008607 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008608 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008609 enum PyUnicode_Kind kind;
8610 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008611
8612 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 PyErr_BadArgument();
8614 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008615 }
8616
Victor Stinner42bf7752011-11-21 22:52:58 +01008617 unicode = PyUnicode_FromUnicode(s, length);
8618 if (unicode == NULL)
8619 return -1;
8620
Benjamin Petersonbac79492012-01-14 13:34:47 -05008621 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008622 Py_DECREF(unicode);
8623 return -1;
8624 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008625 kind = PyUnicode_KIND(unicode);
8626 data = PyUnicode_DATA(unicode);
8627
Victor Stinnerb84d7232011-11-22 01:50:07 +01008628 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008629 PyObject *exc;
8630 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008632 Py_ssize_t startpos;
8633
8634 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008635
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008637 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008638 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008640 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008641 decimal = Py_UNICODE_TODECIMAL(ch);
8642 if (decimal >= 0) {
8643 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008644 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 continue;
8646 }
8647 if (0 < ch && ch < 256) {
8648 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008649 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 continue;
8651 }
Victor Stinner6345be92011-11-25 20:09:01 +01008652
Victor Stinner42bf7752011-11-21 22:52:58 +01008653 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008654 exc = NULL;
8655 raise_encode_exception(&exc, "decimal", unicode,
8656 startpos, startpos+1,
8657 "invalid decimal Unicode string");
8658 Py_XDECREF(exc);
8659 Py_DECREF(unicode);
8660 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008661 }
8662 /* 0-terminate the output string */
8663 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008664 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008665 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008666}
8667
Guido van Rossumd57fd912000-03-10 22:53:23 +00008668/* --- Helpers ------------------------------------------------------------ */
8669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008671any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 Py_ssize_t start,
8673 Py_ssize_t end)
8674{
8675 int kind1, kind2, kind;
8676 void *buf1, *buf2;
8677 Py_ssize_t len1, len2, result;
8678
8679 kind1 = PyUnicode_KIND(s1);
8680 kind2 = PyUnicode_KIND(s2);
8681 kind = kind1 > kind2 ? kind1 : kind2;
8682 buf1 = PyUnicode_DATA(s1);
8683 buf2 = PyUnicode_DATA(s2);
8684 if (kind1 != kind)
8685 buf1 = _PyUnicode_AsKind(s1, kind);
8686 if (!buf1)
8687 return -2;
8688 if (kind2 != kind)
8689 buf2 = _PyUnicode_AsKind(s2, kind);
8690 if (!buf2) {
8691 if (kind1 != kind) PyMem_Free(buf1);
8692 return -2;
8693 }
8694 len1 = PyUnicode_GET_LENGTH(s1);
8695 len2 = PyUnicode_GET_LENGTH(s2);
8696
Victor Stinner794d5672011-10-10 03:21:36 +02008697 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008698 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008699 case PyUnicode_1BYTE_KIND:
8700 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8701 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8702 else
8703 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8704 break;
8705 case PyUnicode_2BYTE_KIND:
8706 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8707 break;
8708 case PyUnicode_4BYTE_KIND:
8709 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8710 break;
8711 default:
8712 assert(0); result = -2;
8713 }
8714 }
8715 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008716 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008717 case PyUnicode_1BYTE_KIND:
8718 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8719 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8720 else
8721 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8722 break;
8723 case PyUnicode_2BYTE_KIND:
8724 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8725 break;
8726 case PyUnicode_4BYTE_KIND:
8727 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8728 break;
8729 default:
8730 assert(0); result = -2;
8731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 }
8733
8734 if (kind1 != kind)
8735 PyMem_Free(buf1);
8736 if (kind2 != kind)
8737 PyMem_Free(buf2);
8738
8739 return result;
8740}
8741
8742Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008743_PyUnicode_InsertThousandsGrouping(
8744 PyObject *unicode, Py_ssize_t index,
8745 Py_ssize_t n_buffer,
8746 void *digits, Py_ssize_t n_digits,
8747 Py_ssize_t min_width,
8748 const char *grouping, PyObject *thousands_sep,
8749 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750{
Victor Stinner41a863c2012-02-24 00:37:51 +01008751 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008752 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008753 Py_ssize_t thousands_sep_len;
8754 Py_ssize_t len;
8755
8756 if (unicode != NULL) {
8757 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008758 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008759 }
8760 else {
8761 kind = PyUnicode_1BYTE_KIND;
8762 data = NULL;
8763 }
8764 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8765 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8766 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8767 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008768 if (thousands_sep_kind < kind) {
8769 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8770 if (!thousands_sep_data)
8771 return -1;
8772 }
8773 else {
8774 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8775 if (!data)
8776 return -1;
8777 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008778 }
8779
Benjamin Petersonead6b532011-12-20 17:23:42 -06008780 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008781 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008782 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008783 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008784 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008785 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008786 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008787 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008788 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008789 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008790 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008791 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008792 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008793 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008794 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008795 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008796 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008797 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008800 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008801 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008802 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008803 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008804 break;
8805 default:
8806 assert(0);
8807 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008809 if (unicode != NULL && thousands_sep_kind != kind) {
8810 if (thousands_sep_kind < kind)
8811 PyMem_Free(thousands_sep_data);
8812 else
8813 PyMem_Free(data);
8814 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008815 if (unicode == NULL) {
8816 *maxchar = 127;
8817 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008818 *maxchar = MAX_MAXCHAR(*maxchar,
8819 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008820 }
8821 }
8822 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823}
8824
8825
Thomas Wouters477c8d52006-05-27 19:21:47 +00008826/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008827#define ADJUST_INDICES(start, end, len) \
8828 if (end > len) \
8829 end = len; \
8830 else if (end < 0) { \
8831 end += len; \
8832 if (end < 0) \
8833 end = 0; \
8834 } \
8835 if (start < 0) { \
8836 start += len; \
8837 if (start < 0) \
8838 start = 0; \
8839 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008840
Alexander Belopolsky40018472011-02-26 01:02:56 +00008841Py_ssize_t
8842PyUnicode_Count(PyObject *str,
8843 PyObject *substr,
8844 Py_ssize_t start,
8845 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008846{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008847 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008848 PyObject* str_obj;
8849 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008850 int kind1, kind2, kind;
8851 void *buf1 = NULL, *buf2 = NULL;
8852 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008853
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008854 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008855 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008857 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008858 if (!sub_obj) {
8859 Py_DECREF(str_obj);
8860 return -1;
8861 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008862 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008863 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 Py_DECREF(str_obj);
8865 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008866 }
Tim Petersced69f82003-09-16 20:30:58 +00008867
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868 kind1 = PyUnicode_KIND(str_obj);
8869 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008870 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008872 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008873 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008874 if (kind2 > kind) {
8875 Py_DECREF(sub_obj);
8876 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008877 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008878 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008879 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008880 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881 if (!buf2)
8882 goto onError;
8883 len1 = PyUnicode_GET_LENGTH(str_obj);
8884 len2 = PyUnicode_GET_LENGTH(sub_obj);
8885
8886 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008887 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008888 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008889 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8890 result = asciilib_count(
8891 ((Py_UCS1*)buf1) + start, end - start,
8892 buf2, len2, PY_SSIZE_T_MAX
8893 );
8894 else
8895 result = ucs1lib_count(
8896 ((Py_UCS1*)buf1) + start, end - start,
8897 buf2, len2, PY_SSIZE_T_MAX
8898 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899 break;
8900 case PyUnicode_2BYTE_KIND:
8901 result = ucs2lib_count(
8902 ((Py_UCS2*)buf1) + start, end - start,
8903 buf2, len2, PY_SSIZE_T_MAX
8904 );
8905 break;
8906 case PyUnicode_4BYTE_KIND:
8907 result = ucs4lib_count(
8908 ((Py_UCS4*)buf1) + start, end - start,
8909 buf2, len2, PY_SSIZE_T_MAX
8910 );
8911 break;
8912 default:
8913 assert(0); result = 0;
8914 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008915
8916 Py_DECREF(sub_obj);
8917 Py_DECREF(str_obj);
8918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008919 if (kind2 != kind)
8920 PyMem_Free(buf2);
8921
Guido van Rossumd57fd912000-03-10 22:53:23 +00008922 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923 onError:
8924 Py_DECREF(sub_obj);
8925 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926 if (kind2 != kind && buf2)
8927 PyMem_Free(buf2);
8928 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008929}
8930
Alexander Belopolsky40018472011-02-26 01:02:56 +00008931Py_ssize_t
8932PyUnicode_Find(PyObject *str,
8933 PyObject *sub,
8934 Py_ssize_t start,
8935 Py_ssize_t end,
8936 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008937{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008938 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008939
Guido van Rossumd57fd912000-03-10 22:53:23 +00008940 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008941 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008943 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008944 if (!sub) {
8945 Py_DECREF(str);
8946 return -2;
8947 }
8948 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
8949 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00008950 Py_DECREF(str);
8951 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008952 }
Tim Petersced69f82003-09-16 20:30:58 +00008953
Victor Stinner794d5672011-10-10 03:21:36 +02008954 result = any_find_slice(direction,
8955 str, sub, start, end
8956 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00008957
Guido van Rossumd57fd912000-03-10 22:53:23 +00008958 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008959 Py_DECREF(sub);
8960
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961 return result;
8962}
8963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964Py_ssize_t
8965PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8966 Py_ssize_t start, Py_ssize_t end,
8967 int direction)
8968{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008970 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971 if (PyUnicode_READY(str) == -1)
8972 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008973 if (start < 0 || end < 0) {
8974 PyErr_SetString(PyExc_IndexError, "string index out of range");
8975 return -2;
8976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 if (end > PyUnicode_GET_LENGTH(str))
8978 end = PyUnicode_GET_LENGTH(str);
8979 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008980 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
8981 kind, end-start, ch, direction);
8982 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008984 else
8985 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008986}
8987
Alexander Belopolsky40018472011-02-26 01:02:56 +00008988static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008989tailmatch(PyObject *self,
8990 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008991 Py_ssize_t start,
8992 Py_ssize_t end,
8993 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008995 int kind_self;
8996 int kind_sub;
8997 void *data_self;
8998 void *data_sub;
8999 Py_ssize_t offset;
9000 Py_ssize_t i;
9001 Py_ssize_t end_sub;
9002
9003 if (PyUnicode_READY(self) == -1 ||
9004 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009005 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009006
9007 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008 return 1;
9009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009010 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9011 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009012 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009013 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015 kind_self = PyUnicode_KIND(self);
9016 data_self = PyUnicode_DATA(self);
9017 kind_sub = PyUnicode_KIND(substring);
9018 data_sub = PyUnicode_DATA(substring);
9019 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9020
9021 if (direction > 0)
9022 offset = end;
9023 else
9024 offset = start;
9025
9026 if (PyUnicode_READ(kind_self, data_self, offset) ==
9027 PyUnicode_READ(kind_sub, data_sub, 0) &&
9028 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9029 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9030 /* If both are of the same kind, memcmp is sufficient */
9031 if (kind_self == kind_sub) {
9032 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009033 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009034 data_sub,
9035 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009036 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037 }
9038 /* otherwise we have to compare each character by first accesing it */
9039 else {
9040 /* We do not need to compare 0 and len(substring)-1 because
9041 the if statement above ensured already that they are equal
9042 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 for (i = 1; i < end_sub; ++i) {
9044 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9045 PyUnicode_READ(kind_sub, data_sub, i))
9046 return 0;
9047 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009048 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009050 }
9051
9052 return 0;
9053}
9054
Alexander Belopolsky40018472011-02-26 01:02:56 +00009055Py_ssize_t
9056PyUnicode_Tailmatch(PyObject *str,
9057 PyObject *substr,
9058 Py_ssize_t start,
9059 Py_ssize_t end,
9060 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009062 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009063
Guido van Rossumd57fd912000-03-10 22:53:23 +00009064 str = PyUnicode_FromObject(str);
9065 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009066 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067 substr = PyUnicode_FromObject(substr);
9068 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009069 Py_DECREF(str);
9070 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009071 }
Tim Petersced69f82003-09-16 20:30:58 +00009072
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009073 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009074 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075 Py_DECREF(str);
9076 Py_DECREF(substr);
9077 return result;
9078}
9079
Guido van Rossumd57fd912000-03-10 22:53:23 +00009080/* Apply fixfct filter to the Unicode object self and return a
9081 reference to the modified object */
9082
Alexander Belopolsky40018472011-02-26 01:02:56 +00009083static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009084fixup(PyObject *self,
9085 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009086{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009087 PyObject *u;
9088 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009089 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009091 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009093 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009094 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009095
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 /* fix functions return the new maximum character in a string,
9097 if the kind of the resulting unicode object does not change,
9098 everything is fine. Otherwise we need to change the string kind
9099 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009100 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009101
9102 if (maxchar_new == 0) {
9103 /* no changes */;
9104 if (PyUnicode_CheckExact(self)) {
9105 Py_DECREF(u);
9106 Py_INCREF(self);
9107 return self;
9108 }
9109 else
9110 return u;
9111 }
9112
Victor Stinnere6abb482012-05-02 01:15:40 +02009113 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114
Victor Stinnereaab6042011-12-11 22:22:39 +01009115 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009116 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009117
9118 /* In case the maximum character changed, we need to
9119 convert the string to the new category. */
9120 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9121 if (v == NULL) {
9122 Py_DECREF(u);
9123 return NULL;
9124 }
9125 if (maxchar_new > maxchar_old) {
9126 /* If the maxchar increased so that the kind changed, not all
9127 characters are representable anymore and we need to fix the
9128 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009129 _PyUnicode_FastCopyCharacters(v, 0,
9130 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009131 maxchar_old = fixfct(v);
9132 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 }
9134 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009135 _PyUnicode_FastCopyCharacters(v, 0,
9136 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009138 Py_DECREF(u);
9139 assert(_PyUnicode_CheckConsistency(v, 1));
9140 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009141}
9142
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009143static PyObject *
9144ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009146 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9147 char *resdata, *data = PyUnicode_DATA(self);
9148 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009149
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009150 res = PyUnicode_New(len, 127);
9151 if (res == NULL)
9152 return NULL;
9153 resdata = PyUnicode_DATA(res);
9154 if (lower)
9155 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009156 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009157 _Py_bytes_upper(resdata, data, len);
9158 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009159}
9160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009162handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009164 Py_ssize_t j;
9165 int final_sigma;
9166 Py_UCS4 c;
9167 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009168
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009169 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9170
9171 where ! is a negation and \p{xxx} is a character with property xxx.
9172 */
9173 for (j = i - 1; j >= 0; j--) {
9174 c = PyUnicode_READ(kind, data, j);
9175 if (!_PyUnicode_IsCaseIgnorable(c))
9176 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009178 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9179 if (final_sigma) {
9180 for (j = i + 1; j < length; j++) {
9181 c = PyUnicode_READ(kind, data, j);
9182 if (!_PyUnicode_IsCaseIgnorable(c))
9183 break;
9184 }
9185 final_sigma = j == length || !_PyUnicode_IsCased(c);
9186 }
9187 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188}
9189
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009190static int
9191lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9192 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009193{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009194 /* Obscure special case. */
9195 if (c == 0x3A3) {
9196 mapped[0] = handle_capital_sigma(kind, data, length, i);
9197 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009198 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009199 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009200}
9201
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009202static Py_ssize_t
9203do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009205 Py_ssize_t i, k = 0;
9206 int n_res, j;
9207 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009208
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009209 c = PyUnicode_READ(kind, data, 0);
9210 n_res = _PyUnicode_ToUpperFull(c, mapped);
9211 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009212 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009213 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009215 for (i = 1; i < length; i++) {
9216 c = PyUnicode_READ(kind, data, i);
9217 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9218 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009219 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009220 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009221 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009222 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009223 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224}
9225
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009226static Py_ssize_t
9227do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9228 Py_ssize_t i, k = 0;
9229
9230 for (i = 0; i < length; i++) {
9231 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9232 int n_res, j;
9233 if (Py_UNICODE_ISUPPER(c)) {
9234 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9235 }
9236 else if (Py_UNICODE_ISLOWER(c)) {
9237 n_res = _PyUnicode_ToUpperFull(c, mapped);
9238 }
9239 else {
9240 n_res = 1;
9241 mapped[0] = c;
9242 }
9243 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009244 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009245 res[k++] = mapped[j];
9246 }
9247 }
9248 return k;
9249}
9250
9251static Py_ssize_t
9252do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9253 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009254{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009255 Py_ssize_t i, k = 0;
9256
9257 for (i = 0; i < length; i++) {
9258 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9259 int n_res, j;
9260 if (lower)
9261 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9262 else
9263 n_res = _PyUnicode_ToUpperFull(c, mapped);
9264 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009265 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009266 res[k++] = mapped[j];
9267 }
9268 }
9269 return k;
9270}
9271
9272static Py_ssize_t
9273do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9274{
9275 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9276}
9277
9278static Py_ssize_t
9279do_lower(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, 1);
9282}
9283
Benjamin Petersone51757f2012-01-12 21:10:29 -05009284static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009285do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9286{
9287 Py_ssize_t i, k = 0;
9288
9289 for (i = 0; i < length; i++) {
9290 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9291 Py_UCS4 mapped[3];
9292 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9293 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009294 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009295 res[k++] = mapped[j];
9296 }
9297 }
9298 return k;
9299}
9300
9301static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009302do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9303{
9304 Py_ssize_t i, k = 0;
9305 int previous_is_cased;
9306
9307 previous_is_cased = 0;
9308 for (i = 0; i < length; i++) {
9309 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9310 Py_UCS4 mapped[3];
9311 int n_res, j;
9312
9313 if (previous_is_cased)
9314 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9315 else
9316 n_res = _PyUnicode_ToTitleFull(c, mapped);
9317
9318 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009319 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009320 res[k++] = mapped[j];
9321 }
9322
9323 previous_is_cased = _PyUnicode_IsCased(c);
9324 }
9325 return k;
9326}
9327
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009328static PyObject *
9329case_operation(PyObject *self,
9330 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9331{
9332 PyObject *res = NULL;
9333 Py_ssize_t length, newlength = 0;
9334 int kind, outkind;
9335 void *data, *outdata;
9336 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9337
Benjamin Petersoneea48462012-01-16 14:28:50 -05009338 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009339
9340 kind = PyUnicode_KIND(self);
9341 data = PyUnicode_DATA(self);
9342 length = PyUnicode_GET_LENGTH(self);
9343 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9344 if (tmp == NULL)
9345 return PyErr_NoMemory();
9346 newlength = perform(kind, data, length, tmp, &maxchar);
9347 res = PyUnicode_New(newlength, maxchar);
9348 if (res == NULL)
9349 goto leave;
9350 tmpend = tmp + newlength;
9351 outdata = PyUnicode_DATA(res);
9352 outkind = PyUnicode_KIND(res);
9353 switch (outkind) {
9354 case PyUnicode_1BYTE_KIND:
9355 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9356 break;
9357 case PyUnicode_2BYTE_KIND:
9358 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9359 break;
9360 case PyUnicode_4BYTE_KIND:
9361 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9362 break;
9363 default:
9364 assert(0);
9365 break;
9366 }
9367 leave:
9368 PyMem_FREE(tmp);
9369 return res;
9370}
9371
Tim Peters8ce9f162004-08-27 01:49:32 +00009372PyObject *
9373PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009376 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009378 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009379 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9380 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009381 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009383 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009384 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009385 int use_memcpy;
9386 unsigned char *res_data = NULL, *sep_data = NULL;
9387 PyObject *last_obj;
9388 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389
Tim Peters05eba1f2004-08-27 21:32:02 +00009390 fseq = PySequence_Fast(seq, "");
9391 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009392 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009393 }
9394
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009395 /* NOTE: the following code can't call back into Python code,
9396 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009397 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009398
Tim Peters05eba1f2004-08-27 21:32:02 +00009399 seqlen = PySequence_Fast_GET_SIZE(fseq);
9400 /* If empty sequence, return u"". */
9401 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009402 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009403 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009404 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009405
Tim Peters05eba1f2004-08-27 21:32:02 +00009406 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009407 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009408 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009409 if (seqlen == 1) {
9410 if (PyUnicode_CheckExact(items[0])) {
9411 res = items[0];
9412 Py_INCREF(res);
9413 Py_DECREF(fseq);
9414 return res;
9415 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009416 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009417 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009418 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009419 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009420 /* Set up sep and seplen */
9421 if (separator == NULL) {
9422 /* fall back to a blank space separator */
9423 sep = PyUnicode_FromOrdinal(' ');
9424 if (!sep)
9425 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009426 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009427 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009428 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009429 else {
9430 if (!PyUnicode_Check(separator)) {
9431 PyErr_Format(PyExc_TypeError,
9432 "separator: expected str instance,"
9433 " %.80s found",
9434 Py_TYPE(separator)->tp_name);
9435 goto onError;
9436 }
9437 if (PyUnicode_READY(separator))
9438 goto onError;
9439 sep = separator;
9440 seplen = PyUnicode_GET_LENGTH(separator);
9441 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9442 /* inc refcount to keep this code path symmetric with the
9443 above case of a blank separator */
9444 Py_INCREF(sep);
9445 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009446 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009447 }
9448
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009449 /* There are at least two things to join, or else we have a subclass
9450 * of str in the sequence.
9451 * Do a pre-pass to figure out the total amount of space we'll
9452 * need (sz), and see whether all argument are strings.
9453 */
9454 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009455#ifdef Py_DEBUG
9456 use_memcpy = 0;
9457#else
9458 use_memcpy = 1;
9459#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009460 for (i = 0; i < seqlen; i++) {
9461 const Py_ssize_t old_sz = sz;
9462 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009463 if (!PyUnicode_Check(item)) {
9464 PyErr_Format(PyExc_TypeError,
9465 "sequence item %zd: expected str instance,"
9466 " %.80s found",
9467 i, Py_TYPE(item)->tp_name);
9468 goto onError;
9469 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 if (PyUnicode_READY(item) == -1)
9471 goto onError;
9472 sz += PyUnicode_GET_LENGTH(item);
9473 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009474 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009475 if (i != 0)
9476 sz += seplen;
9477 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9478 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009479 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009480 goto onError;
9481 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009482 if (use_memcpy && last_obj != NULL) {
9483 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9484 use_memcpy = 0;
9485 }
9486 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009487 }
Tim Petersced69f82003-09-16 20:30:58 +00009488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009490 if (res == NULL)
9491 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009492
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009493 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009494#ifdef Py_DEBUG
9495 use_memcpy = 0;
9496#else
9497 if (use_memcpy) {
9498 res_data = PyUnicode_1BYTE_DATA(res);
9499 kind = PyUnicode_KIND(res);
9500 if (seplen != 0)
9501 sep_data = PyUnicode_1BYTE_DATA(sep);
9502 }
9503#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009505 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009506 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009508 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009509 if (use_memcpy) {
9510 Py_MEMCPY(res_data,
9511 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009512 kind * seplen);
9513 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009514 }
9515 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009516 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009517 res_offset += seplen;
9518 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009519 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009520 itemlen = PyUnicode_GET_LENGTH(item);
9521 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009522 if (use_memcpy) {
9523 Py_MEMCPY(res_data,
9524 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009525 kind * itemlen);
9526 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009527 }
9528 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009529 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009530 res_offset += itemlen;
9531 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009532 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009533 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009534 if (use_memcpy)
9535 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009536 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009537 else
9538 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009539
Tim Peters05eba1f2004-08-27 21:32:02 +00009540 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009542 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009546 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009548 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009549 return NULL;
9550}
9551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552#define FILL(kind, data, value, start, length) \
9553 do { \
9554 Py_ssize_t i_ = 0; \
9555 assert(kind != PyUnicode_WCHAR_KIND); \
9556 switch ((kind)) { \
9557 case PyUnicode_1BYTE_KIND: { \
9558 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009559 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 break; \
9561 } \
9562 case PyUnicode_2BYTE_KIND: { \
9563 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9564 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9565 break; \
9566 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009567 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9569 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9570 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009571 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 } \
9573 } \
9574 } while (0)
9575
Victor Stinnerd3f08822012-05-29 12:57:52 +02009576void
9577_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9578 Py_UCS4 fill_char)
9579{
9580 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9581 const void *data = PyUnicode_DATA(unicode);
9582 assert(PyUnicode_IS_READY(unicode));
9583 assert(unicode_modifiable(unicode));
9584 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9585 assert(start >= 0);
9586 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9587 FILL(kind, data, fill_char, start, length);
9588}
9589
Victor Stinner3fe55312012-01-04 00:33:50 +01009590Py_ssize_t
9591PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9592 Py_UCS4 fill_char)
9593{
9594 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009595
9596 if (!PyUnicode_Check(unicode)) {
9597 PyErr_BadInternalCall();
9598 return -1;
9599 }
9600 if (PyUnicode_READY(unicode) == -1)
9601 return -1;
9602 if (unicode_check_modifiable(unicode))
9603 return -1;
9604
Victor Stinnerd3f08822012-05-29 12:57:52 +02009605 if (start < 0) {
9606 PyErr_SetString(PyExc_IndexError, "string index out of range");
9607 return -1;
9608 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009609 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9610 PyErr_SetString(PyExc_ValueError,
9611 "fill character is bigger than "
9612 "the string maximum character");
9613 return -1;
9614 }
9615
9616 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9617 length = Py_MIN(maxlen, length);
9618 if (length <= 0)
9619 return 0;
9620
Victor Stinnerd3f08822012-05-29 12:57:52 +02009621 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009622 return length;
9623}
9624
Victor Stinner9310abb2011-10-05 00:59:23 +02009625static PyObject *
9626pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009627 Py_ssize_t left,
9628 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 PyObject *u;
9632 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009633 int kind;
9634 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009635
9636 if (left < 0)
9637 left = 0;
9638 if (right < 0)
9639 right = 0;
9640
Victor Stinnerc4b49542011-12-11 22:44:26 +01009641 if (left == 0 && right == 0)
9642 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9645 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009646 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9647 return NULL;
9648 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009650 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009652 if (!u)
9653 return NULL;
9654
9655 kind = PyUnicode_KIND(u);
9656 data = PyUnicode_DATA(u);
9657 if (left)
9658 FILL(kind, data, fill, 0, left);
9659 if (right)
9660 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009661 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009662 assert(_PyUnicode_CheckConsistency(u, 1));
9663 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009664}
9665
Alexander Belopolsky40018472011-02-26 01:02:56 +00009666PyObject *
9667PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670
9671 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009672 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009673 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009674 if (PyUnicode_READY(string) == -1) {
9675 Py_DECREF(string);
9676 return NULL;
9677 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678
Benjamin Petersonead6b532011-12-20 17:23:42 -06009679 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009681 if (PyUnicode_IS_ASCII(string))
9682 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009683 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009684 PyUnicode_GET_LENGTH(string), keepends);
9685 else
9686 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009687 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009688 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689 break;
9690 case PyUnicode_2BYTE_KIND:
9691 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009692 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009693 PyUnicode_GET_LENGTH(string), keepends);
9694 break;
9695 case PyUnicode_4BYTE_KIND:
9696 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009697 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 PyUnicode_GET_LENGTH(string), keepends);
9699 break;
9700 default:
9701 assert(0);
9702 list = 0;
9703 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009704 Py_DECREF(string);
9705 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706}
9707
Alexander Belopolsky40018472011-02-26 01:02:56 +00009708static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009709split(PyObject *self,
9710 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009711 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009712{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009713 int kind1, kind2, kind;
9714 void *buf1, *buf2;
9715 Py_ssize_t len1, len2;
9716 PyObject* out;
9717
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009719 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 if (PyUnicode_READY(self) == -1)
9722 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009724 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009725 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009726 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009727 if (PyUnicode_IS_ASCII(self))
9728 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009729 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009730 PyUnicode_GET_LENGTH(self), maxcount
9731 );
9732 else
9733 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009734 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009735 PyUnicode_GET_LENGTH(self), maxcount
9736 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009737 case PyUnicode_2BYTE_KIND:
9738 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009739 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009740 PyUnicode_GET_LENGTH(self), maxcount
9741 );
9742 case PyUnicode_4BYTE_KIND:
9743 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009744 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009745 PyUnicode_GET_LENGTH(self), maxcount
9746 );
9747 default:
9748 assert(0);
9749 return NULL;
9750 }
9751
9752 if (PyUnicode_READY(substring) == -1)
9753 return NULL;
9754
9755 kind1 = PyUnicode_KIND(self);
9756 kind2 = PyUnicode_KIND(substring);
9757 kind = kind1 > kind2 ? kind1 : kind2;
9758 buf1 = PyUnicode_DATA(self);
9759 buf2 = PyUnicode_DATA(substring);
9760 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009761 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009762 if (!buf1)
9763 return NULL;
9764 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009765 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766 if (!buf2) {
9767 if (kind1 != kind) PyMem_Free(buf1);
9768 return NULL;
9769 }
9770 len1 = PyUnicode_GET_LENGTH(self);
9771 len2 = PyUnicode_GET_LENGTH(substring);
9772
Benjamin Petersonead6b532011-12-20 17:23:42 -06009773 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009775 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9776 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009777 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009778 else
9779 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009780 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009781 break;
9782 case PyUnicode_2BYTE_KIND:
9783 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009784 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 break;
9786 case PyUnicode_4BYTE_KIND:
9787 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009788 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009789 break;
9790 default:
9791 out = NULL;
9792 }
9793 if (kind1 != kind)
9794 PyMem_Free(buf1);
9795 if (kind2 != kind)
9796 PyMem_Free(buf2);
9797 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798}
9799
Alexander Belopolsky40018472011-02-26 01:02:56 +00009800static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009801rsplit(PyObject *self,
9802 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009803 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009805 int kind1, kind2, kind;
9806 void *buf1, *buf2;
9807 Py_ssize_t len1, len2;
9808 PyObject* out;
9809
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009810 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009811 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 if (PyUnicode_READY(self) == -1)
9814 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009816 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009817 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009818 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009819 if (PyUnicode_IS_ASCII(self))
9820 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009821 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009822 PyUnicode_GET_LENGTH(self), maxcount
9823 );
9824 else
9825 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009826 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009827 PyUnicode_GET_LENGTH(self), maxcount
9828 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 case PyUnicode_2BYTE_KIND:
9830 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009831 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 PyUnicode_GET_LENGTH(self), maxcount
9833 );
9834 case PyUnicode_4BYTE_KIND:
9835 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009836 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 PyUnicode_GET_LENGTH(self), maxcount
9838 );
9839 default:
9840 assert(0);
9841 return NULL;
9842 }
9843
9844 if (PyUnicode_READY(substring) == -1)
9845 return NULL;
9846
9847 kind1 = PyUnicode_KIND(self);
9848 kind2 = PyUnicode_KIND(substring);
9849 kind = kind1 > kind2 ? kind1 : kind2;
9850 buf1 = PyUnicode_DATA(self);
9851 buf2 = PyUnicode_DATA(substring);
9852 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009853 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 if (!buf1)
9855 return NULL;
9856 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009857 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009858 if (!buf2) {
9859 if (kind1 != kind) PyMem_Free(buf1);
9860 return NULL;
9861 }
9862 len1 = PyUnicode_GET_LENGTH(self);
9863 len2 = PyUnicode_GET_LENGTH(substring);
9864
Benjamin Petersonead6b532011-12-20 17:23:42 -06009865 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009867 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9868 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009869 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009870 else
9871 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009872 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 break;
9874 case PyUnicode_2BYTE_KIND:
9875 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009876 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 break;
9878 case PyUnicode_4BYTE_KIND:
9879 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009880 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 break;
9882 default:
9883 out = NULL;
9884 }
9885 if (kind1 != kind)
9886 PyMem_Free(buf1);
9887 if (kind2 != kind)
9888 PyMem_Free(buf2);
9889 return out;
9890}
9891
9892static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009893anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9894 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009896 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009898 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9899 return asciilib_find(buf1, len1, buf2, len2, offset);
9900 else
9901 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 case PyUnicode_2BYTE_KIND:
9903 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9904 case PyUnicode_4BYTE_KIND:
9905 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9906 }
9907 assert(0);
9908 return -1;
9909}
9910
9911static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009912anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9913 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009915 switch (kind) {
9916 case PyUnicode_1BYTE_KIND:
9917 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9918 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9919 else
9920 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9921 case PyUnicode_2BYTE_KIND:
9922 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9923 case PyUnicode_4BYTE_KIND:
9924 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9925 }
9926 assert(0);
9927 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009928}
9929
Alexander Belopolsky40018472011-02-26 01:02:56 +00009930static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931replace(PyObject *self, PyObject *str1,
9932 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 PyObject *u;
9935 char *sbuf = PyUnicode_DATA(self);
9936 char *buf1 = PyUnicode_DATA(str1);
9937 char *buf2 = PyUnicode_DATA(str2);
9938 int srelease = 0, release1 = 0, release2 = 0;
9939 int skind = PyUnicode_KIND(self);
9940 int kind1 = PyUnicode_KIND(str1);
9941 int kind2 = PyUnicode_KIND(str2);
9942 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9943 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9944 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009945 int mayshrink;
9946 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947
9948 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009949 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009951 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952
Victor Stinner59de0ee2011-10-07 10:01:28 +02009953 if (str1 == str2)
9954 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009955 if (skind < kind1)
9956 /* substring too wide to be present */
9957 goto nothing;
9958
Victor Stinner49a0a212011-10-12 23:46:10 +02009959 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9960 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
9961 /* Replacing str1 with str2 may cause a maxchar reduction in the
9962 result string. */
9963 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +02009964 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009967 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009969 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009971 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +02009972 Py_UCS4 u1, u2;
9973 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +01009974 Py_ssize_t index, pos;
9975 char *src;
9976
Victor Stinner69ed0f42013-04-09 21:48:24 +02009977 u1 = PyUnicode_READ(kind1, buf1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +01009978 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
9979 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009980 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +02009981 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009983 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +02009985 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +01009987
9988 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
9989 index = 0;
9990 src = sbuf;
9991 while (--maxcount)
9992 {
9993 pos++;
9994 src += pos * PyUnicode_KIND(self);
9995 slen -= pos;
9996 index += pos;
9997 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
9998 if (pos < 0)
9999 break;
10000 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10001 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010002 }
10003 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 int rkind = skind;
10005 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010006 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 if (kind1 < rkind) {
10009 /* widen substring */
10010 buf1 = _PyUnicode_AsKind(str1, rkind);
10011 if (!buf1) goto error;
10012 release1 = 1;
10013 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010014 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010015 if (i < 0)
10016 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 if (rkind > kind2) {
10018 /* widen replacement */
10019 buf2 = _PyUnicode_AsKind(str2, rkind);
10020 if (!buf2) goto error;
10021 release2 = 1;
10022 }
10023 else if (rkind < kind2) {
10024 /* widen self and buf1 */
10025 rkind = kind2;
10026 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010027 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 sbuf = _PyUnicode_AsKind(self, rkind);
10029 if (!sbuf) goto error;
10030 srelease = 1;
10031 buf1 = _PyUnicode_AsKind(str1, rkind);
10032 if (!buf1) goto error;
10033 release1 = 1;
10034 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010035 u = PyUnicode_New(slen, maxchar);
10036 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010038 assert(PyUnicode_KIND(u) == rkind);
10039 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010040
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010041 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010042 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010043 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010045 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010047
10048 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010049 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010050 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010051 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010052 if (i == -1)
10053 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010054 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010056 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010058 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010059 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010060 }
10061 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010063 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 int rkind = skind;
10065 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010068 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 buf1 = _PyUnicode_AsKind(str1, rkind);
10070 if (!buf1) goto error;
10071 release1 = 1;
10072 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010073 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010074 if (n == 0)
10075 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010077 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 buf2 = _PyUnicode_AsKind(str2, rkind);
10079 if (!buf2) goto error;
10080 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010083 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 rkind = kind2;
10085 sbuf = _PyUnicode_AsKind(self, rkind);
10086 if (!sbuf) goto error;
10087 srelease = 1;
10088 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010089 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 buf1 = _PyUnicode_AsKind(str1, rkind);
10091 if (!buf1) goto error;
10092 release1 = 1;
10093 }
10094 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10095 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010096 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 PyErr_SetString(PyExc_OverflowError,
10098 "replace string is too long");
10099 goto error;
10100 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010101 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010102 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010103 _Py_INCREF_UNICODE_EMPTY();
10104 if (!unicode_empty)
10105 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010106 u = unicode_empty;
10107 goto done;
10108 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010109 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 PyErr_SetString(PyExc_OverflowError,
10111 "replace string is too long");
10112 goto error;
10113 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010114 u = PyUnicode_New(new_size, maxchar);
10115 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010117 assert(PyUnicode_KIND(u) == rkind);
10118 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 ires = i = 0;
10120 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010121 while (n-- > 0) {
10122 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010123 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010124 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010125 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010126 if (j == -1)
10127 break;
10128 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010129 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010130 memcpy(res + rkind * ires,
10131 sbuf + rkind * i,
10132 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010134 }
10135 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010137 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010139 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010141 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010143 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010145 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010146 memcpy(res + rkind * ires,
10147 sbuf + rkind * i,
10148 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010149 }
10150 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010151 /* interleave */
10152 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010153 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010155 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010157 if (--n <= 0)
10158 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010159 memcpy(res + rkind * ires,
10160 sbuf + rkind * i,
10161 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 ires++;
10163 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010164 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010165 memcpy(res + rkind * ires,
10166 sbuf + rkind * i,
10167 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010168 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010169 }
10170
10171 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010172 unicode_adjust_maxchar(&u);
10173 if (u == NULL)
10174 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010176
10177 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 if (srelease)
10179 PyMem_FREE(sbuf);
10180 if (release1)
10181 PyMem_FREE(buf1);
10182 if (release2)
10183 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010184 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010186
Benjamin Peterson29060642009-01-31 22:14:21 +000010187 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010188 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 if (srelease)
10190 PyMem_FREE(sbuf);
10191 if (release1)
10192 PyMem_FREE(buf1);
10193 if (release2)
10194 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010195 return unicode_result_unchanged(self);
10196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 error:
10198 if (srelease && sbuf)
10199 PyMem_FREE(sbuf);
10200 if (release1 && buf1)
10201 PyMem_FREE(buf1);
10202 if (release2 && buf2)
10203 PyMem_FREE(buf2);
10204 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010205}
10206
10207/* --- Unicode Object Methods --------------------------------------------- */
10208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010209PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010210 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010211\n\
10212Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010213characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214
10215static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010216unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010217{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010218 if (PyUnicode_READY(self) == -1)
10219 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010220 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221}
10222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010223PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010224 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010225\n\
10226Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010227have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010228
10229static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010230unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010231{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010232 if (PyUnicode_READY(self) == -1)
10233 return NULL;
10234 if (PyUnicode_GET_LENGTH(self) == 0)
10235 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010236 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010237}
10238
Benjamin Petersond5890c82012-01-14 13:23:30 -050010239PyDoc_STRVAR(casefold__doc__,
10240 "S.casefold() -> str\n\
10241\n\
10242Return a version of S suitable for caseless comparisons.");
10243
10244static PyObject *
10245unicode_casefold(PyObject *self)
10246{
10247 if (PyUnicode_READY(self) == -1)
10248 return NULL;
10249 if (PyUnicode_IS_ASCII(self))
10250 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010251 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010252}
10253
10254
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010255/* Argument converter. Coerces to a single unicode character */
10256
10257static int
10258convert_uc(PyObject *obj, void *addr)
10259{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010261 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010262
Benjamin Peterson14339b62009-01-31 16:36:08 +000010263 uniobj = PyUnicode_FromObject(obj);
10264 if (uniobj == NULL) {
10265 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010266 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010267 return 0;
10268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010270 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010271 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010272 Py_DECREF(uniobj);
10273 return 0;
10274 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010276 Py_DECREF(uniobj);
10277 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010278}
10279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010280PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010281 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010282\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010283Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010284done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010285
10286static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010287unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010289 Py_ssize_t marg, left;
10290 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 Py_UCS4 fillchar = ' ';
10292
Victor Stinnere9a29352011-10-01 02:14:59 +020010293 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295
Benjamin Petersonbac79492012-01-14 13:34:47 -050010296 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010297 return NULL;
10298
Victor Stinnerc4b49542011-12-11 22:44:26 +010010299 if (PyUnicode_GET_LENGTH(self) >= width)
10300 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301
Victor Stinnerc4b49542011-12-11 22:44:26 +010010302 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303 left = marg / 2 + (marg & width & 1);
10304
Victor Stinner9310abb2011-10-05 00:59:23 +020010305 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306}
10307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308/* This function assumes that str1 and str2 are readied by the caller. */
10309
Marc-André Lemburge5034372000-08-08 08:04:29 +000010310static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010311unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010312{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010313#define COMPARE(TYPE1, TYPE2) \
10314 do { \
10315 TYPE1* p1 = (TYPE1 *)data1; \
10316 TYPE2* p2 = (TYPE2 *)data2; \
10317 TYPE1* end = p1 + len; \
10318 Py_UCS4 c1, c2; \
10319 for (; p1 != end; p1++, p2++) { \
10320 c1 = *p1; \
10321 c2 = *p2; \
10322 if (c1 != c2) \
10323 return (c1 < c2) ? -1 : 1; \
10324 } \
10325 } \
10326 while (0)
10327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 int kind1, kind2;
10329 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010330 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010331
Victor Stinner90db9c42012-10-04 21:53:50 +020010332 /* a string is equal to itself */
10333 if (str1 == str2)
10334 return 0;
10335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 kind1 = PyUnicode_KIND(str1);
10337 kind2 = PyUnicode_KIND(str2);
10338 data1 = PyUnicode_DATA(str1);
10339 data2 = PyUnicode_DATA(str2);
10340 len1 = PyUnicode_GET_LENGTH(str1);
10341 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010342 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010343
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010344 switch(kind1) {
10345 case PyUnicode_1BYTE_KIND:
10346 {
10347 switch(kind2) {
10348 case PyUnicode_1BYTE_KIND:
10349 {
10350 int cmp = memcmp(data1, data2, len);
10351 /* normalize result of memcmp() into the range [-1; 1] */
10352 if (cmp < 0)
10353 return -1;
10354 if (cmp > 0)
10355 return 1;
10356 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010357 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010358 case PyUnicode_2BYTE_KIND:
10359 COMPARE(Py_UCS1, Py_UCS2);
10360 break;
10361 case PyUnicode_4BYTE_KIND:
10362 COMPARE(Py_UCS1, Py_UCS4);
10363 break;
10364 default:
10365 assert(0);
10366 }
10367 break;
10368 }
10369 case PyUnicode_2BYTE_KIND:
10370 {
10371 switch(kind2) {
10372 case PyUnicode_1BYTE_KIND:
10373 COMPARE(Py_UCS2, Py_UCS1);
10374 break;
10375 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010376 {
10377#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 2
10378 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10379 /* normalize result of wmemcmp() into the range [-1; 1] */
10380 if (cmp < 0)
10381 return -1;
10382 if (cmp > 0)
10383 return 1;
10384#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010385 COMPARE(Py_UCS2, Py_UCS2);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010386#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010387 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010388 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010389 case PyUnicode_4BYTE_KIND:
10390 COMPARE(Py_UCS2, Py_UCS4);
10391 break;
10392 default:
10393 assert(0);
10394 }
10395 break;
10396 }
10397 case PyUnicode_4BYTE_KIND:
10398 {
10399 switch(kind2) {
10400 case PyUnicode_1BYTE_KIND:
10401 COMPARE(Py_UCS4, Py_UCS1);
10402 break;
10403 case PyUnicode_2BYTE_KIND:
10404 COMPARE(Py_UCS4, Py_UCS2);
10405 break;
10406 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010407 {
10408#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10409 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10410 /* normalize result of wmemcmp() into the range [-1; 1] */
10411 if (cmp < 0)
10412 return -1;
10413 if (cmp > 0)
10414 return 1;
10415#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010416 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010417#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010418 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010419 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010420 default:
10421 assert(0);
10422 }
10423 break;
10424 }
10425 default:
10426 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010427 }
10428
Victor Stinner770e19e2012-10-04 22:59:45 +020010429 if (len1 == len2)
10430 return 0;
10431 if (len1 < len2)
10432 return -1;
10433 else
10434 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010435
10436#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010437}
10438
Victor Stinnere5567ad2012-10-23 02:48:49 +020010439static int
10440unicode_compare_eq(PyObject *str1, PyObject *str2)
10441{
10442 int kind;
10443 void *data1, *data2;
10444 Py_ssize_t len;
10445 int cmp;
10446
10447 /* a string is equal to itself */
10448 if (str1 == str2)
10449 return 1;
10450
10451 len = PyUnicode_GET_LENGTH(str1);
10452 if (PyUnicode_GET_LENGTH(str2) != len)
10453 return 0;
10454 kind = PyUnicode_KIND(str1);
10455 if (PyUnicode_KIND(str2) != kind)
10456 return 0;
10457 data1 = PyUnicode_DATA(str1);
10458 data2 = PyUnicode_DATA(str2);
10459
10460 cmp = memcmp(data1, data2, len * kind);
10461 return (cmp == 0);
10462}
10463
10464
Alexander Belopolsky40018472011-02-26 01:02:56 +000010465int
10466PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10469 if (PyUnicode_READY(left) == -1 ||
10470 PyUnicode_READY(right) == -1)
10471 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010472 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010474 PyErr_Format(PyExc_TypeError,
10475 "Can't compare %.100s and %.100s",
10476 left->ob_type->tp_name,
10477 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010478 return -1;
10479}
10480
Martin v. Löwis5b222132007-06-10 09:51:05 +000010481int
10482PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 Py_ssize_t i;
10485 int kind;
10486 void *data;
10487 Py_UCS4 chr;
10488
Victor Stinner910337b2011-10-03 03:20:16 +020010489 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 if (PyUnicode_READY(uni) == -1)
10491 return -1;
10492 kind = PyUnicode_KIND(uni);
10493 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010494 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10496 if (chr != str[i])
10497 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010498 /* This check keeps Python strings that end in '\0' from comparing equal
10499 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010501 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010502 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010503 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010504 return 0;
10505}
10506
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010507
Benjamin Peterson29060642009-01-31 22:14:21 +000010508#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010509 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010510
Alexander Belopolsky40018472011-02-26 01:02:56 +000010511PyObject *
10512PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010513{
10514 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010515 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010516
Victor Stinnere5567ad2012-10-23 02:48:49 +020010517 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10518 Py_RETURN_NOTIMPLEMENTED;
10519
10520 if (PyUnicode_READY(left) == -1 ||
10521 PyUnicode_READY(right) == -1)
10522 return NULL;
10523
10524 if (op == Py_EQ || op == Py_NE) {
10525 result = unicode_compare_eq(left, right);
10526 if (op == Py_EQ)
10527 v = TEST_COND(result);
10528 else
10529 v = TEST_COND(!result);
10530 }
10531 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010532 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010533
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010534 /* Convert the return value to a Boolean */
10535 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010536 case Py_LE:
10537 v = TEST_COND(result <= 0);
10538 break;
10539 case Py_GE:
10540 v = TEST_COND(result >= 0);
10541 break;
10542 case Py_LT:
10543 v = TEST_COND(result == -1);
10544 break;
10545 case Py_GT:
10546 v = TEST_COND(result == 1);
10547 break;
10548 default:
10549 PyErr_BadArgument();
10550 return NULL;
10551 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010552 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010553 Py_INCREF(v);
10554 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010555}
10556
Alexander Belopolsky40018472011-02-26 01:02:56 +000010557int
10558PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010559{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010560 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 int kind1, kind2, kind;
10562 void *buf1, *buf2;
10563 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010564 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010565
10566 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010567 sub = PyUnicode_FromObject(element);
10568 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010569 PyErr_Format(PyExc_TypeError,
10570 "'in <string>' requires string as left operand, not %s",
10571 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010572 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010573 }
10574
Thomas Wouters477c8d52006-05-27 19:21:47 +000010575 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010576 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010577 Py_DECREF(sub);
10578 return -1;
10579 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010580 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10581 Py_DECREF(sub);
10582 Py_DECREF(str);
10583 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 kind1 = PyUnicode_KIND(str);
10586 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010587 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 buf1 = PyUnicode_DATA(str);
10589 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010590 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010591 if (kind2 > kind) {
10592 Py_DECREF(sub);
10593 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010594 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010595 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010596 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010597 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 if (!buf2) {
10599 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010600 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 return -1;
10602 }
10603 len1 = PyUnicode_GET_LENGTH(str);
10604 len2 = PyUnicode_GET_LENGTH(sub);
10605
Benjamin Petersonead6b532011-12-20 17:23:42 -060010606 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 case PyUnicode_1BYTE_KIND:
10608 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10609 break;
10610 case PyUnicode_2BYTE_KIND:
10611 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10612 break;
10613 case PyUnicode_4BYTE_KIND:
10614 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10615 break;
10616 default:
10617 result = -1;
10618 assert(0);
10619 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010620
10621 Py_DECREF(str);
10622 Py_DECREF(sub);
10623
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 if (kind2 != kind)
10625 PyMem_Free(buf2);
10626
Guido van Rossum403d68b2000-03-13 15:55:09 +000010627 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010628}
10629
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630/* Concat to string or Unicode object giving a new Unicode object. */
10631
Alexander Belopolsky40018472011-02-26 01:02:56 +000010632PyObject *
10633PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010636 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010637 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638
10639 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010642 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010645 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010646
10647 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010648 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010652 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010653 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010655 }
10656
Victor Stinner488fa492011-12-12 00:01:39 +010010657 u_len = PyUnicode_GET_LENGTH(u);
10658 v_len = PyUnicode_GET_LENGTH(v);
10659 if (u_len > PY_SSIZE_T_MAX - v_len) {
10660 PyErr_SetString(PyExc_OverflowError,
10661 "strings are too large to concat");
10662 goto onError;
10663 }
10664 new_len = u_len + v_len;
10665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010667 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010668 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010671 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010673 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010674 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10675 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676 Py_DECREF(u);
10677 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010678 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680
Benjamin Peterson29060642009-01-31 22:14:21 +000010681 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010682 Py_XDECREF(u);
10683 Py_XDECREF(v);
10684 return NULL;
10685}
10686
Walter Dörwald1ab83302007-05-18 17:15:44 +000010687void
Victor Stinner23e56682011-10-03 03:54:37 +020010688PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010689{
Victor Stinner23e56682011-10-03 03:54:37 +020010690 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010691 Py_UCS4 maxchar, maxchar2;
10692 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010693
10694 if (p_left == NULL) {
10695 if (!PyErr_Occurred())
10696 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010697 return;
10698 }
Victor Stinner23e56682011-10-03 03:54:37 +020010699 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010700 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010701 if (!PyErr_Occurred())
10702 PyErr_BadInternalCall();
10703 goto error;
10704 }
10705
Benjamin Petersonbac79492012-01-14 13:34:47 -050010706 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010707 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010708 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010709 goto error;
10710
Victor Stinner488fa492011-12-12 00:01:39 +010010711 /* Shortcuts */
10712 if (left == unicode_empty) {
10713 Py_DECREF(left);
10714 Py_INCREF(right);
10715 *p_left = right;
10716 return;
10717 }
10718 if (right == unicode_empty)
10719 return;
10720
10721 left_len = PyUnicode_GET_LENGTH(left);
10722 right_len = PyUnicode_GET_LENGTH(right);
10723 if (left_len > PY_SSIZE_T_MAX - right_len) {
10724 PyErr_SetString(PyExc_OverflowError,
10725 "strings are too large to concat");
10726 goto error;
10727 }
10728 new_len = left_len + right_len;
10729
10730 if (unicode_modifiable(left)
10731 && PyUnicode_CheckExact(right)
10732 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010733 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10734 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010735 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010736 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010737 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10738 {
10739 /* append inplace */
10740 if (unicode_resize(p_left, new_len) != 0) {
10741 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10742 * deallocated so it cannot be put back into
10743 * 'variable'. The MemoryError is raised when there
10744 * is no value in 'variable', which might (very
10745 * remotely) be a cause of incompatibilities.
10746 */
10747 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010748 }
Victor Stinner488fa492011-12-12 00:01:39 +010010749 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010750 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010751 }
Victor Stinner488fa492011-12-12 00:01:39 +010010752 else {
10753 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10754 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010755 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010756
Victor Stinner488fa492011-12-12 00:01:39 +010010757 /* Concat the two Unicode strings */
10758 res = PyUnicode_New(new_len, maxchar);
10759 if (res == NULL)
10760 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010761 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10762 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010763 Py_DECREF(left);
10764 *p_left = res;
10765 }
10766 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010767 return;
10768
10769error:
Victor Stinner488fa492011-12-12 00:01:39 +010010770 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010771}
10772
10773void
10774PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10775{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010776 PyUnicode_Append(pleft, right);
10777 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010778}
10779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010780PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010781 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010783Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010784string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010785interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786
10787static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010788unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010790 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010791 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010792 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010793 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 int kind1, kind2, kind;
10795 void *buf1, *buf2;
10796 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797
Jesus Ceaac451502011-04-20 17:09:23 +020010798 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10799 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010800 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 kind1 = PyUnicode_KIND(self);
10803 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010804 if (kind2 > kind1)
10805 return PyLong_FromLong(0);
10806 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 buf1 = PyUnicode_DATA(self);
10808 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010810 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010811 if (!buf2) {
10812 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010813 return NULL;
10814 }
10815 len1 = PyUnicode_GET_LENGTH(self);
10816 len2 = PyUnicode_GET_LENGTH(substring);
10817
10818 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010819 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010820 case PyUnicode_1BYTE_KIND:
10821 iresult = ucs1lib_count(
10822 ((Py_UCS1*)buf1) + start, end - start,
10823 buf2, len2, PY_SSIZE_T_MAX
10824 );
10825 break;
10826 case PyUnicode_2BYTE_KIND:
10827 iresult = ucs2lib_count(
10828 ((Py_UCS2*)buf1) + start, end - start,
10829 buf2, len2, PY_SSIZE_T_MAX
10830 );
10831 break;
10832 case PyUnicode_4BYTE_KIND:
10833 iresult = ucs4lib_count(
10834 ((Py_UCS4*)buf1) + start, end - start,
10835 buf2, len2, PY_SSIZE_T_MAX
10836 );
10837 break;
10838 default:
10839 assert(0); iresult = 0;
10840 }
10841
10842 result = PyLong_FromSsize_t(iresult);
10843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844 if (kind2 != kind)
10845 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846
10847 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010848
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849 return result;
10850}
10851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010852PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010853 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010854\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010855Encode S using the codec registered for encoding. Default encoding\n\
10856is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010857handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010858a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10859'xmlcharrefreplace' as well as any other name registered with\n\
10860codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861
10862static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010863unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010865 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010866 char *encoding = NULL;
10867 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010868
Benjamin Peterson308d6372009-09-18 21:42:35 +000010869 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10870 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010872 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010873}
10874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010875PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010876 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877\n\
10878Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010879If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880
10881static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010882unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010883{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010884 Py_ssize_t i, j, line_pos, src_len, incr;
10885 Py_UCS4 ch;
10886 PyObject *u;
10887 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010889 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010890 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891
10892 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010893 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894
Antoine Pitrou22425222011-10-04 19:10:51 +020010895 if (PyUnicode_READY(self) == -1)
10896 return NULL;
10897
Thomas Wouters7e474022000-07-16 12:04:32 +000010898 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010899 src_len = PyUnicode_GET_LENGTH(self);
10900 i = j = line_pos = 0;
10901 kind = PyUnicode_KIND(self);
10902 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010903 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010904 for (; i < src_len; i++) {
10905 ch = PyUnicode_READ(kind, src_data, i);
10906 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010907 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010908 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010909 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010910 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010911 goto overflow;
10912 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010913 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010914 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010915 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010917 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010918 goto overflow;
10919 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 if (ch == '\n' || ch == '\r')
10922 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010924 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010925 if (!found)
10926 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010927
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010929 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010930 if (!u)
10931 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010932 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935
Antoine Pitroue71d5742011-10-04 15:55:09 +020010936 for (; i < src_len; i++) {
10937 ch = PyUnicode_READ(kind, src_data, i);
10938 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010939 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010940 incr = tabsize - (line_pos % tabsize);
10941 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010942 FILL(kind, dest_data, ' ', j, incr);
10943 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010944 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010945 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010946 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010947 line_pos++;
10948 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010949 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010950 if (ch == '\n' || ch == '\r')
10951 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010953 }
10954 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010955 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010956
Antoine Pitroue71d5742011-10-04 15:55:09 +020010957 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010958 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10959 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960}
10961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010962PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010963 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964\n\
10965Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010966such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967arguments start and end are interpreted as in slice notation.\n\
10968\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010969Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
10971static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010972unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010974 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010975 Py_ssize_t start;
10976 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010977 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978
Jesus Ceaac451502011-04-20 17:09:23 +020010979 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10980 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 if (PyUnicode_READY(self) == -1)
10984 return NULL;
10985 if (PyUnicode_READY(substring) == -1)
10986 return NULL;
10987
Victor Stinner7931d9a2011-11-04 00:22:48 +010010988 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010989
10990 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010992 if (result == -2)
10993 return NULL;
10994
Christian Heimes217cfd12007-12-02 14:31:20 +000010995 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996}
10997
10998static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010999unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011001 void *data;
11002 enum PyUnicode_Kind kind;
11003 Py_UCS4 ch;
11004 PyObject *res;
11005
11006 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11007 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011008 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011009 }
11010 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11011 PyErr_SetString(PyExc_IndexError, "string index out of range");
11012 return NULL;
11013 }
11014 kind = PyUnicode_KIND(self);
11015 data = PyUnicode_DATA(self);
11016 ch = PyUnicode_READ(kind, data, index);
11017 if (ch < 256)
11018 return get_latin1_char(ch);
11019
11020 res = PyUnicode_New(1, ch);
11021 if (res == NULL)
11022 return NULL;
11023 kind = PyUnicode_KIND(res);
11024 data = PyUnicode_DATA(res);
11025 PyUnicode_WRITE(kind, data, 0, ch);
11026 assert(_PyUnicode_CheckConsistency(res, 1));
11027 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028}
11029
Guido van Rossumc2504932007-09-18 19:42:40 +000011030/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011031 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011032static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011033unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034{
Guido van Rossumc2504932007-09-18 19:42:40 +000011035 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011036 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011037
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011038#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011039 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011040#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011041 if (_PyUnicode_HASH(self) != -1)
11042 return _PyUnicode_HASH(self);
11043 if (PyUnicode_READY(self) == -1)
11044 return -1;
11045 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011046 /*
11047 We make the hash of the empty string be 0, rather than using
11048 (prefix ^ suffix), since this slightly obfuscates the hash secret
11049 */
11050 if (len == 0) {
11051 _PyUnicode_HASH(self) = 0;
11052 return 0;
11053 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054
11055 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011056#define HASH(P) \
11057 x ^= (Py_uhash_t) *P << 7; \
11058 while (--len >= 0) \
11059 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011060
Georg Brandl2fb477c2012-02-21 00:33:36 +010011061 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011062 switch (PyUnicode_KIND(self)) {
11063 case PyUnicode_1BYTE_KIND: {
11064 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11065 HASH(c);
11066 break;
11067 }
11068 case PyUnicode_2BYTE_KIND: {
11069 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11070 HASH(s);
11071 break;
11072 }
11073 default: {
11074 Py_UCS4 *l;
11075 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11076 "Impossible switch case in unicode_hash");
11077 l = PyUnicode_4BYTE_DATA(self);
11078 HASH(l);
11079 break;
11080 }
11081 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011082 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11083 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011084
Guido van Rossumc2504932007-09-18 19:42:40 +000011085 if (x == -1)
11086 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011087 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011088 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011092PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011093 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011095Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
11097static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011100 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011101 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011102 Py_ssize_t start;
11103 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104
Jesus Ceaac451502011-04-20 17:09:23 +020011105 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11106 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011109 if (PyUnicode_READY(self) == -1)
11110 return NULL;
11111 if (PyUnicode_READY(substring) == -1)
11112 return NULL;
11113
Victor Stinner7931d9a2011-11-04 00:22:48 +010011114 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115
11116 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011118 if (result == -2)
11119 return NULL;
11120
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 if (result < 0) {
11122 PyErr_SetString(PyExc_ValueError, "substring not found");
11123 return NULL;
11124 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011125
Christian Heimes217cfd12007-12-02 14:31:20 +000011126 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127}
11128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011129PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011130 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011132Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011133at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134
11135static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011136unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 Py_ssize_t i, length;
11139 int kind;
11140 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141 int cased;
11142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 if (PyUnicode_READY(self) == -1)
11144 return NULL;
11145 length = PyUnicode_GET_LENGTH(self);
11146 kind = PyUnicode_KIND(self);
11147 data = PyUnicode_DATA(self);
11148
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 if (length == 1)
11151 return PyBool_FromLong(
11152 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011154 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011156 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011157
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 for (i = 0; i < length; i++) {
11160 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011161
Benjamin Peterson29060642009-01-31 22:14:21 +000011162 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11163 return PyBool_FromLong(0);
11164 else if (!cased && Py_UNICODE_ISLOWER(ch))
11165 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011167 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168}
11169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011170PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011171 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011173Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011174at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175
11176static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011177unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 Py_ssize_t i, length;
11180 int kind;
11181 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 int cased;
11183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011184 if (PyUnicode_READY(self) == -1)
11185 return NULL;
11186 length = PyUnicode_GET_LENGTH(self);
11187 kind = PyUnicode_KIND(self);
11188 data = PyUnicode_DATA(self);
11189
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 if (length == 1)
11192 return PyBool_FromLong(
11193 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011195 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011197 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011198
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011200 for (i = 0; i < length; i++) {
11201 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011202
Benjamin Peterson29060642009-01-31 22:14:21 +000011203 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11204 return PyBool_FromLong(0);
11205 else if (!cased && Py_UNICODE_ISUPPER(ch))
11206 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011208 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209}
11210
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011211PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011212 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011214Return True if S is a titlecased string and there is at least one\n\
11215character in S, i.e. upper- and titlecase characters may only\n\
11216follow uncased characters and lowercase characters only cased ones.\n\
11217Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
11219static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011220unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 Py_ssize_t i, length;
11223 int kind;
11224 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 int cased, previous_is_cased;
11226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 if (PyUnicode_READY(self) == -1)
11228 return NULL;
11229 length = PyUnicode_GET_LENGTH(self);
11230 kind = PyUnicode_KIND(self);
11231 data = PyUnicode_DATA(self);
11232
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234 if (length == 1) {
11235 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11236 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11237 (Py_UNICODE_ISUPPER(ch) != 0));
11238 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011240 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011241 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011243
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244 cased = 0;
11245 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 for (i = 0; i < length; i++) {
11247 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011248
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11250 if (previous_is_cased)
11251 return PyBool_FromLong(0);
11252 previous_is_cased = 1;
11253 cased = 1;
11254 }
11255 else if (Py_UNICODE_ISLOWER(ch)) {
11256 if (!previous_is_cased)
11257 return PyBool_FromLong(0);
11258 previous_is_cased = 1;
11259 cased = 1;
11260 }
11261 else
11262 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011264 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265}
11266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011267PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011270Return True if all characters in S are whitespace\n\
11271and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272
11273static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011274unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 Py_ssize_t i, length;
11277 int kind;
11278 void *data;
11279
11280 if (PyUnicode_READY(self) == -1)
11281 return NULL;
11282 length = PyUnicode_GET_LENGTH(self);
11283 kind = PyUnicode_KIND(self);
11284 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 if (length == 1)
11288 return PyBool_FromLong(
11289 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011291 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011293 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 for (i = 0; i < length; i++) {
11296 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011297 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011298 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011300 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301}
11302
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011303PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011304 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011305\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011306Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011307and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011308
11309static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011310unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011311{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 Py_ssize_t i, length;
11313 int kind;
11314 void *data;
11315
11316 if (PyUnicode_READY(self) == -1)
11317 return NULL;
11318 length = PyUnicode_GET_LENGTH(self);
11319 kind = PyUnicode_KIND(self);
11320 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011321
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 if (length == 1)
11324 return PyBool_FromLong(
11325 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011326
11327 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011329 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 for (i = 0; i < length; i++) {
11332 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011334 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011335 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011336}
11337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011338PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011339 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011340\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011341Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011342and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011343
11344static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011345unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011346{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 int kind;
11348 void *data;
11349 Py_ssize_t len, i;
11350
11351 if (PyUnicode_READY(self) == -1)
11352 return NULL;
11353
11354 kind = PyUnicode_KIND(self);
11355 data = PyUnicode_DATA(self);
11356 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011357
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011358 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 if (len == 1) {
11360 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11361 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11362 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011363
11364 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011366 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 for (i = 0; i < len; i++) {
11369 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011370 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011371 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011372 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011373 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011374}
11375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011376PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011377 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011379Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011380False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381
11382static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011383unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 Py_ssize_t i, length;
11386 int kind;
11387 void *data;
11388
11389 if (PyUnicode_READY(self) == -1)
11390 return NULL;
11391 length = PyUnicode_GET_LENGTH(self);
11392 kind = PyUnicode_KIND(self);
11393 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 if (length == 1)
11397 return PyBool_FromLong(
11398 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011400 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011402 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 for (i = 0; i < length; i++) {
11405 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011408 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409}
11410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011411PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011412 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011414Return True if all characters in S are digits\n\
11415and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
11417static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011418unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420 Py_ssize_t i, length;
11421 int kind;
11422 void *data;
11423
11424 if (PyUnicode_READY(self) == -1)
11425 return NULL;
11426 length = PyUnicode_GET_LENGTH(self);
11427 kind = PyUnicode_KIND(self);
11428 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 if (length == 1) {
11432 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11433 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11434 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011436 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011437 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011438 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 for (i = 0; i < length; i++) {
11441 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011444 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445}
11446
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011447PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011450Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011451False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452
11453static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011454unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011456 Py_ssize_t i, length;
11457 int kind;
11458 void *data;
11459
11460 if (PyUnicode_READY(self) == -1)
11461 return NULL;
11462 length = PyUnicode_GET_LENGTH(self);
11463 kind = PyUnicode_KIND(self);
11464 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 if (length == 1)
11468 return PyBool_FromLong(
11469 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011471 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 for (i = 0; i < length; i++) {
11476 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011479 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480}
11481
Martin v. Löwis47383402007-08-15 07:32:56 +000011482int
11483PyUnicode_IsIdentifier(PyObject *self)
11484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 int kind;
11486 void *data;
11487 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011488 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011489
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 if (PyUnicode_READY(self) == -1) {
11491 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 }
11494
11495 /* Special case for empty strings */
11496 if (PyUnicode_GET_LENGTH(self) == 0)
11497 return 0;
11498 kind = PyUnicode_KIND(self);
11499 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011500
11501 /* PEP 3131 says that the first character must be in
11502 XID_Start and subsequent characters in XID_Continue,
11503 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011504 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011505 letters, digits, underscore). However, given the current
11506 definition of XID_Start and XID_Continue, it is sufficient
11507 to check just for these, except that _ must be allowed
11508 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011510 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011511 return 0;
11512
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011513 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011515 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011516 return 1;
11517}
11518
11519PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011520 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011521\n\
11522Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011523to the language definition.\n\
11524\n\
11525Use keyword.iskeyword() to test for reserved identifiers\n\
11526such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011527
11528static PyObject*
11529unicode_isidentifier(PyObject *self)
11530{
11531 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11532}
11533
Georg Brandl559e5d72008-06-11 18:37:52 +000011534PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011536\n\
11537Return True if all characters in S are considered\n\
11538printable in repr() or S is empty, False otherwise.");
11539
11540static PyObject*
11541unicode_isprintable(PyObject *self)
11542{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011543 Py_ssize_t i, length;
11544 int kind;
11545 void *data;
11546
11547 if (PyUnicode_READY(self) == -1)
11548 return NULL;
11549 length = PyUnicode_GET_LENGTH(self);
11550 kind = PyUnicode_KIND(self);
11551 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011552
11553 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 if (length == 1)
11555 return PyBool_FromLong(
11556 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011557
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 for (i = 0; i < length; i++) {
11559 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011560 Py_RETURN_FALSE;
11561 }
11562 }
11563 Py_RETURN_TRUE;
11564}
11565
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011566PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011567 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568\n\
11569Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011570iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571
11572static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011573unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011575 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576}
11577
Martin v. Löwis18e16552006-02-15 17:27:45 +000011578static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011579unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 if (PyUnicode_READY(self) == -1)
11582 return -1;
11583 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011586PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011587 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011589Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011590done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591
11592static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011593unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011595 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 Py_UCS4 fillchar = ' ';
11597
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011598 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599 return NULL;
11600
Benjamin Petersonbac79492012-01-14 13:34:47 -050011601 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011602 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603
Victor Stinnerc4b49542011-12-11 22:44:26 +010011604 if (PyUnicode_GET_LENGTH(self) >= width)
11605 return unicode_result_unchanged(self);
11606
11607 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608}
11609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011610PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011611 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011613Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614
11615static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011616unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011618 if (PyUnicode_READY(self) == -1)
11619 return NULL;
11620 if (PyUnicode_IS_ASCII(self))
11621 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011622 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623}
11624
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011625#define LEFTSTRIP 0
11626#define RIGHTSTRIP 1
11627#define BOTHSTRIP 2
11628
11629/* Arrays indexed by above */
11630static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11631
11632#define STRIPNAME(i) (stripformat[i]+3)
11633
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011634/* externally visible for str.strip(unicode) */
11635PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011636_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011637{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 void *data;
11639 int kind;
11640 Py_ssize_t i, j, len;
11641 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011642 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11645 return NULL;
11646
11647 kind = PyUnicode_KIND(self);
11648 data = PyUnicode_DATA(self);
11649 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011650 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11652 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011653 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011654
Benjamin Peterson14339b62009-01-31 16:36:08 +000011655 i = 0;
11656 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011657 while (i < len) {
11658 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11659 if (!BLOOM(sepmask, ch))
11660 break;
11661 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11662 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011663 i++;
11664 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011665 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011666
Benjamin Peterson14339b62009-01-31 16:36:08 +000011667 j = len;
11668 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011669 j--;
11670 while (j >= i) {
11671 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11672 if (!BLOOM(sepmask, ch))
11673 break;
11674 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11675 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011676 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011677 }
11678
Benjamin Peterson29060642009-01-31 22:14:21 +000011679 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011680 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011681
Victor Stinner7931d9a2011-11-04 00:22:48 +010011682 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683}
11684
11685PyObject*
11686PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11687{
11688 unsigned char *data;
11689 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011690 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691
Victor Stinnerde636f32011-10-01 03:55:54 +020011692 if (PyUnicode_READY(self) == -1)
11693 return NULL;
11694
Victor Stinner684d5fd2012-05-03 02:32:34 +020011695 length = PyUnicode_GET_LENGTH(self);
11696 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011697
Victor Stinner684d5fd2012-05-03 02:32:34 +020011698 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011699 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700
Victor Stinnerde636f32011-10-01 03:55:54 +020011701 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011702 PyErr_SetString(PyExc_IndexError, "string index out of range");
11703 return NULL;
11704 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011705 if (start >= length || end < start)
11706 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011707
Victor Stinner684d5fd2012-05-03 02:32:34 +020011708 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011709 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011710 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011711 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011712 }
11713 else {
11714 kind = PyUnicode_KIND(self);
11715 data = PyUnicode_1BYTE_DATA(self);
11716 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011717 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011718 length);
11719 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721
11722static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011723do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 Py_ssize_t len, i, j;
11726
11727 if (PyUnicode_READY(self) == -1)
11728 return NULL;
11729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011731
Victor Stinnercc7af722013-04-09 22:39:24 +020011732 if (PyUnicode_IS_ASCII(self)) {
11733 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
11734
11735 i = 0;
11736 if (striptype != RIGHTSTRIP) {
11737 while (i < len) {
11738 Py_UCS4 ch = data[i];
11739 if (!_Py_ascii_whitespace[ch])
11740 break;
11741 i++;
11742 }
11743 }
11744
11745 j = len;
11746 if (striptype != LEFTSTRIP) {
11747 j--;
11748 while (j >= i) {
11749 Py_UCS4 ch = data[j];
11750 if (!_Py_ascii_whitespace[ch])
11751 break;
11752 j--;
11753 }
11754 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011755 }
11756 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011757 else {
11758 int kind = PyUnicode_KIND(self);
11759 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760
Victor Stinnercc7af722013-04-09 22:39:24 +020011761 i = 0;
11762 if (striptype != RIGHTSTRIP) {
11763 while (i < len) {
11764 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11765 if (!Py_UNICODE_ISSPACE(ch))
11766 break;
11767 i++;
11768 }
Victor Stinner9c79e412013-04-09 22:21:08 +020011769 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011770
11771 j = len;
11772 if (striptype != LEFTSTRIP) {
11773 j--;
11774 while (j >= i) {
11775 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11776 if (!Py_UNICODE_ISSPACE(ch))
11777 break;
11778 j--;
11779 }
11780 j++;
11781 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011782 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783
Victor Stinner7931d9a2011-11-04 00:22:48 +010011784 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785}
11786
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787
11788static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011789do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792
Benjamin Peterson14339b62009-01-31 16:36:08 +000011793 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11794 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795
Benjamin Peterson14339b62009-01-31 16:36:08 +000011796 if (sep != NULL && sep != Py_None) {
11797 if (PyUnicode_Check(sep))
11798 return _PyUnicode_XStrip(self, striptype, sep);
11799 else {
11800 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 "%s arg must be None or str",
11802 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011803 return NULL;
11804 }
11805 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011806
Benjamin Peterson14339b62009-01-31 16:36:08 +000011807 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011808}
11809
11810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011811PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011812 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011813\n\
11814Return a copy of the string S with leading and trailing\n\
11815whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011816If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011817
11818static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011819unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011820{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011821 if (PyTuple_GET_SIZE(args) == 0)
11822 return do_strip(self, BOTHSTRIP); /* Common case */
11823 else
11824 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011825}
11826
11827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011828PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830\n\
11831Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011832If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011833
11834static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011835unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011836{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011837 if (PyTuple_GET_SIZE(args) == 0)
11838 return do_strip(self, LEFTSTRIP); /* Common case */
11839 else
11840 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841}
11842
11843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011844PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011846\n\
11847Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011848If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011849
11850static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011851unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011852{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011853 if (PyTuple_GET_SIZE(args) == 0)
11854 return do_strip(self, RIGHTSTRIP); /* Common case */
11855 else
11856 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011857}
11858
11859
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011861unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011863 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865
Serhiy Storchaka05997252013-01-26 12:14:02 +020011866 if (len < 1)
11867 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868
Victor Stinnerc4b49542011-12-11 22:44:26 +010011869 /* no repeat, return original string */
11870 if (len == 1)
11871 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011872
Benjamin Petersonbac79492012-01-14 13:34:47 -050011873 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 return NULL;
11875
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011876 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011877 PyErr_SetString(PyExc_OverflowError,
11878 "repeated string is too long");
11879 return NULL;
11880 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011881 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011882
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011883 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884 if (!u)
11885 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011886 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 if (PyUnicode_GET_LENGTH(str) == 1) {
11889 const int kind = PyUnicode_KIND(str);
11890 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011891 if (kind == PyUnicode_1BYTE_KIND) {
11892 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011893 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011894 }
11895 else if (kind == PyUnicode_2BYTE_KIND) {
11896 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011897 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011898 ucs2[n] = fill_char;
11899 } else {
11900 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11901 assert(kind == PyUnicode_4BYTE_KIND);
11902 for (n = 0; n < len; ++n)
11903 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 }
11906 else {
11907 /* number of characters copied this far */
11908 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011909 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 char *to = (char *) PyUnicode_DATA(u);
11911 Py_MEMCPY(to, PyUnicode_DATA(str),
11912 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011913 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 n = (done <= nchars-done) ? done : nchars-done;
11915 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011916 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011917 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918 }
11919
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011920 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011921 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922}
11923
Alexander Belopolsky40018472011-02-26 01:02:56 +000011924PyObject *
11925PyUnicode_Replace(PyObject *obj,
11926 PyObject *subobj,
11927 PyObject *replobj,
11928 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929{
11930 PyObject *self;
11931 PyObject *str1;
11932 PyObject *str2;
11933 PyObject *result;
11934
11935 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011936 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011939 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011940 Py_DECREF(self);
11941 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942 }
11943 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011944 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 Py_DECREF(self);
11946 Py_DECREF(str1);
11947 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011949 if (PyUnicode_READY(self) == -1 ||
11950 PyUnicode_READY(str1) == -1 ||
11951 PyUnicode_READY(str2) == -1)
11952 result = NULL;
11953 else
11954 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955 Py_DECREF(self);
11956 Py_DECREF(str1);
11957 Py_DECREF(str2);
11958 return result;
11959}
11960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011961PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011962 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963\n\
11964Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011965old replaced by new. If the optional argument count is\n\
11966given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967
11968static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 PyObject *str1;
11972 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011973 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974 PyObject *result;
11975
Martin v. Löwis18e16552006-02-15 17:27:45 +000011976 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011977 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011978 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011981 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011982 return NULL;
11983 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011984 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011985 Py_DECREF(str1);
11986 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011987 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011988 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11989 result = NULL;
11990 else
11991 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992
11993 Py_DECREF(str1);
11994 Py_DECREF(str2);
11995 return result;
11996}
11997
Alexander Belopolsky40018472011-02-26 01:02:56 +000011998static PyObject *
11999unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012000{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012001 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 Py_ssize_t isize;
12003 Py_ssize_t osize, squote, dquote, i, o;
12004 Py_UCS4 max, quote;
12005 int ikind, okind;
12006 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012009 return NULL;
12010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 isize = PyUnicode_GET_LENGTH(unicode);
12012 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 /* Compute length of output, quote characters, and
12015 maximum character */
12016 osize = 2; /* quotes */
12017 max = 127;
12018 squote = dquote = 0;
12019 ikind = PyUnicode_KIND(unicode);
12020 for (i = 0; i < isize; i++) {
12021 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12022 switch (ch) {
12023 case '\'': squote++; osize++; break;
12024 case '"': dquote++; osize++; break;
12025 case '\\': case '\t': case '\r': case '\n':
12026 osize += 2; break;
12027 default:
12028 /* Fast-path ASCII */
12029 if (ch < ' ' || ch == 0x7f)
12030 osize += 4; /* \xHH */
12031 else if (ch < 0x7f)
12032 osize++;
12033 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12034 osize++;
12035 max = ch > max ? ch : max;
12036 }
12037 else if (ch < 0x100)
12038 osize += 4; /* \xHH */
12039 else if (ch < 0x10000)
12040 osize += 6; /* \uHHHH */
12041 else
12042 osize += 10; /* \uHHHHHHHH */
12043 }
12044 }
12045
12046 quote = '\'';
12047 if (squote) {
12048 if (dquote)
12049 /* Both squote and dquote present. Use squote,
12050 and escape them */
12051 osize += squote;
12052 else
12053 quote = '"';
12054 }
12055
12056 repr = PyUnicode_New(osize, max);
12057 if (repr == NULL)
12058 return NULL;
12059 okind = PyUnicode_KIND(repr);
12060 odata = PyUnicode_DATA(repr);
12061
12062 PyUnicode_WRITE(okind, odata, 0, quote);
12063 PyUnicode_WRITE(okind, odata, osize-1, quote);
12064
12065 for (i = 0, o = 1; i < isize; i++) {
12066 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012067
12068 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 if ((ch == quote) || (ch == '\\')) {
12070 PyUnicode_WRITE(okind, odata, o++, '\\');
12071 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012072 continue;
12073 }
12074
Benjamin Peterson29060642009-01-31 22:14:21 +000012075 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012076 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 PyUnicode_WRITE(okind, odata, o++, '\\');
12078 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012079 }
12080 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 PyUnicode_WRITE(okind, odata, o++, '\\');
12082 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012083 }
12084 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 PyUnicode_WRITE(okind, odata, o++, '\\');
12086 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012087 }
12088
12089 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012090 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 PyUnicode_WRITE(okind, odata, o++, '\\');
12092 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012093 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12094 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012095 }
12096
Georg Brandl559e5d72008-06-11 18:37:52 +000012097 /* Copy ASCII characters as-is */
12098 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012100 }
12101
Benjamin Peterson29060642009-01-31 22:14:21 +000012102 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012103 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012104 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012105 (categories Z* and C* except ASCII space)
12106 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012108 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012109 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012110 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012112 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012114 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012115 /* Map 16-bit characters to '\uxxxx' */
12116 else if (ch <= 0xffff) {
12117 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012118 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12119 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12120 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12121 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012122 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012123 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012124 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012125 PyUnicode_WRITE(okind, odata, o++, 'U');
12126 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12127 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12128 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12129 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012130 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12131 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12132 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12133 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012134 }
12135 }
12136 /* Copy characters as-is */
12137 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012139 }
12140 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012141 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012143 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012144 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145}
12146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012147PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012148 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012149\n\
12150Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012151such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152arguments start and end are interpreted as in slice notation.\n\
12153\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012154Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155
12156static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012159 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012160 Py_ssize_t start;
12161 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012162 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163
Jesus Ceaac451502011-04-20 17:09:23 +020012164 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12165 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012166 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 if (PyUnicode_READY(self) == -1)
12169 return NULL;
12170 if (PyUnicode_READY(substring) == -1)
12171 return NULL;
12172
Victor Stinner7931d9a2011-11-04 00:22:48 +010012173 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174
12175 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012176
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012177 if (result == -2)
12178 return NULL;
12179
Christian Heimes217cfd12007-12-02 14:31:20 +000012180 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181}
12182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012183PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012184 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012186Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
12188static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012191 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012192 Py_ssize_t start;
12193 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012194 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
Jesus Ceaac451502011-04-20 17:09:23 +020012196 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12197 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012198 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 if (PyUnicode_READY(self) == -1)
12201 return NULL;
12202 if (PyUnicode_READY(substring) == -1)
12203 return NULL;
12204
Victor Stinner7931d9a2011-11-04 00:22:48 +010012205 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206
12207 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 if (result == -2)
12210 return NULL;
12211
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212 if (result < 0) {
12213 PyErr_SetString(PyExc_ValueError, "substring not found");
12214 return NULL;
12215 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012216
Christian Heimes217cfd12007-12-02 14:31:20 +000012217 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218}
12219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012220PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012221 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012223Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012224done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225
12226static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012227unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012229 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 Py_UCS4 fillchar = ' ';
12231
Victor Stinnere9a29352011-10-01 02:14:59 +020012232 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012234
Benjamin Petersonbac79492012-01-14 13:34:47 -050012235 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236 return NULL;
12237
Victor Stinnerc4b49542011-12-11 22:44:26 +010012238 if (PyUnicode_GET_LENGTH(self) >= width)
12239 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240
Victor Stinnerc4b49542011-12-11 22:44:26 +010012241 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242}
12243
Alexander Belopolsky40018472011-02-26 01:02:56 +000012244PyObject *
12245PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246{
12247 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012248
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249 s = PyUnicode_FromObject(s);
12250 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012251 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012252 if (sep != NULL) {
12253 sep = PyUnicode_FromObject(sep);
12254 if (sep == NULL) {
12255 Py_DECREF(s);
12256 return NULL;
12257 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258 }
12259
Victor Stinner9310abb2011-10-05 00:59:23 +020012260 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261
12262 Py_DECREF(s);
12263 Py_XDECREF(sep);
12264 return result;
12265}
12266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012267PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012268 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269\n\
12270Return a list of the words in S, using sep as the\n\
12271delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012272splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012273whitespace string is a separator and empty strings are\n\
12274removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275
12276static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012277unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012279 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012281 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012283 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12284 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285 return NULL;
12286
12287 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012288 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012290 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012292 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293}
12294
Thomas Wouters477c8d52006-05-27 19:21:47 +000012295PyObject *
12296PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12297{
12298 PyObject* str_obj;
12299 PyObject* sep_obj;
12300 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 int kind1, kind2, kind;
12302 void *buf1 = NULL, *buf2 = NULL;
12303 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012304
12305 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012306 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012307 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012308 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012309 if (!sep_obj) {
12310 Py_DECREF(str_obj);
12311 return NULL;
12312 }
12313 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12314 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012315 Py_DECREF(str_obj);
12316 return NULL;
12317 }
12318
Victor Stinner14f8f022011-10-05 20:58:25 +020012319 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012321 kind = Py_MAX(kind1, kind2);
12322 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012324 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 if (!buf1)
12326 goto onError;
12327 buf2 = PyUnicode_DATA(sep_obj);
12328 if (kind2 != kind)
12329 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12330 if (!buf2)
12331 goto onError;
12332 len1 = PyUnicode_GET_LENGTH(str_obj);
12333 len2 = PyUnicode_GET_LENGTH(sep_obj);
12334
Benjamin Petersonead6b532011-12-20 17:23:42 -060012335 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012337 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12338 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12339 else
12340 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 break;
12342 case PyUnicode_2BYTE_KIND:
12343 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12344 break;
12345 case PyUnicode_4BYTE_KIND:
12346 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12347 break;
12348 default:
12349 assert(0);
12350 out = 0;
12351 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352
12353 Py_DECREF(sep_obj);
12354 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 if (kind1 != kind)
12356 PyMem_Free(buf1);
12357 if (kind2 != kind)
12358 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359
12360 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 onError:
12362 Py_DECREF(sep_obj);
12363 Py_DECREF(str_obj);
12364 if (kind1 != kind && buf1)
12365 PyMem_Free(buf1);
12366 if (kind2 != kind && buf2)
12367 PyMem_Free(buf2);
12368 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369}
12370
12371
12372PyObject *
12373PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12374{
12375 PyObject* str_obj;
12376 PyObject* sep_obj;
12377 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 int kind1, kind2, kind;
12379 void *buf1 = NULL, *buf2 = NULL;
12380 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012381
12382 str_obj = PyUnicode_FromObject(str_in);
12383 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012384 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012385 sep_obj = PyUnicode_FromObject(sep_in);
12386 if (!sep_obj) {
12387 Py_DECREF(str_obj);
12388 return NULL;
12389 }
12390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 kind1 = PyUnicode_KIND(str_in);
12392 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012393 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 buf1 = PyUnicode_DATA(str_in);
12395 if (kind1 != kind)
12396 buf1 = _PyUnicode_AsKind(str_in, kind);
12397 if (!buf1)
12398 goto onError;
12399 buf2 = PyUnicode_DATA(sep_obj);
12400 if (kind2 != kind)
12401 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12402 if (!buf2)
12403 goto onError;
12404 len1 = PyUnicode_GET_LENGTH(str_obj);
12405 len2 = PyUnicode_GET_LENGTH(sep_obj);
12406
Benjamin Petersonead6b532011-12-20 17:23:42 -060012407 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012408 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012409 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12410 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12411 else
12412 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012413 break;
12414 case PyUnicode_2BYTE_KIND:
12415 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12416 break;
12417 case PyUnicode_4BYTE_KIND:
12418 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12419 break;
12420 default:
12421 assert(0);
12422 out = 0;
12423 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012424
12425 Py_DECREF(sep_obj);
12426 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 if (kind1 != kind)
12428 PyMem_Free(buf1);
12429 if (kind2 != kind)
12430 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
12432 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012433 onError:
12434 Py_DECREF(sep_obj);
12435 Py_DECREF(str_obj);
12436 if (kind1 != kind && buf1)
12437 PyMem_Free(buf1);
12438 if (kind2 != kind && buf2)
12439 PyMem_Free(buf2);
12440 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012441}
12442
12443PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012444 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012445\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012446Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012448found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012449
12450static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012451unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012452{
Victor Stinner9310abb2011-10-05 00:59:23 +020012453 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454}
12455
12456PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012457 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012458\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012459Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012460the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012461separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012462
12463static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012464unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012465{
Victor Stinner9310abb2011-10-05 00:59:23 +020012466 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012467}
12468
Alexander Belopolsky40018472011-02-26 01:02:56 +000012469PyObject *
12470PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012471{
12472 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012473
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012474 s = PyUnicode_FromObject(s);
12475 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012476 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012477 if (sep != NULL) {
12478 sep = PyUnicode_FromObject(sep);
12479 if (sep == NULL) {
12480 Py_DECREF(s);
12481 return NULL;
12482 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 }
12484
Victor Stinner9310abb2011-10-05 00:59:23 +020012485 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012486
12487 Py_DECREF(s);
12488 Py_XDECREF(sep);
12489 return result;
12490}
12491
12492PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012493 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012494\n\
12495Return a list of the words in S, using sep as the\n\
12496delimiter string, starting at the end of the string and\n\
12497working to the front. If maxsplit is given, at most maxsplit\n\
12498splits are done. If sep is not specified, any whitespace string\n\
12499is a separator.");
12500
12501static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012502unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012503{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012504 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012505 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012506 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012507
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012508 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12509 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012510 return NULL;
12511
12512 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012513 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012514 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012515 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012516 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012517 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012518}
12519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012520PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012521 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522\n\
12523Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012524Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012525is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526
12527static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012528unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012530 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012531 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012533 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12534 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535 return NULL;
12536
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012537 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012538}
12539
12540static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012541PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012543 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544}
12545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012546PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012547 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012548\n\
12549Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012550and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551
12552static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012553unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012555 if (PyUnicode_READY(self) == -1)
12556 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012557 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558}
12559
Georg Brandlceee0772007-11-27 23:48:05 +000012560PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012561 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012562\n\
12563Return a translation table usable for str.translate().\n\
12564If there is only one argument, it must be a dictionary mapping Unicode\n\
12565ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012566Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012567If there are two arguments, they must be strings of equal length, and\n\
12568in the resulting dictionary, each character in x will be mapped to the\n\
12569character at the same position in y. If there is a third argument, it\n\
12570must be a string, whose characters will be mapped to None in the result.");
12571
12572static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012573unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012574{
12575 PyObject *x, *y = NULL, *z = NULL;
12576 PyObject *new = NULL, *key, *value;
12577 Py_ssize_t i = 0;
12578 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012579
Georg Brandlceee0772007-11-27 23:48:05 +000012580 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12581 return NULL;
12582 new = PyDict_New();
12583 if (!new)
12584 return NULL;
12585 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 int x_kind, y_kind, z_kind;
12587 void *x_data, *y_data, *z_data;
12588
Georg Brandlceee0772007-11-27 23:48:05 +000012589 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012590 if (!PyUnicode_Check(x)) {
12591 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12592 "be a string if there is a second argument");
12593 goto err;
12594 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012596 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12597 "arguments must have equal length");
12598 goto err;
12599 }
12600 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 x_kind = PyUnicode_KIND(x);
12602 y_kind = PyUnicode_KIND(y);
12603 x_data = PyUnicode_DATA(x);
12604 y_data = PyUnicode_DATA(y);
12605 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12606 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012607 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012608 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012609 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012610 if (!value) {
12611 Py_DECREF(key);
12612 goto err;
12613 }
Georg Brandlceee0772007-11-27 23:48:05 +000012614 res = PyDict_SetItem(new, key, value);
12615 Py_DECREF(key);
12616 Py_DECREF(value);
12617 if (res < 0)
12618 goto err;
12619 }
12620 /* create entries for deleting chars in z */
12621 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 z_kind = PyUnicode_KIND(z);
12623 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012624 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012626 if (!key)
12627 goto err;
12628 res = PyDict_SetItem(new, key, Py_None);
12629 Py_DECREF(key);
12630 if (res < 0)
12631 goto err;
12632 }
12633 }
12634 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635 int kind;
12636 void *data;
12637
Georg Brandlceee0772007-11-27 23:48:05 +000012638 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012639 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012640 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12641 "to maketrans it must be a dict");
12642 goto err;
12643 }
12644 /* copy entries into the new dict, converting string keys to int keys */
12645 while (PyDict_Next(x, &i, &key, &value)) {
12646 if (PyUnicode_Check(key)) {
12647 /* convert string keys to integer keys */
12648 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012649 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012650 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12651 "table must be of length 1");
12652 goto err;
12653 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 kind = PyUnicode_KIND(key);
12655 data = PyUnicode_DATA(key);
12656 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012657 if (!newkey)
12658 goto err;
12659 res = PyDict_SetItem(new, newkey, value);
12660 Py_DECREF(newkey);
12661 if (res < 0)
12662 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012663 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012664 /* just keep integer keys */
12665 if (PyDict_SetItem(new, key, value) < 0)
12666 goto err;
12667 } else {
12668 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12669 "be strings or integers");
12670 goto err;
12671 }
12672 }
12673 }
12674 return new;
12675 err:
12676 Py_DECREF(new);
12677 return NULL;
12678}
12679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012680PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012681 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682\n\
12683Return a copy of the string S, where all characters have been mapped\n\
12684through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012685Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012686Unmapped characters are left untouched. Characters mapped to None\n\
12687are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688
12689static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693}
12694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012695PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012696 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012698Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699
12700static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012701unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012703 if (PyUnicode_READY(self) == -1)
12704 return NULL;
12705 if (PyUnicode_IS_ASCII(self))
12706 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012707 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708}
12709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012710PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012711 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012713Pad a numeric string S with zeros on the left, to fill a field\n\
12714of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715
12716static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012717unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012719 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012720 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012721 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 int kind;
12723 void *data;
12724 Py_UCS4 chr;
12725
Martin v. Löwis18e16552006-02-15 17:27:45 +000012726 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727 return NULL;
12728
Benjamin Petersonbac79492012-01-14 13:34:47 -050012729 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
Victor Stinnerc4b49542011-12-11 22:44:26 +010012732 if (PyUnicode_GET_LENGTH(self) >= width)
12733 return unicode_result_unchanged(self);
12734
12735 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736
12737 u = pad(self, fill, 0, '0');
12738
Walter Dörwald068325e2002-04-15 13:36:47 +000012739 if (u == NULL)
12740 return NULL;
12741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 kind = PyUnicode_KIND(u);
12743 data = PyUnicode_DATA(u);
12744 chr = PyUnicode_READ(kind, data, fill);
12745
12746 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 PyUnicode_WRITE(kind, data, 0, chr);
12749 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750 }
12751
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012752 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012753 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755
12756#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012757static PyObject *
12758unicode__decimal2ascii(PyObject *self)
12759{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012761}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012762#endif
12763
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012764PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012765 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012767Return True if S starts with the specified prefix, False otherwise.\n\
12768With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012769With optional end, stop comparing S at that position.\n\
12770prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012771
12772static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012773unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012774 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012777 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012778 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012779 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012780 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781
Jesus Ceaac451502011-04-20 17:09:23 +020012782 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012783 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012784 if (PyTuple_Check(subobj)) {
12785 Py_ssize_t i;
12786 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012787 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012788 if (substring == NULL)
12789 return NULL;
12790 result = tailmatch(self, substring, start, end, -1);
12791 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012792 if (result == -1)
12793 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012794 if (result) {
12795 Py_RETURN_TRUE;
12796 }
12797 }
12798 /* nothing matched */
12799 Py_RETURN_FALSE;
12800 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012801 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012802 if (substring == NULL) {
12803 if (PyErr_ExceptionMatches(PyExc_TypeError))
12804 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12805 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012807 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012808 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012810 if (result == -1)
12811 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012812 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813}
12814
12815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012816PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012817 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012819Return True if S ends with the specified suffix, False otherwise.\n\
12820With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012821With optional end, stop comparing S at that position.\n\
12822suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823
12824static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012825unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012828 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012829 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012830 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012831 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012832 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833
Jesus Ceaac451502011-04-20 17:09:23 +020012834 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012836 if (PyTuple_Check(subobj)) {
12837 Py_ssize_t i;
12838 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012839 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012840 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012841 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012842 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012843 result = tailmatch(self, substring, start, end, +1);
12844 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012845 if (result == -1)
12846 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012847 if (result) {
12848 Py_RETURN_TRUE;
12849 }
12850 }
12851 Py_RETURN_FALSE;
12852 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012853 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012854 if (substring == NULL) {
12855 if (PyErr_ExceptionMatches(PyExc_TypeError))
12856 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12857 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012858 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012859 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012860 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010012861 if (result == -1)
12862 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012864 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865}
12866
Victor Stinner202fdca2012-05-07 12:47:02 +020012867Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012868_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012869{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012870 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012871 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12872 writer->data = PyUnicode_DATA(writer->buffer);
12873 writer->kind = PyUnicode_KIND(writer->buffer);
12874}
12875
Victor Stinnerd3f08822012-05-29 12:57:52 +020012876void
12877_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012878{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012879 memset(writer, 0, sizeof(*writer));
12880#ifdef Py_DEBUG
12881 writer->kind = 5; /* invalid kind */
12882#endif
12883 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012884 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012885}
12886
Victor Stinnerd3f08822012-05-29 12:57:52 +020012887int
12888_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12889 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012890{
12891 Py_ssize_t newlen;
12892 PyObject *newbuffer;
12893
Victor Stinnerd3f08822012-05-29 12:57:52 +020012894 assert(length > 0);
12895
Victor Stinner202fdca2012-05-07 12:47:02 +020012896 if (length > PY_SSIZE_T_MAX - writer->pos) {
12897 PyErr_NoMemory();
12898 return -1;
12899 }
12900 newlen = writer->pos + length;
12901
Victor Stinnerd3f08822012-05-29 12:57:52 +020012902 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012903 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012904 /* overallocate 25% to limit the number of resize */
12905 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12906 newlen += newlen / 4;
12907 if (newlen < writer->min_length)
12908 newlen = writer->min_length;
12909 }
12910 writer->buffer = PyUnicode_New(newlen, maxchar);
12911 if (writer->buffer == NULL)
12912 return -1;
12913 _PyUnicodeWriter_Update(writer);
12914 return 0;
12915 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012916
Victor Stinnerd3f08822012-05-29 12:57:52 +020012917 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012918 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012919 /* overallocate 25% to limit the number of resize */
12920 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12921 newlen += newlen / 4;
12922 if (newlen < writer->min_length)
12923 newlen = writer->min_length;
12924 }
12925
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012926 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012927 /* resize + widen */
12928 newbuffer = PyUnicode_New(newlen, maxchar);
12929 if (newbuffer == NULL)
12930 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012931 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12932 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012933 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012934 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012935 }
12936 else {
12937 newbuffer = resize_compact(writer->buffer, newlen);
12938 if (newbuffer == NULL)
12939 return -1;
12940 }
12941 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012942 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012943 }
12944 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012945 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012946 newbuffer = PyUnicode_New(writer->size, maxchar);
12947 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012948 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012949 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12950 writer->buffer, 0, writer->pos);
12951 Py_DECREF(writer->buffer);
12952 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012953 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012954 }
12955 return 0;
12956}
12957
Victor Stinnerd3f08822012-05-29 12:57:52 +020012958int
12959_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12960{
12961 Py_UCS4 maxchar;
12962 Py_ssize_t len;
12963
12964 if (PyUnicode_READY(str) == -1)
12965 return -1;
12966 len = PyUnicode_GET_LENGTH(str);
12967 if (len == 0)
12968 return 0;
12969 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12970 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012971 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012972 Py_INCREF(str);
12973 writer->buffer = str;
12974 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012975 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012976 writer->size = 0;
12977 writer->pos += len;
12978 return 0;
12979 }
12980 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12981 return -1;
12982 }
12983 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12984 str, 0, len);
12985 writer->pos += len;
12986 return 0;
12987}
12988
Victor Stinnere215d962012-10-06 23:03:36 +020012989int
Victor Stinnercfc4c132013-04-03 01:48:39 +020012990_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
12991 Py_ssize_t start, Py_ssize_t end)
12992{
12993 Py_UCS4 maxchar;
12994 Py_ssize_t len;
12995
12996 if (PyUnicode_READY(str) == -1)
12997 return -1;
12998
12999 assert(0 <= start);
13000 assert(end <= PyUnicode_GET_LENGTH(str));
13001 assert(start <= end);
13002
13003 if (end == 0)
13004 return 0;
13005
13006 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13007 return _PyUnicodeWriter_WriteStr(writer, str);
13008
13009 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13010 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13011 else
13012 maxchar = writer->maxchar;
13013 len = end - start;
13014
13015 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13016 return -1;
13017
13018 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13019 str, start, len);
13020 writer->pos += len;
13021 return 0;
13022}
13023
13024int
Victor Stinnere215d962012-10-06 23:03:36 +020013025_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
13026{
13027 Py_UCS4 maxchar;
13028
13029 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13030 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13031 return -1;
13032 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13033 writer->pos += len;
13034 return 0;
13035}
13036
Victor Stinnerd3f08822012-05-29 12:57:52 +020013037PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013038_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013039{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013040 if (writer->pos == 0) {
13041 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013042 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013043 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013044 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013045 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
13046 return writer->buffer;
13047 }
13048 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13049 PyObject *newbuffer;
13050 newbuffer = resize_compact(writer->buffer, writer->pos);
13051 if (newbuffer == NULL) {
13052 Py_DECREF(writer->buffer);
13053 return NULL;
13054 }
13055 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013056 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020013057 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner2cb16aa2013-03-06 19:28:37 +010013058 return unicode_result_ready(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013059}
13060
Victor Stinnerd3f08822012-05-29 12:57:52 +020013061void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013062_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013063{
13064 Py_CLEAR(writer->buffer);
13065}
13066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013067#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013068
13069PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013070 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013071\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013072Return a formatted version of S, using substitutions from args and kwargs.\n\
13073The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013074
Eric Smith27bbca62010-11-04 17:06:58 +000013075PyDoc_STRVAR(format_map__doc__,
13076 "S.format_map(mapping) -> str\n\
13077\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013078Return a formatted version of S, using substitutions from mapping.\n\
13079The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013080
Eric Smith4a7d76d2008-05-30 18:10:19 +000013081static PyObject *
13082unicode__format__(PyObject* self, PyObject* args)
13083{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013084 PyObject *format_spec;
13085 _PyUnicodeWriter writer;
13086 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013087
13088 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13089 return NULL;
13090
Victor Stinnerd3f08822012-05-29 12:57:52 +020013091 if (PyUnicode_READY(self) == -1)
13092 return NULL;
13093 _PyUnicodeWriter_Init(&writer, 0);
13094 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13095 self, format_spec, 0,
13096 PyUnicode_GET_LENGTH(format_spec));
13097 if (ret == -1) {
13098 _PyUnicodeWriter_Dealloc(&writer);
13099 return NULL;
13100 }
13101 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013102}
13103
Eric Smith8c663262007-08-25 02:26:07 +000013104PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013105 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013106\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013107Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013108
13109static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013110unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013111{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013112 Py_ssize_t size;
13113
13114 /* If it's a compact object, account for base structure +
13115 character data. */
13116 if (PyUnicode_IS_COMPACT_ASCII(v))
13117 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13118 else if (PyUnicode_IS_COMPACT(v))
13119 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013120 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013121 else {
13122 /* If it is a two-block object, account for base object, and
13123 for character block if present. */
13124 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013125 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013126 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013127 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 }
13129 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013130 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013131 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013132 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013133 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013134 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013135
13136 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013137}
13138
13139PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013141
13142static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013143unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013144{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013145 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013146 if (!copy)
13147 return NULL;
13148 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013149}
13150
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013152 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013153 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013154 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13155 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013156 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13157 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013158 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013159 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13160 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13161 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13162 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13163 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013164 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013165 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13166 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13167 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013168 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013169 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13170 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13171 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013172 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013173 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013174 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013175 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013176 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13177 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13178 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13179 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13180 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13181 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13182 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13183 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13184 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13185 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13186 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13187 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13188 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13189 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013190 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013191 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013192 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013193 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013194 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013195 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013196 {"maketrans", (PyCFunction) unicode_maketrans,
13197 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013198 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013199#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013200 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013201 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013202#endif
13203
Benjamin Peterson14339b62009-01-31 16:36:08 +000013204 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 {NULL, NULL}
13206};
13207
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013208static PyObject *
13209unicode_mod(PyObject *v, PyObject *w)
13210{
Brian Curtindfc80e32011-08-10 20:28:54 -050013211 if (!PyUnicode_Check(v))
13212 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013214}
13215
13216static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013217 0, /*nb_add*/
13218 0, /*nb_subtract*/
13219 0, /*nb_multiply*/
13220 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013221};
13222
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013224 (lenfunc) unicode_length, /* sq_length */
13225 PyUnicode_Concat, /* sq_concat */
13226 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13227 (ssizeargfunc) unicode_getitem, /* sq_item */
13228 0, /* sq_slice */
13229 0, /* sq_ass_item */
13230 0, /* sq_ass_slice */
13231 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232};
13233
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013234static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013235unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013236{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013237 if (PyUnicode_READY(self) == -1)
13238 return NULL;
13239
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013240 if (PyIndex_Check(item)) {
13241 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013242 if (i == -1 && PyErr_Occurred())
13243 return NULL;
13244 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013245 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013246 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013247 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013248 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013249 PyObject *result;
13250 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013251 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013252 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013254 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013256 return NULL;
13257 }
13258
13259 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013260 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013261 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013262 slicelength == PyUnicode_GET_LENGTH(self)) {
13263 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013264 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013265 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013266 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013267 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013268 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013269 src_kind = PyUnicode_KIND(self);
13270 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013271 if (!PyUnicode_IS_ASCII(self)) {
13272 kind_limit = kind_maxchar_limit(src_kind);
13273 max_char = 0;
13274 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13275 ch = PyUnicode_READ(src_kind, src_data, cur);
13276 if (ch > max_char) {
13277 max_char = ch;
13278 if (max_char >= kind_limit)
13279 break;
13280 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013281 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013282 }
Victor Stinner55c99112011-10-13 01:17:06 +020013283 else
13284 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013285 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013286 if (result == NULL)
13287 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013288 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013289 dest_data = PyUnicode_DATA(result);
13290
13291 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013292 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13293 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013294 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013295 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013296 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013297 } else {
13298 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13299 return NULL;
13300 }
13301}
13302
13303static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013304 (lenfunc)unicode_length, /* mp_length */
13305 (binaryfunc)unicode_subscript, /* mp_subscript */
13306 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013307};
13308
Guido van Rossumd57fd912000-03-10 22:53:23 +000013309
Guido van Rossumd57fd912000-03-10 22:53:23 +000013310/* Helpers for PyUnicode_Format() */
13311
Victor Stinnera47082312012-10-04 02:19:54 +020013312struct unicode_formatter_t {
13313 PyObject *args;
13314 int args_owned;
13315 Py_ssize_t arglen, argidx;
13316 PyObject *dict;
13317
13318 enum PyUnicode_Kind fmtkind;
13319 Py_ssize_t fmtcnt, fmtpos;
13320 void *fmtdata;
13321 PyObject *fmtstr;
13322
13323 _PyUnicodeWriter writer;
13324};
13325
13326struct unicode_format_arg_t {
13327 Py_UCS4 ch;
13328 int flags;
13329 Py_ssize_t width;
13330 int prec;
13331 int sign;
13332};
13333
Guido van Rossumd57fd912000-03-10 22:53:23 +000013334static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013335unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013336{
Victor Stinnera47082312012-10-04 02:19:54 +020013337 Py_ssize_t argidx = ctx->argidx;
13338
13339 if (argidx < ctx->arglen) {
13340 ctx->argidx++;
13341 if (ctx->arglen < 0)
13342 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 else
Victor Stinnera47082312012-10-04 02:19:54 +020013344 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345 }
13346 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013348 return NULL;
13349}
13350
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013351/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013352
Victor Stinnera47082312012-10-04 02:19:54 +020013353/* Format a float into the writer if the writer is not NULL, or into *p_output
13354 otherwise.
13355
13356 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013357static int
Victor Stinnera47082312012-10-04 02:19:54 +020013358formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13359 PyObject **p_output,
13360 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013362 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013363 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013364 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013365 int prec;
13366 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013367
Guido van Rossumd57fd912000-03-10 22:53:23 +000013368 x = PyFloat_AsDouble(v);
13369 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013370 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013371
Victor Stinnera47082312012-10-04 02:19:54 +020013372 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013373 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013374 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013375
Victor Stinnera47082312012-10-04 02:19:54 +020013376 if (arg->flags & F_ALT)
13377 dtoa_flags = Py_DTSF_ALT;
13378 else
13379 dtoa_flags = 0;
13380 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013381 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013382 return -1;
13383 len = strlen(p);
13384 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013385 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13386 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013387 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013388 }
Victor Stinner184252a2012-06-16 02:57:41 +020013389 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013390 writer->pos += len;
13391 }
13392 else
13393 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013394 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013395 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013396}
13397
Victor Stinnerd0880d52012-04-27 23:40:13 +020013398/* formatlong() emulates the format codes d, u, o, x and X, and
13399 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13400 * Python's regular ints.
13401 * Return value: a new PyUnicodeObject*, or NULL if error.
13402 * The output string is of the form
13403 * "-"? ("0x" | "0X")? digit+
13404 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13405 * set in flags. The case of hex digits will be correct,
13406 * There will be at least prec digits, zero-filled on the left if
13407 * necessary to get that many.
13408 * val object to be converted
13409 * flags bitmask of format flags; only F_ALT is looked at
13410 * prec minimum number of digits; 0-fill on left if needed
13411 * type a character in [duoxX]; u acts the same as d
13412 *
13413 * CAUTION: o, x and X conversions on regular ints can never
13414 * produce a '-' sign, but can for Python's unbounded ints.
13415 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013416static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013417formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013418{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013419 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013420 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013421 Py_ssize_t i;
13422 int sign; /* 1 if '-', else 0 */
13423 int len; /* number of characters */
13424 Py_ssize_t llen;
13425 int numdigits; /* len == numnondigits + numdigits */
13426 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013427 int prec = arg->prec;
13428 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013429
Victor Stinnerd0880d52012-04-27 23:40:13 +020013430 /* Avoid exceeding SSIZE_T_MAX */
13431 if (prec > INT_MAX-3) {
13432 PyErr_SetString(PyExc_OverflowError,
13433 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013434 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013435 }
13436
13437 assert(PyLong_Check(val));
13438
13439 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013440 default:
13441 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013442 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013443 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013444 case 'u':
13445 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013446 if (PyBool_Check(val))
13447 result = PyNumber_ToBase(val, 10);
13448 else
13449 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013450 break;
13451 case 'o':
13452 numnondigits = 2;
13453 result = PyNumber_ToBase(val, 8);
13454 break;
13455 case 'x':
13456 case 'X':
13457 numnondigits = 2;
13458 result = PyNumber_ToBase(val, 16);
13459 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013460 }
13461 if (!result)
13462 return NULL;
13463
13464 assert(unicode_modifiable(result));
13465 assert(PyUnicode_IS_READY(result));
13466 assert(PyUnicode_IS_ASCII(result));
13467
13468 /* To modify the string in-place, there can only be one reference. */
13469 if (Py_REFCNT(result) != 1) {
13470 PyErr_BadInternalCall();
13471 return NULL;
13472 }
13473 buf = PyUnicode_DATA(result);
13474 llen = PyUnicode_GET_LENGTH(result);
13475 if (llen > INT_MAX) {
13476 PyErr_SetString(PyExc_ValueError,
13477 "string too large in _PyBytes_FormatLong");
13478 return NULL;
13479 }
13480 len = (int)llen;
13481 sign = buf[0] == '-';
13482 numnondigits += sign;
13483 numdigits = len - numnondigits;
13484 assert(numdigits > 0);
13485
13486 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013487 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013488 (type == 'o' || type == 'x' || type == 'X'))) {
13489 assert(buf[sign] == '0');
13490 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13491 buf[sign+1] == 'o');
13492 numnondigits -= 2;
13493 buf += 2;
13494 len -= 2;
13495 if (sign)
13496 buf[0] = '-';
13497 assert(len == numnondigits + numdigits);
13498 assert(numdigits > 0);
13499 }
13500
13501 /* Fill with leading zeroes to meet minimum width. */
13502 if (prec > numdigits) {
13503 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13504 numnondigits + prec);
13505 char *b1;
13506 if (!r1) {
13507 Py_DECREF(result);
13508 return NULL;
13509 }
13510 b1 = PyBytes_AS_STRING(r1);
13511 for (i = 0; i < numnondigits; ++i)
13512 *b1++ = *buf++;
13513 for (i = 0; i < prec - numdigits; i++)
13514 *b1++ = '0';
13515 for (i = 0; i < numdigits; i++)
13516 *b1++ = *buf++;
13517 *b1 = '\0';
13518 Py_DECREF(result);
13519 result = r1;
13520 buf = PyBytes_AS_STRING(result);
13521 len = numnondigits + prec;
13522 }
13523
13524 /* Fix up case for hex conversions. */
13525 if (type == 'X') {
13526 /* Need to convert all lower case letters to upper case.
13527 and need to convert 0x to 0X (and -0x to -0X). */
13528 for (i = 0; i < len; i++)
13529 if (buf[i] >= 'a' && buf[i] <= 'x')
13530 buf[i] -= 'a'-'A';
13531 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013532 if (!PyUnicode_Check(result)
13533 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013534 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013535 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013536 Py_DECREF(result);
13537 result = unicode;
13538 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013539 else if (len != PyUnicode_GET_LENGTH(result)) {
13540 if (PyUnicode_Resize(&result, len) < 0)
13541 Py_CLEAR(result);
13542 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013543 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013544}
13545
Victor Stinner621ef3d2012-10-02 00:33:47 +020013546/* Format an integer.
13547 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013548 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013549 * -1 and raise an exception on error */
13550static int
Victor Stinnera47082312012-10-04 02:19:54 +020013551mainformatlong(PyObject *v,
13552 struct unicode_format_arg_t *arg,
13553 PyObject **p_output,
13554 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013555{
13556 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013557 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013558
13559 if (!PyNumber_Check(v))
13560 goto wrongtype;
13561
13562 if (!PyLong_Check(v)) {
13563 iobj = PyNumber_Long(v);
13564 if (iobj == NULL) {
13565 if (PyErr_ExceptionMatches(PyExc_TypeError))
13566 goto wrongtype;
13567 return -1;
13568 }
13569 assert(PyLong_Check(iobj));
13570 }
13571 else {
13572 iobj = v;
13573 Py_INCREF(iobj);
13574 }
13575
13576 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013577 && arg->width == -1 && arg->prec == -1
13578 && !(arg->flags & (F_SIGN | F_BLANK))
13579 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013580 {
13581 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013582 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013583 int base;
13584
Victor Stinnera47082312012-10-04 02:19:54 +020013585 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013586 {
13587 default:
13588 assert(0 && "'type' not in [diuoxX]");
13589 case 'd':
13590 case 'i':
13591 case 'u':
13592 base = 10;
13593 break;
13594 case 'o':
13595 base = 8;
13596 break;
13597 case 'x':
13598 case 'X':
13599 base = 16;
13600 break;
13601 }
13602
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013603 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13604 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013605 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013606 }
13607 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013608 return 1;
13609 }
13610
Victor Stinnera47082312012-10-04 02:19:54 +020013611 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013612 Py_DECREF(iobj);
13613 if (res == NULL)
13614 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013615 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013616 return 0;
13617
13618wrongtype:
13619 PyErr_Format(PyExc_TypeError,
13620 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013621 "not %.200s",
13622 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013623 return -1;
13624}
13625
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013626static Py_UCS4
13627formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013628{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013629 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013630 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013631 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013632 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 goto onError;
13635 }
13636 else {
13637 /* Integer input truncated to a character */
13638 long x;
13639 x = PyLong_AsLong(v);
13640 if (x == -1 && PyErr_Occurred())
13641 goto onError;
13642
Victor Stinner8faf8212011-12-08 22:14:11 +010013643 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013644 PyErr_SetString(PyExc_OverflowError,
13645 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013646 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013647 }
13648
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013649 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013650 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013651
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013653 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013654 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013655 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013656}
13657
Victor Stinnera47082312012-10-04 02:19:54 +020013658/* Parse options of an argument: flags, width, precision.
13659 Handle also "%(name)" syntax.
13660
13661 Return 0 if the argument has been formatted into arg->str.
13662 Return 1 if the argument has been written into ctx->writer,
13663 Raise an exception and return -1 on error. */
13664static int
13665unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13666 struct unicode_format_arg_t *arg)
13667{
13668#define FORMAT_READ(ctx) \
13669 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13670
13671 PyObject *v;
13672
Victor Stinnera47082312012-10-04 02:19:54 +020013673 if (arg->ch == '(') {
13674 /* Get argument value from a dictionary. Example: "%(name)s". */
13675 Py_ssize_t keystart;
13676 Py_ssize_t keylen;
13677 PyObject *key;
13678 int pcount = 1;
13679
13680 if (ctx->dict == NULL) {
13681 PyErr_SetString(PyExc_TypeError,
13682 "format requires a mapping");
13683 return -1;
13684 }
13685 ++ctx->fmtpos;
13686 --ctx->fmtcnt;
13687 keystart = ctx->fmtpos;
13688 /* Skip over balanced parentheses */
13689 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13690 arg->ch = FORMAT_READ(ctx);
13691 if (arg->ch == ')')
13692 --pcount;
13693 else if (arg->ch == '(')
13694 ++pcount;
13695 ctx->fmtpos++;
13696 }
13697 keylen = ctx->fmtpos - keystart - 1;
13698 if (ctx->fmtcnt < 0 || pcount > 0) {
13699 PyErr_SetString(PyExc_ValueError,
13700 "incomplete format key");
13701 return -1;
13702 }
13703 key = PyUnicode_Substring(ctx->fmtstr,
13704 keystart, keystart + keylen);
13705 if (key == NULL)
13706 return -1;
13707 if (ctx->args_owned) {
13708 Py_DECREF(ctx->args);
13709 ctx->args_owned = 0;
13710 }
13711 ctx->args = PyObject_GetItem(ctx->dict, key);
13712 Py_DECREF(key);
13713 if (ctx->args == NULL)
13714 return -1;
13715 ctx->args_owned = 1;
13716 ctx->arglen = -1;
13717 ctx->argidx = -2;
13718 }
13719
13720 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020013721 while (--ctx->fmtcnt >= 0) {
13722 arg->ch = FORMAT_READ(ctx);
13723 ctx->fmtpos++;
13724 switch (arg->ch) {
13725 case '-': arg->flags |= F_LJUST; continue;
13726 case '+': arg->flags |= F_SIGN; continue;
13727 case ' ': arg->flags |= F_BLANK; continue;
13728 case '#': arg->flags |= F_ALT; continue;
13729 case '0': arg->flags |= F_ZERO; continue;
13730 }
13731 break;
13732 }
13733
13734 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020013735 if (arg->ch == '*') {
13736 v = unicode_format_getnextarg(ctx);
13737 if (v == NULL)
13738 return -1;
13739 if (!PyLong_Check(v)) {
13740 PyErr_SetString(PyExc_TypeError,
13741 "* wants int");
13742 return -1;
13743 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013744 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013745 if (arg->width == -1 && PyErr_Occurred())
13746 return -1;
13747 if (arg->width < 0) {
13748 arg->flags |= F_LJUST;
13749 arg->width = -arg->width;
13750 }
13751 if (--ctx->fmtcnt >= 0) {
13752 arg->ch = FORMAT_READ(ctx);
13753 ctx->fmtpos++;
13754 }
13755 }
13756 else if (arg->ch >= '0' && arg->ch <= '9') {
13757 arg->width = arg->ch - '0';
13758 while (--ctx->fmtcnt >= 0) {
13759 arg->ch = FORMAT_READ(ctx);
13760 ctx->fmtpos++;
13761 if (arg->ch < '0' || arg->ch > '9')
13762 break;
13763 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13764 mixing signed and unsigned comparison. Since arg->ch is between
13765 '0' and '9', casting to int is safe. */
13766 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13767 PyErr_SetString(PyExc_ValueError,
13768 "width too big");
13769 return -1;
13770 }
13771 arg->width = arg->width*10 + (arg->ch - '0');
13772 }
13773 }
13774
13775 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020013776 if (arg->ch == '.') {
13777 arg->prec = 0;
13778 if (--ctx->fmtcnt >= 0) {
13779 arg->ch = FORMAT_READ(ctx);
13780 ctx->fmtpos++;
13781 }
13782 if (arg->ch == '*') {
13783 v = unicode_format_getnextarg(ctx);
13784 if (v == NULL)
13785 return -1;
13786 if (!PyLong_Check(v)) {
13787 PyErr_SetString(PyExc_TypeError,
13788 "* wants int");
13789 return -1;
13790 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013791 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013792 if (arg->prec == -1 && PyErr_Occurred())
13793 return -1;
13794 if (arg->prec < 0)
13795 arg->prec = 0;
13796 if (--ctx->fmtcnt >= 0) {
13797 arg->ch = FORMAT_READ(ctx);
13798 ctx->fmtpos++;
13799 }
13800 }
13801 else if (arg->ch >= '0' && arg->ch <= '9') {
13802 arg->prec = arg->ch - '0';
13803 while (--ctx->fmtcnt >= 0) {
13804 arg->ch = FORMAT_READ(ctx);
13805 ctx->fmtpos++;
13806 if (arg->ch < '0' || arg->ch > '9')
13807 break;
13808 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13809 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013810 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013811 return -1;
13812 }
13813 arg->prec = arg->prec*10 + (arg->ch - '0');
13814 }
13815 }
13816 }
13817
13818 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13819 if (ctx->fmtcnt >= 0) {
13820 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13821 if (--ctx->fmtcnt >= 0) {
13822 arg->ch = FORMAT_READ(ctx);
13823 ctx->fmtpos++;
13824 }
13825 }
13826 }
13827 if (ctx->fmtcnt < 0) {
13828 PyErr_SetString(PyExc_ValueError,
13829 "incomplete format");
13830 return -1;
13831 }
13832 return 0;
13833
13834#undef FORMAT_READ
13835}
13836
13837/* Format one argument. Supported conversion specifiers:
13838
13839 - "s", "r", "a": any type
13840 - "i", "d", "u", "o", "x", "X": int
13841 - "e", "E", "f", "F", "g", "G": float
13842 - "c": int or str (1 character)
13843
Victor Stinner8dbd4212012-12-04 09:30:24 +010013844 When possible, the output is written directly into the Unicode writer
13845 (ctx->writer). A string is created when padding is required.
13846
Victor Stinnera47082312012-10-04 02:19:54 +020013847 Return 0 if the argument has been formatted into *p_str,
13848 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010013849 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020013850static int
13851unicode_format_arg_format(struct unicode_formatter_t *ctx,
13852 struct unicode_format_arg_t *arg,
13853 PyObject **p_str)
13854{
13855 PyObject *v;
13856 _PyUnicodeWriter *writer = &ctx->writer;
13857
13858 if (ctx->fmtcnt == 0)
13859 ctx->writer.overallocate = 0;
13860
13861 if (arg->ch == '%') {
13862 if (_PyUnicodeWriter_Prepare(writer, 1, '%') == -1)
13863 return -1;
13864 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '%');
13865 writer->pos += 1;
13866 return 1;
13867 }
13868
13869 v = unicode_format_getnextarg(ctx);
13870 if (v == NULL)
13871 return -1;
13872
Victor Stinnera47082312012-10-04 02:19:54 +020013873
13874 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020013875 case 's':
13876 case 'r':
13877 case 'a':
13878 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
13879 /* Fast path */
13880 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
13881 return -1;
13882 return 1;
13883 }
13884
13885 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
13886 *p_str = v;
13887 Py_INCREF(*p_str);
13888 }
13889 else {
13890 if (arg->ch == 's')
13891 *p_str = PyObject_Str(v);
13892 else if (arg->ch == 'r')
13893 *p_str = PyObject_Repr(v);
13894 else
13895 *p_str = PyObject_ASCII(v);
13896 }
13897 break;
13898
13899 case 'i':
13900 case 'd':
13901 case 'u':
13902 case 'o':
13903 case 'x':
13904 case 'X':
13905 {
13906 int ret = mainformatlong(v, arg, p_str, writer);
13907 if (ret != 0)
13908 return ret;
13909 arg->sign = 1;
13910 break;
13911 }
13912
13913 case 'e':
13914 case 'E':
13915 case 'f':
13916 case 'F':
13917 case 'g':
13918 case 'G':
13919 if (arg->width == -1 && arg->prec == -1
13920 && !(arg->flags & (F_SIGN | F_BLANK)))
13921 {
13922 /* Fast path */
13923 if (formatfloat(v, arg, NULL, writer) == -1)
13924 return -1;
13925 return 1;
13926 }
13927
13928 arg->sign = 1;
13929 if (formatfloat(v, arg, p_str, NULL) == -1)
13930 return -1;
13931 break;
13932
13933 case 'c':
13934 {
13935 Py_UCS4 ch = formatchar(v);
13936 if (ch == (Py_UCS4) -1)
13937 return -1;
13938 if (arg->width == -1 && arg->prec == -1) {
13939 /* Fast path */
13940 if (_PyUnicodeWriter_Prepare(writer, 1, ch) == -1)
13941 return -1;
13942 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13943 writer->pos += 1;
13944 return 1;
13945 }
13946 *p_str = PyUnicode_FromOrdinal(ch);
13947 break;
13948 }
13949
13950 default:
13951 PyErr_Format(PyExc_ValueError,
13952 "unsupported format character '%c' (0x%x) "
13953 "at index %zd",
13954 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
13955 (int)arg->ch,
13956 ctx->fmtpos - 1);
13957 return -1;
13958 }
13959 if (*p_str == NULL)
13960 return -1;
13961 assert (PyUnicode_Check(*p_str));
13962 return 0;
13963}
13964
13965static int
13966unicode_format_arg_output(struct unicode_formatter_t *ctx,
13967 struct unicode_format_arg_t *arg,
13968 PyObject *str)
13969{
13970 Py_ssize_t len;
13971 enum PyUnicode_Kind kind;
13972 void *pbuf;
13973 Py_ssize_t pindex;
13974 Py_UCS4 signchar;
13975 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020013976 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020013977 Py_ssize_t sublen;
13978 _PyUnicodeWriter *writer = &ctx->writer;
13979 Py_UCS4 fill;
13980
13981 fill = ' ';
13982 if (arg->sign && arg->flags & F_ZERO)
13983 fill = '0';
13984
13985 if (PyUnicode_READY(str) == -1)
13986 return -1;
13987
13988 len = PyUnicode_GET_LENGTH(str);
13989 if ((arg->width == -1 || arg->width <= len)
13990 && (arg->prec == -1 || arg->prec >= len)
13991 && !(arg->flags & (F_SIGN | F_BLANK)))
13992 {
13993 /* Fast path */
13994 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
13995 return -1;
13996 return 0;
13997 }
13998
13999 /* Truncate the string for "s", "r" and "a" formats
14000 if the precision is set */
14001 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14002 if (arg->prec >= 0 && len > arg->prec)
14003 len = arg->prec;
14004 }
14005
14006 /* Adjust sign and width */
14007 kind = PyUnicode_KIND(str);
14008 pbuf = PyUnicode_DATA(str);
14009 pindex = 0;
14010 signchar = '\0';
14011 if (arg->sign) {
14012 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14013 if (ch == '-' || ch == '+') {
14014 signchar = ch;
14015 len--;
14016 pindex++;
14017 }
14018 else if (arg->flags & F_SIGN)
14019 signchar = '+';
14020 else if (arg->flags & F_BLANK)
14021 signchar = ' ';
14022 else
14023 arg->sign = 0;
14024 }
14025 if (arg->width < len)
14026 arg->width = len;
14027
14028 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014029 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014030 if (!(arg->flags & F_LJUST)) {
14031 if (arg->sign) {
14032 if ((arg->width-1) > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014033 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014034 }
14035 else {
14036 if (arg->width > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014037 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014038 }
14039 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014040 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14041 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
14042 maxchar = MAX_MAXCHAR(maxchar, strmaxchar);
14043 }
14044
Victor Stinnera47082312012-10-04 02:19:54 +020014045 buflen = arg->width;
14046 if (arg->sign && len == arg->width)
14047 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014048 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014049 return -1;
14050
14051 /* Write the sign if needed */
14052 if (arg->sign) {
14053 if (fill != ' ') {
14054 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14055 writer->pos += 1;
14056 }
14057 if (arg->width > len)
14058 arg->width--;
14059 }
14060
14061 /* Write the numeric prefix for "x", "X" and "o" formats
14062 if the alternate form is used.
14063 For example, write "0x" for the "%#x" format. */
14064 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14065 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14066 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14067 if (fill != ' ') {
14068 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14069 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14070 writer->pos += 2;
14071 pindex += 2;
14072 }
14073 arg->width -= 2;
14074 if (arg->width < 0)
14075 arg->width = 0;
14076 len -= 2;
14077 }
14078
14079 /* Pad left with the fill character if needed */
14080 if (arg->width > len && !(arg->flags & F_LJUST)) {
14081 sublen = arg->width - len;
14082 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14083 writer->pos += sublen;
14084 arg->width = len;
14085 }
14086
14087 /* If padding with spaces: write sign if needed and/or numeric prefix if
14088 the alternate form is used */
14089 if (fill == ' ') {
14090 if (arg->sign) {
14091 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14092 writer->pos += 1;
14093 }
14094 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14095 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14096 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
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 }
14103
14104 /* Write characters */
14105 if (len) {
14106 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14107 str, pindex, len);
14108 writer->pos += len;
14109 }
14110
14111 /* Pad right with the fill character if needed */
14112 if (arg->width > len) {
14113 sublen = arg->width - len;
14114 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14115 writer->pos += sublen;
14116 }
14117 return 0;
14118}
14119
14120/* Helper of PyUnicode_Format(): format one arg.
14121 Return 0 on success, raise an exception and return -1 on error. */
14122static int
14123unicode_format_arg(struct unicode_formatter_t *ctx)
14124{
14125 struct unicode_format_arg_t arg;
14126 PyObject *str;
14127 int ret;
14128
Victor Stinner8dbd4212012-12-04 09:30:24 +010014129 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14130 arg.flags = 0;
14131 arg.width = -1;
14132 arg.prec = -1;
14133 arg.sign = 0;
14134 str = NULL;
14135
Victor Stinnera47082312012-10-04 02:19:54 +020014136 ret = unicode_format_arg_parse(ctx, &arg);
14137 if (ret == -1)
14138 return -1;
14139
14140 ret = unicode_format_arg_format(ctx, &arg, &str);
14141 if (ret == -1)
14142 return -1;
14143
14144 if (ret != 1) {
14145 ret = unicode_format_arg_output(ctx, &arg, str);
14146 Py_DECREF(str);
14147 if (ret == -1)
14148 return -1;
14149 }
14150
14151 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14152 PyErr_SetString(PyExc_TypeError,
14153 "not all arguments converted during string formatting");
14154 return -1;
14155 }
14156 return 0;
14157}
14158
Alexander Belopolsky40018472011-02-26 01:02:56 +000014159PyObject *
14160PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014161{
Victor Stinnera47082312012-10-04 02:19:54 +020014162 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014163
Guido van Rossumd57fd912000-03-10 22:53:23 +000014164 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014165 PyErr_BadInternalCall();
14166 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014167 }
Victor Stinnera47082312012-10-04 02:19:54 +020014168
14169 ctx.fmtstr = PyUnicode_FromObject(format);
14170 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014171 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014172 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14173 Py_DECREF(ctx.fmtstr);
14174 return NULL;
14175 }
14176 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14177 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14178 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14179 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014180
Victor Stinnera47082312012-10-04 02:19:54 +020014181 _PyUnicodeWriter_Init(&ctx.writer, ctx.fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014182
Guido van Rossumd57fd912000-03-10 22:53:23 +000014183 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014184 ctx.arglen = PyTuple_Size(args);
14185 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014186 }
14187 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014188 ctx.arglen = -1;
14189 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014190 }
Victor Stinnera47082312012-10-04 02:19:54 +020014191 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014192 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014193 ctx.dict = args;
14194 else
14195 ctx.dict = NULL;
14196 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014197
Victor Stinnera47082312012-10-04 02:19:54 +020014198 while (--ctx.fmtcnt >= 0) {
14199 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014200 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014201
14202 nonfmtpos = ctx.fmtpos++;
14203 while (ctx.fmtcnt >= 0 &&
14204 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14205 ctx.fmtpos++;
14206 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014207 }
Victor Stinnera47082312012-10-04 02:19:54 +020014208 if (ctx.fmtcnt < 0) {
14209 ctx.fmtpos--;
14210 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014211 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014212
Victor Stinnercfc4c132013-04-03 01:48:39 +020014213 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14214 nonfmtpos, ctx.fmtpos) < 0)
14215 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014216 }
14217 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014218 ctx.fmtpos++;
14219 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014220 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014221 }
14222 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014223
Victor Stinnera47082312012-10-04 02:19:54 +020014224 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014225 PyErr_SetString(PyExc_TypeError,
14226 "not all arguments converted during string formatting");
14227 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014228 }
14229
Victor Stinnera47082312012-10-04 02:19:54 +020014230 if (ctx.args_owned) {
14231 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014232 }
Victor Stinnera47082312012-10-04 02:19:54 +020014233 Py_DECREF(ctx.fmtstr);
14234 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014235
Benjamin Peterson29060642009-01-31 22:14:21 +000014236 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014237 Py_DECREF(ctx.fmtstr);
14238 _PyUnicodeWriter_Dealloc(&ctx.writer);
14239 if (ctx.args_owned) {
14240 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014241 }
14242 return NULL;
14243}
14244
Jeremy Hylton938ace62002-07-17 16:30:39 +000014245static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014246unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14247
Tim Peters6d6c1a32001-08-02 04:15:00 +000014248static PyObject *
14249unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14250{
Benjamin Peterson29060642009-01-31 22:14:21 +000014251 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014252 static char *kwlist[] = {"object", "encoding", "errors", 0};
14253 char *encoding = NULL;
14254 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014255
Benjamin Peterson14339b62009-01-31 16:36:08 +000014256 if (type != &PyUnicode_Type)
14257 return unicode_subtype_new(type, args, kwds);
14258 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014259 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014260 return NULL;
14261 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014262 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014263 if (encoding == NULL && errors == NULL)
14264 return PyObject_Str(x);
14265 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014266 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014267}
14268
Guido van Rossume023fe02001-08-30 03:12:59 +000014269static PyObject *
14270unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14271{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014272 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014273 Py_ssize_t length, char_size;
14274 int share_wstr, share_utf8;
14275 unsigned int kind;
14276 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014277
Benjamin Peterson14339b62009-01-31 16:36:08 +000014278 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014279
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014280 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014281 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014283 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014284 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014285 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014286 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014287 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014288
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014289 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014290 if (self == NULL) {
14291 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014292 return NULL;
14293 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014294 kind = PyUnicode_KIND(unicode);
14295 length = PyUnicode_GET_LENGTH(unicode);
14296
14297 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014298#ifdef Py_DEBUG
14299 _PyUnicode_HASH(self) = -1;
14300#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014301 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014302#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014303 _PyUnicode_STATE(self).interned = 0;
14304 _PyUnicode_STATE(self).kind = kind;
14305 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014306 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014307 _PyUnicode_STATE(self).ready = 1;
14308 _PyUnicode_WSTR(self) = NULL;
14309 _PyUnicode_UTF8_LENGTH(self) = 0;
14310 _PyUnicode_UTF8(self) = NULL;
14311 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014312 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014313
14314 share_utf8 = 0;
14315 share_wstr = 0;
14316 if (kind == PyUnicode_1BYTE_KIND) {
14317 char_size = 1;
14318 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14319 share_utf8 = 1;
14320 }
14321 else if (kind == PyUnicode_2BYTE_KIND) {
14322 char_size = 2;
14323 if (sizeof(wchar_t) == 2)
14324 share_wstr = 1;
14325 }
14326 else {
14327 assert(kind == PyUnicode_4BYTE_KIND);
14328 char_size = 4;
14329 if (sizeof(wchar_t) == 4)
14330 share_wstr = 1;
14331 }
14332
14333 /* Ensure we won't overflow the length. */
14334 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14335 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014336 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014337 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014338 data = PyObject_MALLOC((length + 1) * char_size);
14339 if (data == NULL) {
14340 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014341 goto onError;
14342 }
14343
Victor Stinnerc3c74152011-10-02 20:39:55 +020014344 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014345 if (share_utf8) {
14346 _PyUnicode_UTF8_LENGTH(self) = length;
14347 _PyUnicode_UTF8(self) = data;
14348 }
14349 if (share_wstr) {
14350 _PyUnicode_WSTR_LENGTH(self) = length;
14351 _PyUnicode_WSTR(self) = (wchar_t *)data;
14352 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014353
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014354 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014355 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014356 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014357#ifdef Py_DEBUG
14358 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14359#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014360 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014361 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014362
14363onError:
14364 Py_DECREF(unicode);
14365 Py_DECREF(self);
14366 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014367}
14368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014369PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014370"str(object='') -> str\n\
14371str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014372\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014373Create a new string object from the given object. If encoding or\n\
14374errors is specified, then the object must expose a data buffer\n\
14375that will be decoded using the given encoding and error handler.\n\
14376Otherwise, returns the result of object.__str__() (if defined)\n\
14377or repr(object).\n\
14378encoding defaults to sys.getdefaultencoding().\n\
14379errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014380
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014381static PyObject *unicode_iter(PyObject *seq);
14382
Guido van Rossumd57fd912000-03-10 22:53:23 +000014383PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014384 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014385 "str", /* tp_name */
14386 sizeof(PyUnicodeObject), /* tp_size */
14387 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014388 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014389 (destructor)unicode_dealloc, /* tp_dealloc */
14390 0, /* tp_print */
14391 0, /* tp_getattr */
14392 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014393 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014394 unicode_repr, /* tp_repr */
14395 &unicode_as_number, /* tp_as_number */
14396 &unicode_as_sequence, /* tp_as_sequence */
14397 &unicode_as_mapping, /* tp_as_mapping */
14398 (hashfunc) unicode_hash, /* tp_hash*/
14399 0, /* tp_call*/
14400 (reprfunc) unicode_str, /* tp_str */
14401 PyObject_GenericGetAttr, /* tp_getattro */
14402 0, /* tp_setattro */
14403 0, /* tp_as_buffer */
14404 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014405 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014406 unicode_doc, /* tp_doc */
14407 0, /* tp_traverse */
14408 0, /* tp_clear */
14409 PyUnicode_RichCompare, /* tp_richcompare */
14410 0, /* tp_weaklistoffset */
14411 unicode_iter, /* tp_iter */
14412 0, /* tp_iternext */
14413 unicode_methods, /* tp_methods */
14414 0, /* tp_members */
14415 0, /* tp_getset */
14416 &PyBaseObject_Type, /* tp_base */
14417 0, /* tp_dict */
14418 0, /* tp_descr_get */
14419 0, /* tp_descr_set */
14420 0, /* tp_dictoffset */
14421 0, /* tp_init */
14422 0, /* tp_alloc */
14423 unicode_new, /* tp_new */
14424 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014425};
14426
14427/* Initialize the Unicode implementation */
14428
Victor Stinner3a50e702011-10-18 21:21:00 +020014429int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014430{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014431 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014432 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014433 0x000A, /* LINE FEED */
14434 0x000D, /* CARRIAGE RETURN */
14435 0x001C, /* FILE SEPARATOR */
14436 0x001D, /* GROUP SEPARATOR */
14437 0x001E, /* RECORD SEPARATOR */
14438 0x0085, /* NEXT LINE */
14439 0x2028, /* LINE SEPARATOR */
14440 0x2029, /* PARAGRAPH SEPARATOR */
14441 };
14442
Fred Drakee4315f52000-05-09 19:53:39 +000014443 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014444 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014445 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014446 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014447 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014448
Guido van Rossumcacfc072002-05-24 19:01:59 +000014449 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014450 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014451
14452 /* initialize the linebreak bloom filter */
14453 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014454 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014455 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014456
14457 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014458
Benjamin Petersonc4311282012-10-30 23:21:10 -040014459 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14460 Py_FatalError("Can't initialize field name iterator type");
14461
14462 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14463 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014464
Victor Stinner3a50e702011-10-18 21:21:00 +020014465#ifdef HAVE_MBCS
14466 winver.dwOSVersionInfoSize = sizeof(winver);
14467 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14468 PyErr_SetFromWindowsErr(0);
14469 return -1;
14470 }
14471#endif
14472 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014473}
14474
14475/* Finalize the Unicode implementation */
14476
Christian Heimesa156e092008-02-16 07:38:31 +000014477int
14478PyUnicode_ClearFreeList(void)
14479{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014480 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014481}
14482
Guido van Rossumd57fd912000-03-10 22:53:23 +000014483void
Thomas Wouters78890102000-07-22 19:25:51 +000014484_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014485{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014486 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014487
Serhiy Storchaka05997252013-01-26 12:14:02 +020014488 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014489
Serhiy Storchaka05997252013-01-26 12:14:02 +020014490 for (i = 0; i < 256; i++)
14491 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014492 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014493 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014494}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014495
Walter Dörwald16807132007-05-25 13:52:07 +000014496void
14497PyUnicode_InternInPlace(PyObject **p)
14498{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014499 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014500 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014501#ifdef Py_DEBUG
14502 assert(s != NULL);
14503 assert(_PyUnicode_CHECK(s));
14504#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014505 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014506 return;
14507#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014508 /* If it's a subclass, we don't really know what putting
14509 it in the interned dict might do. */
14510 if (!PyUnicode_CheckExact(s))
14511 return;
14512 if (PyUnicode_CHECK_INTERNED(s))
14513 return;
14514 if (interned == NULL) {
14515 interned = PyDict_New();
14516 if (interned == NULL) {
14517 PyErr_Clear(); /* Don't leave an exception */
14518 return;
14519 }
14520 }
14521 /* It might be that the GetItem call fails even
14522 though the key is present in the dictionary,
14523 namely when this happens during a stack overflow. */
14524 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014525 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014526 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014527
Benjamin Peterson29060642009-01-31 22:14:21 +000014528 if (t) {
14529 Py_INCREF(t);
14530 Py_DECREF(*p);
14531 *p = t;
14532 return;
14533 }
Walter Dörwald16807132007-05-25 13:52:07 +000014534
Benjamin Peterson14339b62009-01-31 16:36:08 +000014535 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014536 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014537 PyErr_Clear();
14538 PyThreadState_GET()->recursion_critical = 0;
14539 return;
14540 }
14541 PyThreadState_GET()->recursion_critical = 0;
14542 /* The two references in interned are not counted by refcnt.
14543 The deallocator will take care of this */
14544 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014545 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014546}
14547
14548void
14549PyUnicode_InternImmortal(PyObject **p)
14550{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014551 PyUnicode_InternInPlace(p);
14552 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014553 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014554 Py_INCREF(*p);
14555 }
Walter Dörwald16807132007-05-25 13:52:07 +000014556}
14557
14558PyObject *
14559PyUnicode_InternFromString(const char *cp)
14560{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014561 PyObject *s = PyUnicode_FromString(cp);
14562 if (s == NULL)
14563 return NULL;
14564 PyUnicode_InternInPlace(&s);
14565 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014566}
14567
Alexander Belopolsky40018472011-02-26 01:02:56 +000014568void
14569_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014570{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014571 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014572 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014573 Py_ssize_t i, n;
14574 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014575
Benjamin Peterson14339b62009-01-31 16:36:08 +000014576 if (interned == NULL || !PyDict_Check(interned))
14577 return;
14578 keys = PyDict_Keys(interned);
14579 if (keys == NULL || !PyList_Check(keys)) {
14580 PyErr_Clear();
14581 return;
14582 }
Walter Dörwald16807132007-05-25 13:52:07 +000014583
Benjamin Peterson14339b62009-01-31 16:36:08 +000014584 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14585 detector, interned unicode strings are not forcibly deallocated;
14586 rather, we give them their stolen references back, and then clear
14587 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014588
Benjamin Peterson14339b62009-01-31 16:36:08 +000014589 n = PyList_GET_SIZE(keys);
14590 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014591 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014592 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014593 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014594 if (PyUnicode_READY(s) == -1) {
14595 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014596 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014597 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014598 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014599 case SSTATE_NOT_INTERNED:
14600 /* XXX Shouldn't happen */
14601 break;
14602 case SSTATE_INTERNED_IMMORTAL:
14603 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014604 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014605 break;
14606 case SSTATE_INTERNED_MORTAL:
14607 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014608 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014609 break;
14610 default:
14611 Py_FatalError("Inconsistent interned string state.");
14612 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014613 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014614 }
14615 fprintf(stderr, "total size of all interned strings: "
14616 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14617 "mortal/immortal\n", mortal_size, immortal_size);
14618 Py_DECREF(keys);
14619 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014620 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014621}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014622
14623
14624/********************* Unicode Iterator **************************/
14625
14626typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014627 PyObject_HEAD
14628 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014629 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014630} unicodeiterobject;
14631
14632static void
14633unicodeiter_dealloc(unicodeiterobject *it)
14634{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014635 _PyObject_GC_UNTRACK(it);
14636 Py_XDECREF(it->it_seq);
14637 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014638}
14639
14640static int
14641unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14642{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014643 Py_VISIT(it->it_seq);
14644 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014645}
14646
14647static PyObject *
14648unicodeiter_next(unicodeiterobject *it)
14649{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014650 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014651
Benjamin Peterson14339b62009-01-31 16:36:08 +000014652 assert(it != NULL);
14653 seq = it->it_seq;
14654 if (seq == NULL)
14655 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014656 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014658 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14659 int kind = PyUnicode_KIND(seq);
14660 void *data = PyUnicode_DATA(seq);
14661 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14662 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014663 if (item != NULL)
14664 ++it->it_index;
14665 return item;
14666 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014667
Benjamin Peterson14339b62009-01-31 16:36:08 +000014668 Py_DECREF(seq);
14669 it->it_seq = NULL;
14670 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014671}
14672
14673static PyObject *
14674unicodeiter_len(unicodeiterobject *it)
14675{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014676 Py_ssize_t len = 0;
14677 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014678 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014679 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014680}
14681
14682PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14683
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014684static PyObject *
14685unicodeiter_reduce(unicodeiterobject *it)
14686{
14687 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014688 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014689 it->it_seq, it->it_index);
14690 } else {
14691 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14692 if (u == NULL)
14693 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014694 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014695 }
14696}
14697
14698PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14699
14700static PyObject *
14701unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14702{
14703 Py_ssize_t index = PyLong_AsSsize_t(state);
14704 if (index == -1 && PyErr_Occurred())
14705 return NULL;
14706 if (index < 0)
14707 index = 0;
14708 it->it_index = index;
14709 Py_RETURN_NONE;
14710}
14711
14712PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14713
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014714static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014715 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014716 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014717 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14718 reduce_doc},
14719 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14720 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014721 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014722};
14723
14724PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014725 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14726 "str_iterator", /* tp_name */
14727 sizeof(unicodeiterobject), /* tp_basicsize */
14728 0, /* tp_itemsize */
14729 /* methods */
14730 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14731 0, /* tp_print */
14732 0, /* tp_getattr */
14733 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014734 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014735 0, /* tp_repr */
14736 0, /* tp_as_number */
14737 0, /* tp_as_sequence */
14738 0, /* tp_as_mapping */
14739 0, /* tp_hash */
14740 0, /* tp_call */
14741 0, /* tp_str */
14742 PyObject_GenericGetAttr, /* tp_getattro */
14743 0, /* tp_setattro */
14744 0, /* tp_as_buffer */
14745 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14746 0, /* tp_doc */
14747 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14748 0, /* tp_clear */
14749 0, /* tp_richcompare */
14750 0, /* tp_weaklistoffset */
14751 PyObject_SelfIter, /* tp_iter */
14752 (iternextfunc)unicodeiter_next, /* tp_iternext */
14753 unicodeiter_methods, /* tp_methods */
14754 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014755};
14756
14757static PyObject *
14758unicode_iter(PyObject *seq)
14759{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014760 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014761
Benjamin Peterson14339b62009-01-31 16:36:08 +000014762 if (!PyUnicode_Check(seq)) {
14763 PyErr_BadInternalCall();
14764 return NULL;
14765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014766 if (PyUnicode_READY(seq) == -1)
14767 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014768 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14769 if (it == NULL)
14770 return NULL;
14771 it->it_index = 0;
14772 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014773 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014774 _PyObject_GC_TRACK(it);
14775 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014776}
14777
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014778
14779size_t
14780Py_UNICODE_strlen(const Py_UNICODE *u)
14781{
14782 int res = 0;
14783 while(*u++)
14784 res++;
14785 return res;
14786}
14787
14788Py_UNICODE*
14789Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14790{
14791 Py_UNICODE *u = s1;
14792 while ((*u++ = *s2++));
14793 return s1;
14794}
14795
14796Py_UNICODE*
14797Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14798{
14799 Py_UNICODE *u = s1;
14800 while ((*u++ = *s2++))
14801 if (n-- == 0)
14802 break;
14803 return s1;
14804}
14805
14806Py_UNICODE*
14807Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14808{
14809 Py_UNICODE *u1 = s1;
14810 u1 += Py_UNICODE_strlen(u1);
14811 Py_UNICODE_strcpy(u1, s2);
14812 return s1;
14813}
14814
14815int
14816Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14817{
14818 while (*s1 && *s2 && *s1 == *s2)
14819 s1++, s2++;
14820 if (*s1 && *s2)
14821 return (*s1 < *s2) ? -1 : +1;
14822 if (*s1)
14823 return 1;
14824 if (*s2)
14825 return -1;
14826 return 0;
14827}
14828
14829int
14830Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14831{
14832 register Py_UNICODE u1, u2;
14833 for (; n != 0; n--) {
14834 u1 = *s1;
14835 u2 = *s2;
14836 if (u1 != u2)
14837 return (u1 < u2) ? -1 : +1;
14838 if (u1 == '\0')
14839 return 0;
14840 s1++;
14841 s2++;
14842 }
14843 return 0;
14844}
14845
14846Py_UNICODE*
14847Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14848{
14849 const Py_UNICODE *p;
14850 for (p = s; *p; p++)
14851 if (*p == c)
14852 return (Py_UNICODE*)p;
14853 return NULL;
14854}
14855
14856Py_UNICODE*
14857Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14858{
14859 const Py_UNICODE *p;
14860 p = s + Py_UNICODE_strlen(s);
14861 while (p != s) {
14862 p--;
14863 if (*p == c)
14864 return (Py_UNICODE*)p;
14865 }
14866 return NULL;
14867}
Victor Stinner331ea922010-08-10 16:37:20 +000014868
Victor Stinner71133ff2010-09-01 23:43:53 +000014869Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014870PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014871{
Victor Stinner577db2c2011-10-11 22:12:48 +020014872 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014873 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014875 if (!PyUnicode_Check(unicode)) {
14876 PyErr_BadArgument();
14877 return NULL;
14878 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014879 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014880 if (u == NULL)
14881 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014882 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014883 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014884 PyErr_NoMemory();
14885 return NULL;
14886 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014887 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014888 size *= sizeof(Py_UNICODE);
14889 copy = PyMem_Malloc(size);
14890 if (copy == NULL) {
14891 PyErr_NoMemory();
14892 return NULL;
14893 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014894 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014895 return copy;
14896}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014897
Georg Brandl66c221e2010-10-14 07:04:07 +000014898/* A _string module, to export formatter_parser and formatter_field_name_split
14899 to the string.Formatter class implemented in Python. */
14900
14901static PyMethodDef _string_methods[] = {
14902 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14903 METH_O, PyDoc_STR("split the argument as a field name")},
14904 {"formatter_parser", (PyCFunction) formatter_parser,
14905 METH_O, PyDoc_STR("parse the argument as a format string")},
14906 {NULL, NULL}
14907};
14908
14909static struct PyModuleDef _string_module = {
14910 PyModuleDef_HEAD_INIT,
14911 "_string",
14912 PyDoc_STR("string helper module"),
14913 0,
14914 _string_methods,
14915 NULL,
14916 NULL,
14917 NULL,
14918 NULL
14919};
14920
14921PyMODINIT_FUNC
14922PyInit__string(void)
14923{
14924 return PyModule_Create(&_string_module);
14925}
14926
14927
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014928#ifdef __cplusplus
14929}
14930#endif