blob: 162221ceb2054d189b3fc15fe3e713f265c4eccc [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;
Victor Stinner0cff4b12013-04-09 22:52:48 +02009975 char *src, *rbuf;
Victor Stinnerf6441102011-12-18 02:43:08 +01009976
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 Stinner0cff4b12013-04-09 22:52:48 +02009987 rbuf = PyUnicode_DATA(u);
Victor Stinnerf6441102011-12-18 02:43:08 +01009988
Victor Stinner0cff4b12013-04-09 22:52:48 +02009989 PyUnicode_WRITE(rkind, rbuf, pos, u2);
Victor Stinnerf6441102011-12-18 02:43:08 +01009990 index = 0;
9991 src = sbuf;
9992 while (--maxcount)
9993 {
9994 pos++;
9995 src += pos * PyUnicode_KIND(self);
9996 slen -= pos;
9997 index += pos;
9998 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
9999 if (pos < 0)
10000 break;
Victor Stinner0cff4b12013-04-09 22:52:48 +020010001 PyUnicode_WRITE(rkind, rbuf, index + pos, u2);
Victor Stinnerf6441102011-12-18 02:43:08 +010010002 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010003 }
10004 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 int rkind = skind;
10006 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010007 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 if (kind1 < rkind) {
10010 /* widen substring */
10011 buf1 = _PyUnicode_AsKind(str1, rkind);
10012 if (!buf1) goto error;
10013 release1 = 1;
10014 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010015 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010016 if (i < 0)
10017 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018 if (rkind > kind2) {
10019 /* widen replacement */
10020 buf2 = _PyUnicode_AsKind(str2, rkind);
10021 if (!buf2) goto error;
10022 release2 = 1;
10023 }
10024 else if (rkind < kind2) {
10025 /* widen self and buf1 */
10026 rkind = kind2;
10027 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010028 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 sbuf = _PyUnicode_AsKind(self, rkind);
10030 if (!sbuf) goto error;
10031 srelease = 1;
10032 buf1 = _PyUnicode_AsKind(str1, rkind);
10033 if (!buf1) goto error;
10034 release1 = 1;
10035 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010036 u = PyUnicode_New(slen, maxchar);
10037 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010039 assert(PyUnicode_KIND(u) == rkind);
10040 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010041
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010042 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010043 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010044 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010046 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010048
10049 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010050 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010051 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010052 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010053 if (i == -1)
10054 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010055 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010057 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010059 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010060 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010061 }
10062 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010064 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 int rkind = skind;
10066 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010069 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 buf1 = _PyUnicode_AsKind(str1, rkind);
10071 if (!buf1) goto error;
10072 release1 = 1;
10073 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010074 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010075 if (n == 0)
10076 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010078 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 buf2 = _PyUnicode_AsKind(str2, rkind);
10080 if (!buf2) goto error;
10081 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010084 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 rkind = kind2;
10086 sbuf = _PyUnicode_AsKind(self, rkind);
10087 if (!sbuf) goto error;
10088 srelease = 1;
10089 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010090 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 buf1 = _PyUnicode_AsKind(str1, rkind);
10092 if (!buf1) goto error;
10093 release1 = 1;
10094 }
10095 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10096 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010097 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 PyErr_SetString(PyExc_OverflowError,
10099 "replace string is too long");
10100 goto error;
10101 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010102 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010103 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010104 _Py_INCREF_UNICODE_EMPTY();
10105 if (!unicode_empty)
10106 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010107 u = unicode_empty;
10108 goto done;
10109 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010110 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 PyErr_SetString(PyExc_OverflowError,
10112 "replace string is too long");
10113 goto error;
10114 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010115 u = PyUnicode_New(new_size, maxchar);
10116 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010118 assert(PyUnicode_KIND(u) == rkind);
10119 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 ires = i = 0;
10121 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010122 while (n-- > 0) {
10123 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010125 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010126 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010127 if (j == -1)
10128 break;
10129 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010130 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010131 memcpy(res + rkind * ires,
10132 sbuf + rkind * i,
10133 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010135 }
10136 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010138 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010140 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010146 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010147 memcpy(res + rkind * ires,
10148 sbuf + rkind * i,
10149 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010150 }
10151 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010152 /* interleave */
10153 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010154 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010156 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010158 if (--n <= 0)
10159 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010160 memcpy(res + rkind * ires,
10161 sbuf + rkind * i,
10162 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 ires++;
10164 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010165 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010166 memcpy(res + rkind * ires,
10167 sbuf + rkind * i,
10168 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010169 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010170 }
10171
10172 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010173 unicode_adjust_maxchar(&u);
10174 if (u == NULL)
10175 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010177
10178 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 if (srelease)
10180 PyMem_FREE(sbuf);
10181 if (release1)
10182 PyMem_FREE(buf1);
10183 if (release2)
10184 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010185 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010187
Benjamin Peterson29060642009-01-31 22:14:21 +000010188 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010189 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (srelease)
10191 PyMem_FREE(sbuf);
10192 if (release1)
10193 PyMem_FREE(buf1);
10194 if (release2)
10195 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010196 return unicode_result_unchanged(self);
10197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 error:
10199 if (srelease && sbuf)
10200 PyMem_FREE(sbuf);
10201 if (release1 && buf1)
10202 PyMem_FREE(buf1);
10203 if (release2 && buf2)
10204 PyMem_FREE(buf2);
10205 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010206}
10207
10208/* --- Unicode Object Methods --------------------------------------------- */
10209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010210PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010211 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212\n\
10213Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010214characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215
10216static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010217unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010218{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010219 if (PyUnicode_READY(self) == -1)
10220 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010221 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010222}
10223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010224PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010225 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226\n\
10227Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010228have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229
10230static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010231unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010232{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010233 if (PyUnicode_READY(self) == -1)
10234 return NULL;
10235 if (PyUnicode_GET_LENGTH(self) == 0)
10236 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010237 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010238}
10239
Benjamin Petersond5890c82012-01-14 13:23:30 -050010240PyDoc_STRVAR(casefold__doc__,
10241 "S.casefold() -> str\n\
10242\n\
10243Return a version of S suitable for caseless comparisons.");
10244
10245static PyObject *
10246unicode_casefold(PyObject *self)
10247{
10248 if (PyUnicode_READY(self) == -1)
10249 return NULL;
10250 if (PyUnicode_IS_ASCII(self))
10251 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010252 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010253}
10254
10255
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010256/* Argument converter. Coerces to a single unicode character */
10257
10258static int
10259convert_uc(PyObject *obj, void *addr)
10260{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010262 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010263
Benjamin Peterson14339b62009-01-31 16:36:08 +000010264 uniobj = PyUnicode_FromObject(obj);
10265 if (uniobj == NULL) {
10266 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010267 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010268 return 0;
10269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010271 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010272 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010273 Py_DECREF(uniobj);
10274 return 0;
10275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010277 Py_DECREF(uniobj);
10278 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010279}
10280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010281PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010282 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010284Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010285done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010286
10287static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010288unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010290 Py_ssize_t marg, left;
10291 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 Py_UCS4 fillchar = ' ';
10293
Victor Stinnere9a29352011-10-01 02:14:59 +020010294 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010296
Benjamin Petersonbac79492012-01-14 13:34:47 -050010297 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298 return NULL;
10299
Victor Stinnerc4b49542011-12-11 22:44:26 +010010300 if (PyUnicode_GET_LENGTH(self) >= width)
10301 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302
Victor Stinnerc4b49542011-12-11 22:44:26 +010010303 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304 left = marg / 2 + (marg & width & 1);
10305
Victor Stinner9310abb2011-10-05 00:59:23 +020010306 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307}
10308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309/* This function assumes that str1 and str2 are readied by the caller. */
10310
Marc-André Lemburge5034372000-08-08 08:04:29 +000010311static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010312unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010313{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010314#define COMPARE(TYPE1, TYPE2) \
10315 do { \
10316 TYPE1* p1 = (TYPE1 *)data1; \
10317 TYPE2* p2 = (TYPE2 *)data2; \
10318 TYPE1* end = p1 + len; \
10319 Py_UCS4 c1, c2; \
10320 for (; p1 != end; p1++, p2++) { \
10321 c1 = *p1; \
10322 c2 = *p2; \
10323 if (c1 != c2) \
10324 return (c1 < c2) ? -1 : 1; \
10325 } \
10326 } \
10327 while (0)
10328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 int kind1, kind2;
10330 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010331 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010332
Victor Stinner90db9c42012-10-04 21:53:50 +020010333 /* a string is equal to itself */
10334 if (str1 == str2)
10335 return 0;
10336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 kind1 = PyUnicode_KIND(str1);
10338 kind2 = PyUnicode_KIND(str2);
10339 data1 = PyUnicode_DATA(str1);
10340 data2 = PyUnicode_DATA(str2);
10341 len1 = PyUnicode_GET_LENGTH(str1);
10342 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010343 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010344
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010345 switch(kind1) {
10346 case PyUnicode_1BYTE_KIND:
10347 {
10348 switch(kind2) {
10349 case PyUnicode_1BYTE_KIND:
10350 {
10351 int cmp = memcmp(data1, data2, len);
10352 /* normalize result of memcmp() into the range [-1; 1] */
10353 if (cmp < 0)
10354 return -1;
10355 if (cmp > 0)
10356 return 1;
10357 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010358 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010359 case PyUnicode_2BYTE_KIND:
10360 COMPARE(Py_UCS1, Py_UCS2);
10361 break;
10362 case PyUnicode_4BYTE_KIND:
10363 COMPARE(Py_UCS1, Py_UCS4);
10364 break;
10365 default:
10366 assert(0);
10367 }
10368 break;
10369 }
10370 case PyUnicode_2BYTE_KIND:
10371 {
10372 switch(kind2) {
10373 case PyUnicode_1BYTE_KIND:
10374 COMPARE(Py_UCS2, Py_UCS1);
10375 break;
10376 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010377 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010378 COMPARE(Py_UCS2, Py_UCS2);
10379 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010380 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010381 case PyUnicode_4BYTE_KIND:
10382 COMPARE(Py_UCS2, Py_UCS4);
10383 break;
10384 default:
10385 assert(0);
10386 }
10387 break;
10388 }
10389 case PyUnicode_4BYTE_KIND:
10390 {
10391 switch(kind2) {
10392 case PyUnicode_1BYTE_KIND:
10393 COMPARE(Py_UCS4, Py_UCS1);
10394 break;
10395 case PyUnicode_2BYTE_KIND:
10396 COMPARE(Py_UCS4, Py_UCS2);
10397 break;
10398 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010399 {
10400#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10401 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10402 /* normalize result of wmemcmp() into the range [-1; 1] */
10403 if (cmp < 0)
10404 return -1;
10405 if (cmp > 0)
10406 return 1;
10407#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010408 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010409#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010410 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010411 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010412 default:
10413 assert(0);
10414 }
10415 break;
10416 }
10417 default:
10418 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010419 }
10420
Victor Stinner770e19e2012-10-04 22:59:45 +020010421 if (len1 == len2)
10422 return 0;
10423 if (len1 < len2)
10424 return -1;
10425 else
10426 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010427
10428#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010429}
10430
Victor Stinnere5567ad2012-10-23 02:48:49 +020010431static int
10432unicode_compare_eq(PyObject *str1, PyObject *str2)
10433{
10434 int kind;
10435 void *data1, *data2;
10436 Py_ssize_t len;
10437 int cmp;
10438
10439 /* a string is equal to itself */
10440 if (str1 == str2)
10441 return 1;
10442
10443 len = PyUnicode_GET_LENGTH(str1);
10444 if (PyUnicode_GET_LENGTH(str2) != len)
10445 return 0;
10446 kind = PyUnicode_KIND(str1);
10447 if (PyUnicode_KIND(str2) != kind)
10448 return 0;
10449 data1 = PyUnicode_DATA(str1);
10450 data2 = PyUnicode_DATA(str2);
10451
10452 cmp = memcmp(data1, data2, len * kind);
10453 return (cmp == 0);
10454}
10455
10456
Alexander Belopolsky40018472011-02-26 01:02:56 +000010457int
10458PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10461 if (PyUnicode_READY(left) == -1 ||
10462 PyUnicode_READY(right) == -1)
10463 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010464 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010466 PyErr_Format(PyExc_TypeError,
10467 "Can't compare %.100s and %.100s",
10468 left->ob_type->tp_name,
10469 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470 return -1;
10471}
10472
Martin v. Löwis5b222132007-06-10 09:51:05 +000010473int
10474PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10475{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 Py_ssize_t i;
10477 int kind;
10478 void *data;
10479 Py_UCS4 chr;
10480
Victor Stinner910337b2011-10-03 03:20:16 +020010481 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 if (PyUnicode_READY(uni) == -1)
10483 return -1;
10484 kind = PyUnicode_KIND(uni);
10485 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010486 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10488 if (chr != str[i])
10489 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010490 /* This check keeps Python strings that end in '\0' from comparing equal
10491 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010493 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010494 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010495 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010496 return 0;
10497}
10498
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010499
Benjamin Peterson29060642009-01-31 22:14:21 +000010500#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010501 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010502
Alexander Belopolsky40018472011-02-26 01:02:56 +000010503PyObject *
10504PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010505{
10506 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010507 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010508
Victor Stinnere5567ad2012-10-23 02:48:49 +020010509 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10510 Py_RETURN_NOTIMPLEMENTED;
10511
10512 if (PyUnicode_READY(left) == -1 ||
10513 PyUnicode_READY(right) == -1)
10514 return NULL;
10515
10516 if (op == Py_EQ || op == Py_NE) {
10517 result = unicode_compare_eq(left, right);
10518 if (op == Py_EQ)
10519 v = TEST_COND(result);
10520 else
10521 v = TEST_COND(!result);
10522 }
10523 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010524 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010525
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010526 /* Convert the return value to a Boolean */
10527 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010528 case Py_LE:
10529 v = TEST_COND(result <= 0);
10530 break;
10531 case Py_GE:
10532 v = TEST_COND(result >= 0);
10533 break;
10534 case Py_LT:
10535 v = TEST_COND(result == -1);
10536 break;
10537 case Py_GT:
10538 v = TEST_COND(result == 1);
10539 break;
10540 default:
10541 PyErr_BadArgument();
10542 return NULL;
10543 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010544 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010545 Py_INCREF(v);
10546 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010547}
10548
Alexander Belopolsky40018472011-02-26 01:02:56 +000010549int
10550PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010551{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010552 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 int kind1, kind2, kind;
10554 void *buf1, *buf2;
10555 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010556 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010557
10558 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010559 sub = PyUnicode_FromObject(element);
10560 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 PyErr_Format(PyExc_TypeError,
10562 "'in <string>' requires string as left operand, not %s",
10563 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010564 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010565 }
10566
Thomas Wouters477c8d52006-05-27 19:21:47 +000010567 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010568 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569 Py_DECREF(sub);
10570 return -1;
10571 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010572 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10573 Py_DECREF(sub);
10574 Py_DECREF(str);
10575 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 kind1 = PyUnicode_KIND(str);
10578 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010579 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 buf1 = PyUnicode_DATA(str);
10581 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010582 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010583 if (kind2 > kind) {
10584 Py_DECREF(sub);
10585 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010586 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010587 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010588 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (!buf2) {
10591 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010592 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 return -1;
10594 }
10595 len1 = PyUnicode_GET_LENGTH(str);
10596 len2 = PyUnicode_GET_LENGTH(sub);
10597
Benjamin Petersonead6b532011-12-20 17:23:42 -060010598 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 case PyUnicode_1BYTE_KIND:
10600 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10601 break;
10602 case PyUnicode_2BYTE_KIND:
10603 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10604 break;
10605 case PyUnicode_4BYTE_KIND:
10606 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10607 break;
10608 default:
10609 result = -1;
10610 assert(0);
10611 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612
10613 Py_DECREF(str);
10614 Py_DECREF(sub);
10615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 if (kind2 != kind)
10617 PyMem_Free(buf2);
10618
Guido van Rossum403d68b2000-03-13 15:55:09 +000010619 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010620}
10621
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622/* Concat to string or Unicode object giving a new Unicode object. */
10623
Alexander Belopolsky40018472011-02-26 01:02:56 +000010624PyObject *
10625PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010628 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010629 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630
10631 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010634 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010637 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638
10639 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010640 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010641 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010644 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010645 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647 }
10648
Victor Stinner488fa492011-12-12 00:01:39 +010010649 u_len = PyUnicode_GET_LENGTH(u);
10650 v_len = PyUnicode_GET_LENGTH(v);
10651 if (u_len > PY_SSIZE_T_MAX - v_len) {
10652 PyErr_SetString(PyExc_OverflowError,
10653 "strings are too large to concat");
10654 goto onError;
10655 }
10656 new_len = u_len + v_len;
10657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010659 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010660 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010663 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010665 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010666 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10667 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668 Py_DECREF(u);
10669 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010670 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672
Benjamin Peterson29060642009-01-31 22:14:21 +000010673 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674 Py_XDECREF(u);
10675 Py_XDECREF(v);
10676 return NULL;
10677}
10678
Walter Dörwald1ab83302007-05-18 17:15:44 +000010679void
Victor Stinner23e56682011-10-03 03:54:37 +020010680PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010681{
Victor Stinner23e56682011-10-03 03:54:37 +020010682 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010683 Py_UCS4 maxchar, maxchar2;
10684 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010685
10686 if (p_left == NULL) {
10687 if (!PyErr_Occurred())
10688 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010689 return;
10690 }
Victor Stinner23e56682011-10-03 03:54:37 +020010691 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010692 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010693 if (!PyErr_Occurred())
10694 PyErr_BadInternalCall();
10695 goto error;
10696 }
10697
Benjamin Petersonbac79492012-01-14 13:34:47 -050010698 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010699 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010700 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010701 goto error;
10702
Victor Stinner488fa492011-12-12 00:01:39 +010010703 /* Shortcuts */
10704 if (left == unicode_empty) {
10705 Py_DECREF(left);
10706 Py_INCREF(right);
10707 *p_left = right;
10708 return;
10709 }
10710 if (right == unicode_empty)
10711 return;
10712
10713 left_len = PyUnicode_GET_LENGTH(left);
10714 right_len = PyUnicode_GET_LENGTH(right);
10715 if (left_len > PY_SSIZE_T_MAX - right_len) {
10716 PyErr_SetString(PyExc_OverflowError,
10717 "strings are too large to concat");
10718 goto error;
10719 }
10720 new_len = left_len + right_len;
10721
10722 if (unicode_modifiable(left)
10723 && PyUnicode_CheckExact(right)
10724 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010725 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10726 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010727 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010728 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010729 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10730 {
10731 /* append inplace */
10732 if (unicode_resize(p_left, new_len) != 0) {
10733 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10734 * deallocated so it cannot be put back into
10735 * 'variable'. The MemoryError is raised when there
10736 * is no value in 'variable', which might (very
10737 * remotely) be a cause of incompatibilities.
10738 */
10739 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010740 }
Victor Stinner488fa492011-12-12 00:01:39 +010010741 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010742 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010743 }
Victor Stinner488fa492011-12-12 00:01:39 +010010744 else {
10745 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10746 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010747 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010748
Victor Stinner488fa492011-12-12 00:01:39 +010010749 /* Concat the two Unicode strings */
10750 res = PyUnicode_New(new_len, maxchar);
10751 if (res == NULL)
10752 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010753 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10754 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010755 Py_DECREF(left);
10756 *p_left = res;
10757 }
10758 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010759 return;
10760
10761error:
Victor Stinner488fa492011-12-12 00:01:39 +010010762 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010763}
10764
10765void
10766PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10767{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010768 PyUnicode_Append(pleft, right);
10769 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010770}
10771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010772PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010773 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010775Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010776string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010777interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778
10779static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010780unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010782 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010783 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010784 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 int kind1, kind2, kind;
10787 void *buf1, *buf2;
10788 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789
Jesus Ceaac451502011-04-20 17:09:23 +020010790 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10791 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010792 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 kind1 = PyUnicode_KIND(self);
10795 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010796 if (kind2 > kind1)
10797 return PyLong_FromLong(0);
10798 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 buf1 = PyUnicode_DATA(self);
10800 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010802 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010803 if (!buf2) {
10804 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010805 return NULL;
10806 }
10807 len1 = PyUnicode_GET_LENGTH(self);
10808 len2 = PyUnicode_GET_LENGTH(substring);
10809
10810 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010811 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 case PyUnicode_1BYTE_KIND:
10813 iresult = ucs1lib_count(
10814 ((Py_UCS1*)buf1) + start, end - start,
10815 buf2, len2, PY_SSIZE_T_MAX
10816 );
10817 break;
10818 case PyUnicode_2BYTE_KIND:
10819 iresult = ucs2lib_count(
10820 ((Py_UCS2*)buf1) + start, end - start,
10821 buf2, len2, PY_SSIZE_T_MAX
10822 );
10823 break;
10824 case PyUnicode_4BYTE_KIND:
10825 iresult = ucs4lib_count(
10826 ((Py_UCS4*)buf1) + start, end - start,
10827 buf2, len2, PY_SSIZE_T_MAX
10828 );
10829 break;
10830 default:
10831 assert(0); iresult = 0;
10832 }
10833
10834 result = PyLong_FromSsize_t(iresult);
10835
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 if (kind2 != kind)
10837 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838
10839 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010840
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841 return result;
10842}
10843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010844PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010845 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010847Encode S using the codec registered for encoding. Default encoding\n\
10848is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010849handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010850a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10851'xmlcharrefreplace' as well as any other name registered with\n\
10852codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853
10854static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010855unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010857 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858 char *encoding = NULL;
10859 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010860
Benjamin Peterson308d6372009-09-18 21:42:35 +000010861 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10862 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010864 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010865}
10866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010867PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010868 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869\n\
10870Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010871If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872
10873static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010874unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010876 Py_ssize_t i, j, line_pos, src_len, incr;
10877 Py_UCS4 ch;
10878 PyObject *u;
10879 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010881 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010882 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010883
10884 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886
Antoine Pitrou22425222011-10-04 19:10:51 +020010887 if (PyUnicode_READY(self) == -1)
10888 return NULL;
10889
Thomas Wouters7e474022000-07-16 12:04:32 +000010890 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010891 src_len = PyUnicode_GET_LENGTH(self);
10892 i = j = line_pos = 0;
10893 kind = PyUnicode_KIND(self);
10894 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010895 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 for (; i < src_len; i++) {
10897 ch = PyUnicode_READ(kind, src_data, i);
10898 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010899 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010900 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010901 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010903 goto overflow;
10904 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010905 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010906 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010907 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010909 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010910 goto overflow;
10911 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010913 if (ch == '\n' || ch == '\r')
10914 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010917 if (!found)
10918 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010919
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922 if (!u)
10923 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010924 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925
Antoine Pitroue71d5742011-10-04 15:55:09 +020010926 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927
Antoine Pitroue71d5742011-10-04 15:55:09 +020010928 for (; i < src_len; i++) {
10929 ch = PyUnicode_READ(kind, src_data, i);
10930 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010931 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010932 incr = tabsize - (line_pos % tabsize);
10933 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010934 FILL(kind, dest_data, ' ', j, incr);
10935 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010936 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010937 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010938 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010939 line_pos++;
10940 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010941 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010942 if (ch == '\n' || ch == '\r')
10943 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 }
10946 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010947 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010948
Antoine Pitroue71d5742011-10-04 15:55:09 +020010949 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010950 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10951 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952}
10953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010954PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956\n\
10957Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010958such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959arguments start and end are interpreted as in slice notation.\n\
10960\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010961Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962
10963static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010966 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010967 Py_ssize_t start;
10968 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010969 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
Jesus Ceaac451502011-04-20 17:09:23 +020010971 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10972 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 if (PyUnicode_READY(self) == -1)
10976 return NULL;
10977 if (PyUnicode_READY(substring) == -1)
10978 return NULL;
10979
Victor Stinner7931d9a2011-11-04 00:22:48 +010010980 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981
10982 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 if (result == -2)
10985 return NULL;
10986
Christian Heimes217cfd12007-12-02 14:31:20 +000010987 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988}
10989
10990static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010991unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010993 void *data;
10994 enum PyUnicode_Kind kind;
10995 Py_UCS4 ch;
10996 PyObject *res;
10997
10998 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10999 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011001 }
11002 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11003 PyErr_SetString(PyExc_IndexError, "string index out of range");
11004 return NULL;
11005 }
11006 kind = PyUnicode_KIND(self);
11007 data = PyUnicode_DATA(self);
11008 ch = PyUnicode_READ(kind, data, index);
11009 if (ch < 256)
11010 return get_latin1_char(ch);
11011
11012 res = PyUnicode_New(1, ch);
11013 if (res == NULL)
11014 return NULL;
11015 kind = PyUnicode_KIND(res);
11016 data = PyUnicode_DATA(res);
11017 PyUnicode_WRITE(kind, data, 0, ch);
11018 assert(_PyUnicode_CheckConsistency(res, 1));
11019 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020}
11021
Guido van Rossumc2504932007-09-18 19:42:40 +000011022/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011023 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011024static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011025unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026{
Guido van Rossumc2504932007-09-18 19:42:40 +000011027 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011028 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011029
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011030#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011031 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011032#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033 if (_PyUnicode_HASH(self) != -1)
11034 return _PyUnicode_HASH(self);
11035 if (PyUnicode_READY(self) == -1)
11036 return -1;
11037 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011038 /*
11039 We make the hash of the empty string be 0, rather than using
11040 (prefix ^ suffix), since this slightly obfuscates the hash secret
11041 */
11042 if (len == 0) {
11043 _PyUnicode_HASH(self) = 0;
11044 return 0;
11045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046
11047 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011048#define HASH(P) \
11049 x ^= (Py_uhash_t) *P << 7; \
11050 while (--len >= 0) \
11051 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011052
Georg Brandl2fb477c2012-02-21 00:33:36 +010011053 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 switch (PyUnicode_KIND(self)) {
11055 case PyUnicode_1BYTE_KIND: {
11056 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11057 HASH(c);
11058 break;
11059 }
11060 case PyUnicode_2BYTE_KIND: {
11061 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11062 HASH(s);
11063 break;
11064 }
11065 default: {
11066 Py_UCS4 *l;
11067 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11068 "Impossible switch case in unicode_hash");
11069 l = PyUnicode_4BYTE_DATA(self);
11070 HASH(l);
11071 break;
11072 }
11073 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011074 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11075 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011076
Guido van Rossumc2504932007-09-18 19:42:40 +000011077 if (x == -1)
11078 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011080 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011084PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011087Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
11089static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011092 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011093 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011094 Py_ssize_t start;
11095 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
Jesus Ceaac451502011-04-20 17:09:23 +020011097 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11098 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011101 if (PyUnicode_READY(self) == -1)
11102 return NULL;
11103 if (PyUnicode_READY(substring) == -1)
11104 return NULL;
11105
Victor Stinner7931d9a2011-11-04 00:22:48 +010011106 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107
11108 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 if (result == -2)
11111 return NULL;
11112
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113 if (result < 0) {
11114 PyErr_SetString(PyExc_ValueError, "substring not found");
11115 return NULL;
11116 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011117
Christian Heimes217cfd12007-12-02 14:31:20 +000011118 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011119}
11120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011121PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011122 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011124Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011126
11127static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011128unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011130 Py_ssize_t i, length;
11131 int kind;
11132 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133 int cased;
11134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 if (PyUnicode_READY(self) == -1)
11136 return NULL;
11137 length = PyUnicode_GET_LENGTH(self);
11138 kind = PyUnicode_KIND(self);
11139 data = PyUnicode_DATA(self);
11140
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 if (length == 1)
11143 return PyBool_FromLong(
11144 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011146 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011148 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011149
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 for (i = 0; i < length; i++) {
11152 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011153
Benjamin Peterson29060642009-01-31 22:14:21 +000011154 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11155 return PyBool_FromLong(0);
11156 else if (!cased && Py_UNICODE_ISLOWER(ch))
11157 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011159 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160}
11161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011162PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011163 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011165Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011166at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167
11168static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011169unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 Py_ssize_t i, length;
11172 int kind;
11173 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174 int cased;
11175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 if (PyUnicode_READY(self) == -1)
11177 return NULL;
11178 length = PyUnicode_GET_LENGTH(self);
11179 kind = PyUnicode_KIND(self);
11180 data = PyUnicode_DATA(self);
11181
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (length == 1)
11184 return PyBool_FromLong(
11185 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011187 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011189 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011190
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 for (i = 0; i < length; i++) {
11193 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011194
Benjamin Peterson29060642009-01-31 22:14:21 +000011195 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11196 return PyBool_FromLong(0);
11197 else if (!cased && Py_UNICODE_ISUPPER(ch))
11198 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011200 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201}
11202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011203PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011206Return True if S is a titlecased string and there is at least one\n\
11207character in S, i.e. upper- and titlecase characters may only\n\
11208follow uncased characters and lowercase characters only cased ones.\n\
11209Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
11211static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011212unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 Py_ssize_t i, length;
11215 int kind;
11216 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 int cased, previous_is_cased;
11218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011219 if (PyUnicode_READY(self) == -1)
11220 return NULL;
11221 length = PyUnicode_GET_LENGTH(self);
11222 kind = PyUnicode_KIND(self);
11223 data = PyUnicode_DATA(self);
11224
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 if (length == 1) {
11227 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11228 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11229 (Py_UNICODE_ISUPPER(ch) != 0));
11230 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011232 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011233 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011234 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011235
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 cased = 0;
11237 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011238 for (i = 0; i < length; i++) {
11239 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011240
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11242 if (previous_is_cased)
11243 return PyBool_FromLong(0);
11244 previous_is_cased = 1;
11245 cased = 1;
11246 }
11247 else if (Py_UNICODE_ISLOWER(ch)) {
11248 if (!previous_is_cased)
11249 return PyBool_FromLong(0);
11250 previous_is_cased = 1;
11251 cased = 1;
11252 }
11253 else
11254 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011256 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257}
11258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011259PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011262Return True if all characters in S are whitespace\n\
11263and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
11265static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011266unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 Py_ssize_t i, length;
11269 int kind;
11270 void *data;
11271
11272 if (PyUnicode_READY(self) == -1)
11273 return NULL;
11274 length = PyUnicode_GET_LENGTH(self);
11275 kind = PyUnicode_KIND(self);
11276 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 if (length == 1)
11280 return PyBool_FromLong(
11281 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011283 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 for (i = 0; i < length; i++) {
11288 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011289 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011292 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293}
11294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011295PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011296 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011297\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011298Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011299and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011300
11301static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011302unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011303{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 Py_ssize_t i, length;
11305 int kind;
11306 void *data;
11307
11308 if (PyUnicode_READY(self) == -1)
11309 return NULL;
11310 length = PyUnicode_GET_LENGTH(self);
11311 kind = PyUnicode_KIND(self);
11312 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011314 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 if (length == 1)
11316 return PyBool_FromLong(
11317 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318
11319 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 for (i = 0; i < length; i++) {
11324 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011325 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011326 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011327 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328}
11329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011330PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011331 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011332\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011333Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011334and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335
11336static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011337unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011338{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 int kind;
11340 void *data;
11341 Py_ssize_t len, i;
11342
11343 if (PyUnicode_READY(self) == -1)
11344 return NULL;
11345
11346 kind = PyUnicode_KIND(self);
11347 data = PyUnicode_DATA(self);
11348 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011349
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011350 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 if (len == 1) {
11352 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11353 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11354 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011355
11356 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 for (i = 0; i < len; i++) {
11361 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011362 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011365 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366}
11367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011368PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011369 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011371Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011372False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373
11374static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011375unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 Py_ssize_t i, length;
11378 int kind;
11379 void *data;
11380
11381 if (PyUnicode_READY(self) == -1)
11382 return NULL;
11383 length = PyUnicode_GET_LENGTH(self);
11384 kind = PyUnicode_KIND(self);
11385 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388 if (length == 1)
11389 return PyBool_FromLong(
11390 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011392 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 for (i = 0; i < length; i++) {
11397 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011400 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401}
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011406Return True if all characters in S are digits\n\
11407and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
11409static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011410unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 Py_ssize_t i, length;
11413 int kind;
11414 void *data;
11415
11416 if (PyUnicode_READY(self) == -1)
11417 return NULL;
11418 length = PyUnicode_GET_LENGTH(self);
11419 kind = PyUnicode_KIND(self);
11420 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 if (length == 1) {
11424 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11425 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11426 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011428 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011430 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 for (i = 0; i < length; i++) {
11433 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011436 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437}
11438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011439PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011440 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011442Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011443False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
11445static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011446unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 Py_ssize_t i, length;
11449 int kind;
11450 void *data;
11451
11452 if (PyUnicode_READY(self) == -1)
11453 return NULL;
11454 length = PyUnicode_GET_LENGTH(self);
11455 kind = PyUnicode_KIND(self);
11456 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (length == 1)
11460 return PyBool_FromLong(
11461 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011463 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011465 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 for (i = 0; i < length; i++) {
11468 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011471 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472}
11473
Martin v. Löwis47383402007-08-15 07:32:56 +000011474int
11475PyUnicode_IsIdentifier(PyObject *self)
11476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 int kind;
11478 void *data;
11479 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011480 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 if (PyUnicode_READY(self) == -1) {
11483 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 }
11486
11487 /* Special case for empty strings */
11488 if (PyUnicode_GET_LENGTH(self) == 0)
11489 return 0;
11490 kind = PyUnicode_KIND(self);
11491 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011492
11493 /* PEP 3131 says that the first character must be in
11494 XID_Start and subsequent characters in XID_Continue,
11495 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011496 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011497 letters, digits, underscore). However, given the current
11498 definition of XID_Start and XID_Continue, it is sufficient
11499 to check just for these, except that _ must be allowed
11500 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011502 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011503 return 0;
11504
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011505 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011508 return 1;
11509}
11510
11511PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011513\n\
11514Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011515to the language definition.\n\
11516\n\
11517Use keyword.iskeyword() to test for reserved identifiers\n\
11518such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011519
11520static PyObject*
11521unicode_isidentifier(PyObject *self)
11522{
11523 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11524}
11525
Georg Brandl559e5d72008-06-11 18:37:52 +000011526PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011528\n\
11529Return True if all characters in S are considered\n\
11530printable in repr() or S is empty, False otherwise.");
11531
11532static PyObject*
11533unicode_isprintable(PyObject *self)
11534{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 Py_ssize_t i, length;
11536 int kind;
11537 void *data;
11538
11539 if (PyUnicode_READY(self) == -1)
11540 return NULL;
11541 length = PyUnicode_GET_LENGTH(self);
11542 kind = PyUnicode_KIND(self);
11543 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011544
11545 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011546 if (length == 1)
11547 return PyBool_FromLong(
11548 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 for (i = 0; i < length; i++) {
11551 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011552 Py_RETURN_FALSE;
11553 }
11554 }
11555 Py_RETURN_TRUE;
11556}
11557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011558PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011559 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560\n\
11561Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011562iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563
11564static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011565unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011567 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568}
11569
Martin v. Löwis18e16552006-02-15 17:27:45 +000011570static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011571unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 if (PyUnicode_READY(self) == -1)
11574 return -1;
11575 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576}
11577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011578PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011581Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011582done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583
11584static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011585unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011587 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 Py_UCS4 fillchar = ' ';
11589
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011590 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591 return NULL;
11592
Benjamin Petersonbac79492012-01-14 13:34:47 -050011593 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011594 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
Victor Stinnerc4b49542011-12-11 22:44:26 +010011596 if (PyUnicode_GET_LENGTH(self) >= width)
11597 return unicode_result_unchanged(self);
11598
11599 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600}
11601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011602PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011603 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011605Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
11607static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011608unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011610 if (PyUnicode_READY(self) == -1)
11611 return NULL;
11612 if (PyUnicode_IS_ASCII(self))
11613 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011614 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615}
11616
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011617#define LEFTSTRIP 0
11618#define RIGHTSTRIP 1
11619#define BOTHSTRIP 2
11620
11621/* Arrays indexed by above */
11622static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11623
11624#define STRIPNAME(i) (stripformat[i]+3)
11625
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011626/* externally visible for str.strip(unicode) */
11627PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011628_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 void *data;
11631 int kind;
11632 Py_ssize_t i, j, len;
11633 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011634 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11637 return NULL;
11638
11639 kind = PyUnicode_KIND(self);
11640 data = PyUnicode_DATA(self);
11641 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011642 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11644 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011645 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011646
Benjamin Peterson14339b62009-01-31 16:36:08 +000011647 i = 0;
11648 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011649 while (i < len) {
11650 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11651 if (!BLOOM(sepmask, ch))
11652 break;
11653 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11654 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 i++;
11656 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011657 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011658
Benjamin Peterson14339b62009-01-31 16:36:08 +000011659 j = len;
11660 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011661 j--;
11662 while (j >= i) {
11663 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11664 if (!BLOOM(sepmask, ch))
11665 break;
11666 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11667 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011668 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011669 }
11670
Benjamin Peterson29060642009-01-31 22:14:21 +000011671 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011672 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011673
Victor Stinner7931d9a2011-11-04 00:22:48 +010011674 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675}
11676
11677PyObject*
11678PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11679{
11680 unsigned char *data;
11681 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011682 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683
Victor Stinnerde636f32011-10-01 03:55:54 +020011684 if (PyUnicode_READY(self) == -1)
11685 return NULL;
11686
Victor Stinner684d5fd2012-05-03 02:32:34 +020011687 length = PyUnicode_GET_LENGTH(self);
11688 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011689
Victor Stinner684d5fd2012-05-03 02:32:34 +020011690 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011691 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692
Victor Stinnerde636f32011-10-01 03:55:54 +020011693 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011694 PyErr_SetString(PyExc_IndexError, "string index out of range");
11695 return NULL;
11696 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011697 if (start >= length || end < start)
11698 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011699
Victor Stinner684d5fd2012-05-03 02:32:34 +020011700 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011701 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011702 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011703 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011704 }
11705 else {
11706 kind = PyUnicode_KIND(self);
11707 data = PyUnicode_1BYTE_DATA(self);
11708 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011709 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011710 length);
11711 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713
11714static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011715do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 Py_ssize_t len, i, j;
11718
11719 if (PyUnicode_READY(self) == -1)
11720 return NULL;
11721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011723
Victor Stinnercc7af722013-04-09 22:39:24 +020011724 if (PyUnicode_IS_ASCII(self)) {
11725 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
11726
11727 i = 0;
11728 if (striptype != RIGHTSTRIP) {
11729 while (i < len) {
11730 Py_UCS4 ch = data[i];
11731 if (!_Py_ascii_whitespace[ch])
11732 break;
11733 i++;
11734 }
11735 }
11736
11737 j = len;
11738 if (striptype != LEFTSTRIP) {
11739 j--;
11740 while (j >= i) {
11741 Py_UCS4 ch = data[j];
11742 if (!_Py_ascii_whitespace[ch])
11743 break;
11744 j--;
11745 }
11746 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011747 }
11748 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011749 else {
11750 int kind = PyUnicode_KIND(self);
11751 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011752
Victor Stinnercc7af722013-04-09 22:39:24 +020011753 i = 0;
11754 if (striptype != RIGHTSTRIP) {
11755 while (i < len) {
11756 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11757 if (!Py_UNICODE_ISSPACE(ch))
11758 break;
11759 i++;
11760 }
Victor Stinner9c79e412013-04-09 22:21:08 +020011761 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011762
11763 j = len;
11764 if (striptype != LEFTSTRIP) {
11765 j--;
11766 while (j >= i) {
11767 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11768 if (!Py_UNICODE_ISSPACE(ch))
11769 break;
11770 j--;
11771 }
11772 j++;
11773 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011774 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775
Victor Stinner7931d9a2011-11-04 00:22:48 +010011776 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777}
11778
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011779
11780static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011781do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011782{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011783 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
Benjamin Peterson14339b62009-01-31 16:36:08 +000011785 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11786 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787
Benjamin Peterson14339b62009-01-31 16:36:08 +000011788 if (sep != NULL && sep != Py_None) {
11789 if (PyUnicode_Check(sep))
11790 return _PyUnicode_XStrip(self, striptype, sep);
11791 else {
11792 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011793 "%s arg must be None or str",
11794 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011795 return NULL;
11796 }
11797 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011798
Benjamin Peterson14339b62009-01-31 16:36:08 +000011799 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011800}
11801
11802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011803PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011804 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011805\n\
11806Return a copy of the string S with leading and trailing\n\
11807whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011808If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011809
11810static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011811unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011812{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011813 if (PyTuple_GET_SIZE(args) == 0)
11814 return do_strip(self, BOTHSTRIP); /* Common case */
11815 else
11816 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011817}
11818
11819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011820PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011821 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011822\n\
11823Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011824If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011825
11826static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011827unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011828{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011829 if (PyTuple_GET_SIZE(args) == 0)
11830 return do_strip(self, LEFTSTRIP); /* Common case */
11831 else
11832 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011833}
11834
11835
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011836PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011837 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011838\n\
11839Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011840If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841
11842static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011843unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011844{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011845 if (PyTuple_GET_SIZE(args) == 0)
11846 return do_strip(self, RIGHTSTRIP); /* Common case */
11847 else
11848 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011849}
11850
11851
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011853unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011855 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857
Serhiy Storchaka05997252013-01-26 12:14:02 +020011858 if (len < 1)
11859 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860
Victor Stinnerc4b49542011-12-11 22:44:26 +010011861 /* no repeat, return original string */
11862 if (len == 1)
11863 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011864
Benjamin Petersonbac79492012-01-14 13:34:47 -050011865 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 return NULL;
11867
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011868 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011869 PyErr_SetString(PyExc_OverflowError,
11870 "repeated string is too long");
11871 return NULL;
11872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011874
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011875 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876 if (!u)
11877 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011878 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 if (PyUnicode_GET_LENGTH(str) == 1) {
11881 const int kind = PyUnicode_KIND(str);
11882 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011883 if (kind == PyUnicode_1BYTE_KIND) {
11884 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011885 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011886 }
11887 else if (kind == PyUnicode_2BYTE_KIND) {
11888 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011889 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011890 ucs2[n] = fill_char;
11891 } else {
11892 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11893 assert(kind == PyUnicode_4BYTE_KIND);
11894 for (n = 0; n < len; ++n)
11895 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 }
11898 else {
11899 /* number of characters copied this far */
11900 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011901 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 char *to = (char *) PyUnicode_DATA(u);
11903 Py_MEMCPY(to, PyUnicode_DATA(str),
11904 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 n = (done <= nchars-done) ? done : nchars-done;
11907 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011908 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011909 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910 }
11911
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011912 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011913 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914}
11915
Alexander Belopolsky40018472011-02-26 01:02:56 +000011916PyObject *
11917PyUnicode_Replace(PyObject *obj,
11918 PyObject *subobj,
11919 PyObject *replobj,
11920 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921{
11922 PyObject *self;
11923 PyObject *str1;
11924 PyObject *str2;
11925 PyObject *result;
11926
11927 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011928 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011929 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011931 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 Py_DECREF(self);
11933 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934 }
11935 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011936 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 Py_DECREF(self);
11938 Py_DECREF(str1);
11939 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011941 if (PyUnicode_READY(self) == -1 ||
11942 PyUnicode_READY(str1) == -1 ||
11943 PyUnicode_READY(str2) == -1)
11944 result = NULL;
11945 else
11946 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 Py_DECREF(self);
11948 Py_DECREF(str1);
11949 Py_DECREF(str2);
11950 return result;
11951}
11952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011953PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011954 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955\n\
11956Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011957old replaced by new. If the optional argument count is\n\
11958given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
11960static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 PyObject *str1;
11964 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011965 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966 PyObject *result;
11967
Martin v. Löwis18e16552006-02-15 17:27:45 +000011968 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011970 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011973 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011974 return NULL;
11975 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011976 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011977 Py_DECREF(str1);
11978 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011979 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011980 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11981 result = NULL;
11982 else
11983 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011984
11985 Py_DECREF(str1);
11986 Py_DECREF(str2);
11987 return result;
11988}
11989
Alexander Belopolsky40018472011-02-26 01:02:56 +000011990static PyObject *
11991unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011993 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 Py_ssize_t isize;
11995 Py_ssize_t osize, squote, dquote, i, o;
11996 Py_UCS4 max, quote;
11997 int ikind, okind;
11998 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012001 return NULL;
12002
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012003 isize = PyUnicode_GET_LENGTH(unicode);
12004 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 /* Compute length of output, quote characters, and
12007 maximum character */
12008 osize = 2; /* quotes */
12009 max = 127;
12010 squote = dquote = 0;
12011 ikind = PyUnicode_KIND(unicode);
12012 for (i = 0; i < isize; i++) {
12013 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12014 switch (ch) {
12015 case '\'': squote++; osize++; break;
12016 case '"': dquote++; osize++; break;
12017 case '\\': case '\t': case '\r': case '\n':
12018 osize += 2; break;
12019 default:
12020 /* Fast-path ASCII */
12021 if (ch < ' ' || ch == 0x7f)
12022 osize += 4; /* \xHH */
12023 else if (ch < 0x7f)
12024 osize++;
12025 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12026 osize++;
12027 max = ch > max ? ch : max;
12028 }
12029 else if (ch < 0x100)
12030 osize += 4; /* \xHH */
12031 else if (ch < 0x10000)
12032 osize += 6; /* \uHHHH */
12033 else
12034 osize += 10; /* \uHHHHHHHH */
12035 }
12036 }
12037
12038 quote = '\'';
12039 if (squote) {
12040 if (dquote)
12041 /* Both squote and dquote present. Use squote,
12042 and escape them */
12043 osize += squote;
12044 else
12045 quote = '"';
12046 }
12047
12048 repr = PyUnicode_New(osize, max);
12049 if (repr == NULL)
12050 return NULL;
12051 okind = PyUnicode_KIND(repr);
12052 odata = PyUnicode_DATA(repr);
12053
12054 PyUnicode_WRITE(okind, odata, 0, quote);
12055 PyUnicode_WRITE(okind, odata, osize-1, quote);
12056
12057 for (i = 0, o = 1; i < isize; i++) {
12058 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012059
12060 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 if ((ch == quote) || (ch == '\\')) {
12062 PyUnicode_WRITE(okind, odata, o++, '\\');
12063 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012064 continue;
12065 }
12066
Benjamin Peterson29060642009-01-31 22:14:21 +000012067 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012068 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 PyUnicode_WRITE(okind, odata, o++, '\\');
12070 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012071 }
12072 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 PyUnicode_WRITE(okind, odata, o++, '\\');
12074 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012075 }
12076 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 PyUnicode_WRITE(okind, odata, o++, '\\');
12078 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012079 }
12080
12081 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012082 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 PyUnicode_WRITE(okind, odata, o++, '\\');
12084 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012085 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12086 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012087 }
12088
Georg Brandl559e5d72008-06-11 18:37:52 +000012089 /* Copy ASCII characters as-is */
12090 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012092 }
12093
Benjamin Peterson29060642009-01-31 22:14:21 +000012094 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012095 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012096 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012097 (categories Z* and C* except ASCII space)
12098 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012100 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012101 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012104 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12105 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012106 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012107 /* Map 16-bit characters to '\uxxxx' */
12108 else if (ch <= 0xffff) {
12109 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012110 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12111 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12112 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012114 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012115 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012116 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012117 PyUnicode_WRITE(okind, odata, o++, 'U');
12118 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12119 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12120 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12121 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012122 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12123 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12124 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12125 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012126 }
12127 }
12128 /* Copy characters as-is */
12129 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012131 }
12132 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012135 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012136 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137}
12138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012139PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012140 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141\n\
12142Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012143such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144arguments start and end are interpreted as in slice notation.\n\
12145\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012146Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147
12148static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012151 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012152 Py_ssize_t start;
12153 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012154 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155
Jesus Ceaac451502011-04-20 17:09:23 +020012156 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12157 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 if (PyUnicode_READY(self) == -1)
12161 return NULL;
12162 if (PyUnicode_READY(substring) == -1)
12163 return NULL;
12164
Victor Stinner7931d9a2011-11-04 00:22:48 +010012165 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166
12167 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 if (result == -2)
12170 return NULL;
12171
Christian Heimes217cfd12007-12-02 14:31:20 +000012172 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173}
12174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012175PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012176 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012178Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
12180static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012181unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012183 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012184 Py_ssize_t start;
12185 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012186 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
Jesus Ceaac451502011-04-20 17:09:23 +020012188 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12189 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012190 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012192 if (PyUnicode_READY(self) == -1)
12193 return NULL;
12194 if (PyUnicode_READY(substring) == -1)
12195 return NULL;
12196
Victor Stinner7931d9a2011-11-04 00:22:48 +010012197 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198
12199 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 if (result == -2)
12202 return NULL;
12203
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204 if (result < 0) {
12205 PyErr_SetString(PyExc_ValueError, "substring not found");
12206 return NULL;
12207 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208
Christian Heimes217cfd12007-12-02 14:31:20 +000012209 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210}
12211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012212PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012213 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012215Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012216done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217
12218static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012219unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012221 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 Py_UCS4 fillchar = ' ';
12223
Victor Stinnere9a29352011-10-01 02:14:59 +020012224 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012226
Benjamin Petersonbac79492012-01-14 13:34:47 -050012227 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228 return NULL;
12229
Victor Stinnerc4b49542011-12-11 22:44:26 +010012230 if (PyUnicode_GET_LENGTH(self) >= width)
12231 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232
Victor Stinnerc4b49542011-12-11 22:44:26 +010012233 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234}
12235
Alexander Belopolsky40018472011-02-26 01:02:56 +000012236PyObject *
12237PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238{
12239 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012240
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241 s = PyUnicode_FromObject(s);
12242 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012243 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 if (sep != NULL) {
12245 sep = PyUnicode_FromObject(sep);
12246 if (sep == NULL) {
12247 Py_DECREF(s);
12248 return NULL;
12249 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250 }
12251
Victor Stinner9310abb2011-10-05 00:59:23 +020012252 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253
12254 Py_DECREF(s);
12255 Py_XDECREF(sep);
12256 return result;
12257}
12258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012259PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012260 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261\n\
12262Return a list of the words in S, using sep as the\n\
12263delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012264splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012265whitespace string is a separator and empty strings are\n\
12266removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267
12268static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012269unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012271 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012273 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012275 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12276 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277 return NULL;
12278
12279 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012280 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012282 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012284 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285}
12286
Thomas Wouters477c8d52006-05-27 19:21:47 +000012287PyObject *
12288PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12289{
12290 PyObject* str_obj;
12291 PyObject* sep_obj;
12292 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 int kind1, kind2, kind;
12294 void *buf1 = NULL, *buf2 = NULL;
12295 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012296
12297 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012298 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012299 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012300 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012301 if (!sep_obj) {
12302 Py_DECREF(str_obj);
12303 return NULL;
12304 }
12305 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12306 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012307 Py_DECREF(str_obj);
12308 return NULL;
12309 }
12310
Victor Stinner14f8f022011-10-05 20:58:25 +020012311 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012313 kind = Py_MAX(kind1, kind2);
12314 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012316 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 if (!buf1)
12318 goto onError;
12319 buf2 = PyUnicode_DATA(sep_obj);
12320 if (kind2 != kind)
12321 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12322 if (!buf2)
12323 goto onError;
12324 len1 = PyUnicode_GET_LENGTH(str_obj);
12325 len2 = PyUnicode_GET_LENGTH(sep_obj);
12326
Benjamin Petersonead6b532011-12-20 17:23:42 -060012327 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012329 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12330 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12331 else
12332 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 break;
12334 case PyUnicode_2BYTE_KIND:
12335 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12336 break;
12337 case PyUnicode_4BYTE_KIND:
12338 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12339 break;
12340 default:
12341 assert(0);
12342 out = 0;
12343 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012344
12345 Py_DECREF(sep_obj);
12346 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 if (kind1 != kind)
12348 PyMem_Free(buf1);
12349 if (kind2 != kind)
12350 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012351
12352 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 onError:
12354 Py_DECREF(sep_obj);
12355 Py_DECREF(str_obj);
12356 if (kind1 != kind && buf1)
12357 PyMem_Free(buf1);
12358 if (kind2 != kind && buf2)
12359 PyMem_Free(buf2);
12360 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012361}
12362
12363
12364PyObject *
12365PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12366{
12367 PyObject* str_obj;
12368 PyObject* sep_obj;
12369 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 int kind1, kind2, kind;
12371 void *buf1 = NULL, *buf2 = NULL;
12372 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373
12374 str_obj = PyUnicode_FromObject(str_in);
12375 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012377 sep_obj = PyUnicode_FromObject(sep_in);
12378 if (!sep_obj) {
12379 Py_DECREF(str_obj);
12380 return NULL;
12381 }
12382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012383 kind1 = PyUnicode_KIND(str_in);
12384 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012385 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386 buf1 = PyUnicode_DATA(str_in);
12387 if (kind1 != kind)
12388 buf1 = _PyUnicode_AsKind(str_in, kind);
12389 if (!buf1)
12390 goto onError;
12391 buf2 = PyUnicode_DATA(sep_obj);
12392 if (kind2 != kind)
12393 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12394 if (!buf2)
12395 goto onError;
12396 len1 = PyUnicode_GET_LENGTH(str_obj);
12397 len2 = PyUnicode_GET_LENGTH(sep_obj);
12398
Benjamin Petersonead6b532011-12-20 17:23:42 -060012399 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012401 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12402 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12403 else
12404 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 break;
12406 case PyUnicode_2BYTE_KIND:
12407 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12408 break;
12409 case PyUnicode_4BYTE_KIND:
12410 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12411 break;
12412 default:
12413 assert(0);
12414 out = 0;
12415 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012416
12417 Py_DECREF(sep_obj);
12418 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 if (kind1 != kind)
12420 PyMem_Free(buf1);
12421 if (kind2 != kind)
12422 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423
12424 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 onError:
12426 Py_DECREF(sep_obj);
12427 Py_DECREF(str_obj);
12428 if (kind1 != kind && buf1)
12429 PyMem_Free(buf1);
12430 if (kind2 != kind && buf2)
12431 PyMem_Free(buf2);
12432 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012433}
12434
12435PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012436 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012437\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012438Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012439the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012440found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012441
12442static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012443unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012444{
Victor Stinner9310abb2011-10-05 00:59:23 +020012445 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012446}
12447
12448PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012449 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012451Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012452the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012453separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454
12455static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012456unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012457{
Victor Stinner9310abb2011-10-05 00:59:23 +020012458 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012459}
12460
Alexander Belopolsky40018472011-02-26 01:02:56 +000012461PyObject *
12462PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012463{
12464 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012465
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012466 s = PyUnicode_FromObject(s);
12467 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012468 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012469 if (sep != NULL) {
12470 sep = PyUnicode_FromObject(sep);
12471 if (sep == NULL) {
12472 Py_DECREF(s);
12473 return NULL;
12474 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012475 }
12476
Victor Stinner9310abb2011-10-05 00:59:23 +020012477 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012478
12479 Py_DECREF(s);
12480 Py_XDECREF(sep);
12481 return result;
12482}
12483
12484PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012485 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012486\n\
12487Return a list of the words in S, using sep as the\n\
12488delimiter string, starting at the end of the string and\n\
12489working to the front. If maxsplit is given, at most maxsplit\n\
12490splits are done. If sep is not specified, any whitespace string\n\
12491is a separator.");
12492
12493static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012494unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012495{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012496 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012497 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012498 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012499
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012500 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12501 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012502 return NULL;
12503
12504 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012505 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012506 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012507 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012508 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012509 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012510}
12511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012512PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012513 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514\n\
12515Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012516Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012517is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518
12519static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012520unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012522 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012523 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012525 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12526 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527 return NULL;
12528
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012529 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530}
12531
12532static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012533PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012535 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536}
12537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012538PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012539 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540\n\
12541Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012542and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543
12544static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012545unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012547 if (PyUnicode_READY(self) == -1)
12548 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012549 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012550}
12551
Georg Brandlceee0772007-11-27 23:48:05 +000012552PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012553 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012554\n\
12555Return a translation table usable for str.translate().\n\
12556If there is only one argument, it must be a dictionary mapping Unicode\n\
12557ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012558Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012559If there are two arguments, they must be strings of equal length, and\n\
12560in the resulting dictionary, each character in x will be mapped to the\n\
12561character at the same position in y. If there is a third argument, it\n\
12562must be a string, whose characters will be mapped to None in the result.");
12563
12564static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012565unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012566{
12567 PyObject *x, *y = NULL, *z = NULL;
12568 PyObject *new = NULL, *key, *value;
12569 Py_ssize_t i = 0;
12570 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012571
Georg Brandlceee0772007-11-27 23:48:05 +000012572 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12573 return NULL;
12574 new = PyDict_New();
12575 if (!new)
12576 return NULL;
12577 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 int x_kind, y_kind, z_kind;
12579 void *x_data, *y_data, *z_data;
12580
Georg Brandlceee0772007-11-27 23:48:05 +000012581 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012582 if (!PyUnicode_Check(x)) {
12583 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12584 "be a string if there is a second argument");
12585 goto err;
12586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012588 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12589 "arguments must have equal length");
12590 goto err;
12591 }
12592 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 x_kind = PyUnicode_KIND(x);
12594 y_kind = PyUnicode_KIND(y);
12595 x_data = PyUnicode_DATA(x);
12596 y_data = PyUnicode_DATA(y);
12597 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12598 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012599 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012600 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012601 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012602 if (!value) {
12603 Py_DECREF(key);
12604 goto err;
12605 }
Georg Brandlceee0772007-11-27 23:48:05 +000012606 res = PyDict_SetItem(new, key, value);
12607 Py_DECREF(key);
12608 Py_DECREF(value);
12609 if (res < 0)
12610 goto err;
12611 }
12612 /* create entries for deleting chars in z */
12613 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012614 z_kind = PyUnicode_KIND(z);
12615 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012616 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012618 if (!key)
12619 goto err;
12620 res = PyDict_SetItem(new, key, Py_None);
12621 Py_DECREF(key);
12622 if (res < 0)
12623 goto err;
12624 }
12625 }
12626 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012627 int kind;
12628 void *data;
12629
Georg Brandlceee0772007-11-27 23:48:05 +000012630 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012631 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012632 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12633 "to maketrans it must be a dict");
12634 goto err;
12635 }
12636 /* copy entries into the new dict, converting string keys to int keys */
12637 while (PyDict_Next(x, &i, &key, &value)) {
12638 if (PyUnicode_Check(key)) {
12639 /* convert string keys to integer keys */
12640 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012641 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012642 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12643 "table must be of length 1");
12644 goto err;
12645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646 kind = PyUnicode_KIND(key);
12647 data = PyUnicode_DATA(key);
12648 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012649 if (!newkey)
12650 goto err;
12651 res = PyDict_SetItem(new, newkey, value);
12652 Py_DECREF(newkey);
12653 if (res < 0)
12654 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012655 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012656 /* just keep integer keys */
12657 if (PyDict_SetItem(new, key, value) < 0)
12658 goto err;
12659 } else {
12660 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12661 "be strings or integers");
12662 goto err;
12663 }
12664 }
12665 }
12666 return new;
12667 err:
12668 Py_DECREF(new);
12669 return NULL;
12670}
12671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012672PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012673 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674\n\
12675Return a copy of the string S, where all characters have been mapped\n\
12676through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012677Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012678Unmapped characters are left untouched. Characters mapped to None\n\
12679are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680
12681static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685}
12686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012687PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012688 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012690Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691
12692static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012693unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012695 if (PyUnicode_READY(self) == -1)
12696 return NULL;
12697 if (PyUnicode_IS_ASCII(self))
12698 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012699 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700}
12701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012702PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012703 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012705Pad a numeric string S with zeros on the left, to fill a field\n\
12706of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707
12708static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012709unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012711 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012712 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012713 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012714 int kind;
12715 void *data;
12716 Py_UCS4 chr;
12717
Martin v. Löwis18e16552006-02-15 17:27:45 +000012718 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719 return NULL;
12720
Benjamin Petersonbac79492012-01-14 13:34:47 -050012721 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012722 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723
Victor Stinnerc4b49542011-12-11 22:44:26 +010012724 if (PyUnicode_GET_LENGTH(self) >= width)
12725 return unicode_result_unchanged(self);
12726
12727 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728
12729 u = pad(self, fill, 0, '0');
12730
Walter Dörwald068325e2002-04-15 13:36:47 +000012731 if (u == NULL)
12732 return NULL;
12733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012734 kind = PyUnicode_KIND(u);
12735 data = PyUnicode_DATA(u);
12736 chr = PyUnicode_READ(kind, data, fill);
12737
12738 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 PyUnicode_WRITE(kind, data, 0, chr);
12741 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742 }
12743
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012744 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012745 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012746}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747
12748#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012749static PyObject *
12750unicode__decimal2ascii(PyObject *self)
12751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012752 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012753}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754#endif
12755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012756PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012759Return True if S starts with the specified prefix, False otherwise.\n\
12760With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012761With optional end, stop comparing S at that position.\n\
12762prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763
12764static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012765unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012768 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012769 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012770 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012771 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012772 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773
Jesus Ceaac451502011-04-20 17:09:23 +020012774 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012775 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 if (PyTuple_Check(subobj)) {
12777 Py_ssize_t i;
12778 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012779 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012780 if (substring == NULL)
12781 return NULL;
12782 result = tailmatch(self, substring, start, end, -1);
12783 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012784 if (result == -1)
12785 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012786 if (result) {
12787 Py_RETURN_TRUE;
12788 }
12789 }
12790 /* nothing matched */
12791 Py_RETURN_FALSE;
12792 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012793 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012794 if (substring == NULL) {
12795 if (PyErr_ExceptionMatches(PyExc_TypeError))
12796 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12797 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012798 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012799 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012800 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012802 if (result == -1)
12803 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012804 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805}
12806
12807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012808PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012811Return True if S ends with the specified suffix, False otherwise.\n\
12812With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012813With optional end, stop comparing S at that position.\n\
12814suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815
12816static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012817unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012818 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012820 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012821 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012822 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012823 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012824 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825
Jesus Ceaac451502011-04-20 17:09:23 +020012826 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012828 if (PyTuple_Check(subobj)) {
12829 Py_ssize_t i;
12830 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012831 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012832 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012833 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012834 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012835 result = tailmatch(self, substring, start, end, +1);
12836 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012837 if (result == -1)
12838 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012839 if (result) {
12840 Py_RETURN_TRUE;
12841 }
12842 }
12843 Py_RETURN_FALSE;
12844 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012845 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012846 if (substring == NULL) {
12847 if (PyErr_ExceptionMatches(PyExc_TypeError))
12848 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12849 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012850 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012851 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012852 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010012853 if (result == -1)
12854 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012856 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012857}
12858
Victor Stinner202fdca2012-05-07 12:47:02 +020012859Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012860_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012861{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012862 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012863 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12864 writer->data = PyUnicode_DATA(writer->buffer);
12865 writer->kind = PyUnicode_KIND(writer->buffer);
12866}
12867
Victor Stinnerd3f08822012-05-29 12:57:52 +020012868void
12869_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012870{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012871 memset(writer, 0, sizeof(*writer));
12872#ifdef Py_DEBUG
12873 writer->kind = 5; /* invalid kind */
12874#endif
12875 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012876 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012877}
12878
Victor Stinnerd3f08822012-05-29 12:57:52 +020012879int
12880_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12881 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012882{
12883 Py_ssize_t newlen;
12884 PyObject *newbuffer;
12885
Victor Stinnerd3f08822012-05-29 12:57:52 +020012886 assert(length > 0);
12887
Victor Stinner202fdca2012-05-07 12:47:02 +020012888 if (length > PY_SSIZE_T_MAX - writer->pos) {
12889 PyErr_NoMemory();
12890 return -1;
12891 }
12892 newlen = writer->pos + length;
12893
Victor Stinnerd3f08822012-05-29 12:57:52 +020012894 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012895 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012896 /* overallocate 25% to limit the number of resize */
12897 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12898 newlen += newlen / 4;
12899 if (newlen < writer->min_length)
12900 newlen = writer->min_length;
12901 }
12902 writer->buffer = PyUnicode_New(newlen, maxchar);
12903 if (writer->buffer == NULL)
12904 return -1;
12905 _PyUnicodeWriter_Update(writer);
12906 return 0;
12907 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012908
Victor Stinnerd3f08822012-05-29 12:57:52 +020012909 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012910 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012911 /* overallocate 25% to limit the number of resize */
12912 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12913 newlen += newlen / 4;
12914 if (newlen < writer->min_length)
12915 newlen = writer->min_length;
12916 }
12917
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012918 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012919 /* resize + widen */
12920 newbuffer = PyUnicode_New(newlen, maxchar);
12921 if (newbuffer == NULL)
12922 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012923 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12924 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012925 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012926 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012927 }
12928 else {
12929 newbuffer = resize_compact(writer->buffer, newlen);
12930 if (newbuffer == NULL)
12931 return -1;
12932 }
12933 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012934 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012935 }
12936 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012937 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012938 newbuffer = PyUnicode_New(writer->size, maxchar);
12939 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012940 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012941 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12942 writer->buffer, 0, writer->pos);
12943 Py_DECREF(writer->buffer);
12944 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012945 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012946 }
12947 return 0;
12948}
12949
Victor Stinnerd3f08822012-05-29 12:57:52 +020012950int
12951_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12952{
12953 Py_UCS4 maxchar;
12954 Py_ssize_t len;
12955
12956 if (PyUnicode_READY(str) == -1)
12957 return -1;
12958 len = PyUnicode_GET_LENGTH(str);
12959 if (len == 0)
12960 return 0;
12961 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12962 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012963 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012964 Py_INCREF(str);
12965 writer->buffer = str;
12966 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012967 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012968 writer->size = 0;
12969 writer->pos += len;
12970 return 0;
12971 }
12972 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12973 return -1;
12974 }
12975 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12976 str, 0, len);
12977 writer->pos += len;
12978 return 0;
12979}
12980
Victor Stinnere215d962012-10-06 23:03:36 +020012981int
Victor Stinnercfc4c132013-04-03 01:48:39 +020012982_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
12983 Py_ssize_t start, Py_ssize_t end)
12984{
12985 Py_UCS4 maxchar;
12986 Py_ssize_t len;
12987
12988 if (PyUnicode_READY(str) == -1)
12989 return -1;
12990
12991 assert(0 <= start);
12992 assert(end <= PyUnicode_GET_LENGTH(str));
12993 assert(start <= end);
12994
12995 if (end == 0)
12996 return 0;
12997
12998 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
12999 return _PyUnicodeWriter_WriteStr(writer, str);
13000
13001 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13002 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13003 else
13004 maxchar = writer->maxchar;
13005 len = end - start;
13006
13007 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13008 return -1;
13009
13010 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13011 str, start, len);
13012 writer->pos += len;
13013 return 0;
13014}
13015
13016int
Victor Stinnere215d962012-10-06 23:03:36 +020013017_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
13018{
13019 Py_UCS4 maxchar;
13020
13021 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13022 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13023 return -1;
13024 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13025 writer->pos += len;
13026 return 0;
13027}
13028
Victor Stinnerd3f08822012-05-29 12:57:52 +020013029PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013030_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013031{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013032 if (writer->pos == 0) {
13033 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013034 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013035 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013036 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013037 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
13038 return writer->buffer;
13039 }
13040 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13041 PyObject *newbuffer;
13042 newbuffer = resize_compact(writer->buffer, writer->pos);
13043 if (newbuffer == NULL) {
13044 Py_DECREF(writer->buffer);
13045 return NULL;
13046 }
13047 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013048 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020013049 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner2cb16aa2013-03-06 19:28:37 +010013050 return unicode_result_ready(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013051}
13052
Victor Stinnerd3f08822012-05-29 12:57:52 +020013053void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013054_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013055{
13056 Py_CLEAR(writer->buffer);
13057}
13058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013059#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013060
13061PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013062 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013063\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013064Return a formatted version of S, using substitutions from args and kwargs.\n\
13065The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013066
Eric Smith27bbca62010-11-04 17:06:58 +000013067PyDoc_STRVAR(format_map__doc__,
13068 "S.format_map(mapping) -> str\n\
13069\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013070Return a formatted version of S, using substitutions from mapping.\n\
13071The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013072
Eric Smith4a7d76d2008-05-30 18:10:19 +000013073static PyObject *
13074unicode__format__(PyObject* self, PyObject* args)
13075{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013076 PyObject *format_spec;
13077 _PyUnicodeWriter writer;
13078 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013079
13080 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13081 return NULL;
13082
Victor Stinnerd3f08822012-05-29 12:57:52 +020013083 if (PyUnicode_READY(self) == -1)
13084 return NULL;
13085 _PyUnicodeWriter_Init(&writer, 0);
13086 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13087 self, format_spec, 0,
13088 PyUnicode_GET_LENGTH(format_spec));
13089 if (ret == -1) {
13090 _PyUnicodeWriter_Dealloc(&writer);
13091 return NULL;
13092 }
13093 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013094}
13095
Eric Smith8c663262007-08-25 02:26:07 +000013096PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013097 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013098\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013099Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013100
13101static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013102unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013103{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 Py_ssize_t size;
13105
13106 /* If it's a compact object, account for base structure +
13107 character data. */
13108 if (PyUnicode_IS_COMPACT_ASCII(v))
13109 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13110 else if (PyUnicode_IS_COMPACT(v))
13111 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013112 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013113 else {
13114 /* If it is a two-block object, account for base object, and
13115 for character block if present. */
13116 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013117 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013119 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 }
13121 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013122 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013123 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013125 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013126 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127
13128 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013129}
13130
13131PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013132 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013133
13134static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013135unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013136{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013137 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013138 if (!copy)
13139 return NULL;
13140 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013141}
13142
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013144 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013145 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013146 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13147 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013148 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13149 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013150 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013151 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13152 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13153 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13154 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13155 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013156 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013157 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13158 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13159 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013160 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013161 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13162 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13163 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013164 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013165 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013166 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013167 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013168 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13169 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13170 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13171 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13172 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13173 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13174 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13175 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13176 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13177 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13178 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13179 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13180 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13181 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013182 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013183 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013184 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013185 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013186 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013187 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013188 {"maketrans", (PyCFunction) unicode_maketrans,
13189 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013190 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013191#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013192 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013193 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194#endif
13195
Benjamin Peterson14339b62009-01-31 16:36:08 +000013196 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197 {NULL, NULL}
13198};
13199
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013200static PyObject *
13201unicode_mod(PyObject *v, PyObject *w)
13202{
Brian Curtindfc80e32011-08-10 20:28:54 -050013203 if (!PyUnicode_Check(v))
13204 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013205 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013206}
13207
13208static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013209 0, /*nb_add*/
13210 0, /*nb_subtract*/
13211 0, /*nb_multiply*/
13212 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013213};
13214
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013216 (lenfunc) unicode_length, /* sq_length */
13217 PyUnicode_Concat, /* sq_concat */
13218 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13219 (ssizeargfunc) unicode_getitem, /* sq_item */
13220 0, /* sq_slice */
13221 0, /* sq_ass_item */
13222 0, /* sq_ass_slice */
13223 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224};
13225
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013226static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013227unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013228{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013229 if (PyUnicode_READY(self) == -1)
13230 return NULL;
13231
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013232 if (PyIndex_Check(item)) {
13233 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013234 if (i == -1 && PyErr_Occurred())
13235 return NULL;
13236 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013237 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013238 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013239 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013240 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013241 PyObject *result;
13242 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013243 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013244 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013246 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013247 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013248 return NULL;
13249 }
13250
13251 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013252 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013253 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013254 slicelength == PyUnicode_GET_LENGTH(self)) {
13255 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013256 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013257 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013258 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013259 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013260 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013261 src_kind = PyUnicode_KIND(self);
13262 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013263 if (!PyUnicode_IS_ASCII(self)) {
13264 kind_limit = kind_maxchar_limit(src_kind);
13265 max_char = 0;
13266 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13267 ch = PyUnicode_READ(src_kind, src_data, cur);
13268 if (ch > max_char) {
13269 max_char = ch;
13270 if (max_char >= kind_limit)
13271 break;
13272 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013273 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013274 }
Victor Stinner55c99112011-10-13 01:17:06 +020013275 else
13276 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013277 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013278 if (result == NULL)
13279 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013280 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013281 dest_data = PyUnicode_DATA(result);
13282
13283 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013284 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13285 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013286 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013287 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013288 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013289 } else {
13290 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13291 return NULL;
13292 }
13293}
13294
13295static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013296 (lenfunc)unicode_length, /* mp_length */
13297 (binaryfunc)unicode_subscript, /* mp_subscript */
13298 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013299};
13300
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302/* Helpers for PyUnicode_Format() */
13303
Victor Stinnera47082312012-10-04 02:19:54 +020013304struct unicode_formatter_t {
13305 PyObject *args;
13306 int args_owned;
13307 Py_ssize_t arglen, argidx;
13308 PyObject *dict;
13309
13310 enum PyUnicode_Kind fmtkind;
13311 Py_ssize_t fmtcnt, fmtpos;
13312 void *fmtdata;
13313 PyObject *fmtstr;
13314
13315 _PyUnicodeWriter writer;
13316};
13317
13318struct unicode_format_arg_t {
13319 Py_UCS4 ch;
13320 int flags;
13321 Py_ssize_t width;
13322 int prec;
13323 int sign;
13324};
13325
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013327unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013328{
Victor Stinnera47082312012-10-04 02:19:54 +020013329 Py_ssize_t argidx = ctx->argidx;
13330
13331 if (argidx < ctx->arglen) {
13332 ctx->argidx++;
13333 if (ctx->arglen < 0)
13334 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013335 else
Victor Stinnera47082312012-10-04 02:19:54 +020013336 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337 }
13338 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013339 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013340 return NULL;
13341}
13342
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013343/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013344
Victor Stinnera47082312012-10-04 02:19:54 +020013345/* Format a float into the writer if the writer is not NULL, or into *p_output
13346 otherwise.
13347
13348 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349static int
Victor Stinnera47082312012-10-04 02:19:54 +020013350formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13351 PyObject **p_output,
13352 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013354 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013356 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013357 int prec;
13358 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013359
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360 x = PyFloat_AsDouble(v);
13361 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013362 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013363
Victor Stinnera47082312012-10-04 02:19:54 +020013364 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013365 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013367
Victor Stinnera47082312012-10-04 02:19:54 +020013368 if (arg->flags & F_ALT)
13369 dtoa_flags = Py_DTSF_ALT;
13370 else
13371 dtoa_flags = 0;
13372 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013373 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013374 return -1;
13375 len = strlen(p);
13376 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013377 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13378 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013379 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013380 }
Victor Stinner184252a2012-06-16 02:57:41 +020013381 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013382 writer->pos += len;
13383 }
13384 else
13385 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013386 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013387 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388}
13389
Victor Stinnerd0880d52012-04-27 23:40:13 +020013390/* formatlong() emulates the format codes d, u, o, x and X, and
13391 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13392 * Python's regular ints.
13393 * Return value: a new PyUnicodeObject*, or NULL if error.
13394 * The output string is of the form
13395 * "-"? ("0x" | "0X")? digit+
13396 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13397 * set in flags. The case of hex digits will be correct,
13398 * There will be at least prec digits, zero-filled on the left if
13399 * necessary to get that many.
13400 * val object to be converted
13401 * flags bitmask of format flags; only F_ALT is looked at
13402 * prec minimum number of digits; 0-fill on left if needed
13403 * type a character in [duoxX]; u acts the same as d
13404 *
13405 * CAUTION: o, x and X conversions on regular ints can never
13406 * produce a '-' sign, but can for Python's unbounded ints.
13407 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013408static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013409formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013410{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013411 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013412 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013413 Py_ssize_t i;
13414 int sign; /* 1 if '-', else 0 */
13415 int len; /* number of characters */
13416 Py_ssize_t llen;
13417 int numdigits; /* len == numnondigits + numdigits */
13418 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013419 int prec = arg->prec;
13420 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013421
Victor Stinnerd0880d52012-04-27 23:40:13 +020013422 /* Avoid exceeding SSIZE_T_MAX */
13423 if (prec > INT_MAX-3) {
13424 PyErr_SetString(PyExc_OverflowError,
13425 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013426 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013427 }
13428
13429 assert(PyLong_Check(val));
13430
13431 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013432 default:
13433 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013434 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013435 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013436 case 'u':
13437 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013438 if (PyBool_Check(val))
13439 result = PyNumber_ToBase(val, 10);
13440 else
13441 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013442 break;
13443 case 'o':
13444 numnondigits = 2;
13445 result = PyNumber_ToBase(val, 8);
13446 break;
13447 case 'x':
13448 case 'X':
13449 numnondigits = 2;
13450 result = PyNumber_ToBase(val, 16);
13451 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013452 }
13453 if (!result)
13454 return NULL;
13455
13456 assert(unicode_modifiable(result));
13457 assert(PyUnicode_IS_READY(result));
13458 assert(PyUnicode_IS_ASCII(result));
13459
13460 /* To modify the string in-place, there can only be one reference. */
13461 if (Py_REFCNT(result) != 1) {
13462 PyErr_BadInternalCall();
13463 return NULL;
13464 }
13465 buf = PyUnicode_DATA(result);
13466 llen = PyUnicode_GET_LENGTH(result);
13467 if (llen > INT_MAX) {
13468 PyErr_SetString(PyExc_ValueError,
13469 "string too large in _PyBytes_FormatLong");
13470 return NULL;
13471 }
13472 len = (int)llen;
13473 sign = buf[0] == '-';
13474 numnondigits += sign;
13475 numdigits = len - numnondigits;
13476 assert(numdigits > 0);
13477
13478 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013479 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013480 (type == 'o' || type == 'x' || type == 'X'))) {
13481 assert(buf[sign] == '0');
13482 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13483 buf[sign+1] == 'o');
13484 numnondigits -= 2;
13485 buf += 2;
13486 len -= 2;
13487 if (sign)
13488 buf[0] = '-';
13489 assert(len == numnondigits + numdigits);
13490 assert(numdigits > 0);
13491 }
13492
13493 /* Fill with leading zeroes to meet minimum width. */
13494 if (prec > numdigits) {
13495 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13496 numnondigits + prec);
13497 char *b1;
13498 if (!r1) {
13499 Py_DECREF(result);
13500 return NULL;
13501 }
13502 b1 = PyBytes_AS_STRING(r1);
13503 for (i = 0; i < numnondigits; ++i)
13504 *b1++ = *buf++;
13505 for (i = 0; i < prec - numdigits; i++)
13506 *b1++ = '0';
13507 for (i = 0; i < numdigits; i++)
13508 *b1++ = *buf++;
13509 *b1 = '\0';
13510 Py_DECREF(result);
13511 result = r1;
13512 buf = PyBytes_AS_STRING(result);
13513 len = numnondigits + prec;
13514 }
13515
13516 /* Fix up case for hex conversions. */
13517 if (type == 'X') {
13518 /* Need to convert all lower case letters to upper case.
13519 and need to convert 0x to 0X (and -0x to -0X). */
13520 for (i = 0; i < len; i++)
13521 if (buf[i] >= 'a' && buf[i] <= 'x')
13522 buf[i] -= 'a'-'A';
13523 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013524 if (!PyUnicode_Check(result)
13525 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013526 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013527 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013528 Py_DECREF(result);
13529 result = unicode;
13530 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013531 else if (len != PyUnicode_GET_LENGTH(result)) {
13532 if (PyUnicode_Resize(&result, len) < 0)
13533 Py_CLEAR(result);
13534 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013535 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013536}
13537
Victor Stinner621ef3d2012-10-02 00:33:47 +020013538/* Format an integer.
13539 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013540 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013541 * -1 and raise an exception on error */
13542static int
Victor Stinnera47082312012-10-04 02:19:54 +020013543mainformatlong(PyObject *v,
13544 struct unicode_format_arg_t *arg,
13545 PyObject **p_output,
13546 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013547{
13548 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013549 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013550
13551 if (!PyNumber_Check(v))
13552 goto wrongtype;
13553
13554 if (!PyLong_Check(v)) {
13555 iobj = PyNumber_Long(v);
13556 if (iobj == NULL) {
13557 if (PyErr_ExceptionMatches(PyExc_TypeError))
13558 goto wrongtype;
13559 return -1;
13560 }
13561 assert(PyLong_Check(iobj));
13562 }
13563 else {
13564 iobj = v;
13565 Py_INCREF(iobj);
13566 }
13567
13568 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013569 && arg->width == -1 && arg->prec == -1
13570 && !(arg->flags & (F_SIGN | F_BLANK))
13571 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013572 {
13573 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013574 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013575 int base;
13576
Victor Stinnera47082312012-10-04 02:19:54 +020013577 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013578 {
13579 default:
13580 assert(0 && "'type' not in [diuoxX]");
13581 case 'd':
13582 case 'i':
13583 case 'u':
13584 base = 10;
13585 break;
13586 case 'o':
13587 base = 8;
13588 break;
13589 case 'x':
13590 case 'X':
13591 base = 16;
13592 break;
13593 }
13594
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013595 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13596 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013597 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013598 }
13599 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013600 return 1;
13601 }
13602
Victor Stinnera47082312012-10-04 02:19:54 +020013603 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013604 Py_DECREF(iobj);
13605 if (res == NULL)
13606 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013607 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013608 return 0;
13609
13610wrongtype:
13611 PyErr_Format(PyExc_TypeError,
13612 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013613 "not %.200s",
13614 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013615 return -1;
13616}
13617
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013618static Py_UCS4
13619formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013620{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013621 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013622 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013623 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013624 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013626 goto onError;
13627 }
13628 else {
13629 /* Integer input truncated to a character */
13630 long x;
13631 x = PyLong_AsLong(v);
13632 if (x == -1 && PyErr_Occurred())
13633 goto onError;
13634
Victor Stinner8faf8212011-12-08 22:14:11 +010013635 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013636 PyErr_SetString(PyExc_OverflowError,
13637 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013638 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013639 }
13640
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013641 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013642 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013643
Benjamin Peterson29060642009-01-31 22:14:21 +000013644 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013645 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013647 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013648}
13649
Victor Stinnera47082312012-10-04 02:19:54 +020013650/* Parse options of an argument: flags, width, precision.
13651 Handle also "%(name)" syntax.
13652
13653 Return 0 if the argument has been formatted into arg->str.
13654 Return 1 if the argument has been written into ctx->writer,
13655 Raise an exception and return -1 on error. */
13656static int
13657unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13658 struct unicode_format_arg_t *arg)
13659{
13660#define FORMAT_READ(ctx) \
13661 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13662
13663 PyObject *v;
13664
Victor Stinnera47082312012-10-04 02:19:54 +020013665 if (arg->ch == '(') {
13666 /* Get argument value from a dictionary. Example: "%(name)s". */
13667 Py_ssize_t keystart;
13668 Py_ssize_t keylen;
13669 PyObject *key;
13670 int pcount = 1;
13671
13672 if (ctx->dict == NULL) {
13673 PyErr_SetString(PyExc_TypeError,
13674 "format requires a mapping");
13675 return -1;
13676 }
13677 ++ctx->fmtpos;
13678 --ctx->fmtcnt;
13679 keystart = ctx->fmtpos;
13680 /* Skip over balanced parentheses */
13681 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13682 arg->ch = FORMAT_READ(ctx);
13683 if (arg->ch == ')')
13684 --pcount;
13685 else if (arg->ch == '(')
13686 ++pcount;
13687 ctx->fmtpos++;
13688 }
13689 keylen = ctx->fmtpos - keystart - 1;
13690 if (ctx->fmtcnt < 0 || pcount > 0) {
13691 PyErr_SetString(PyExc_ValueError,
13692 "incomplete format key");
13693 return -1;
13694 }
13695 key = PyUnicode_Substring(ctx->fmtstr,
13696 keystart, keystart + keylen);
13697 if (key == NULL)
13698 return -1;
13699 if (ctx->args_owned) {
13700 Py_DECREF(ctx->args);
13701 ctx->args_owned = 0;
13702 }
13703 ctx->args = PyObject_GetItem(ctx->dict, key);
13704 Py_DECREF(key);
13705 if (ctx->args == NULL)
13706 return -1;
13707 ctx->args_owned = 1;
13708 ctx->arglen = -1;
13709 ctx->argidx = -2;
13710 }
13711
13712 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020013713 while (--ctx->fmtcnt >= 0) {
13714 arg->ch = FORMAT_READ(ctx);
13715 ctx->fmtpos++;
13716 switch (arg->ch) {
13717 case '-': arg->flags |= F_LJUST; continue;
13718 case '+': arg->flags |= F_SIGN; continue;
13719 case ' ': arg->flags |= F_BLANK; continue;
13720 case '#': arg->flags |= F_ALT; continue;
13721 case '0': arg->flags |= F_ZERO; continue;
13722 }
13723 break;
13724 }
13725
13726 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020013727 if (arg->ch == '*') {
13728 v = unicode_format_getnextarg(ctx);
13729 if (v == NULL)
13730 return -1;
13731 if (!PyLong_Check(v)) {
13732 PyErr_SetString(PyExc_TypeError,
13733 "* wants int");
13734 return -1;
13735 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013736 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013737 if (arg->width == -1 && PyErr_Occurred())
13738 return -1;
13739 if (arg->width < 0) {
13740 arg->flags |= F_LJUST;
13741 arg->width = -arg->width;
13742 }
13743 if (--ctx->fmtcnt >= 0) {
13744 arg->ch = FORMAT_READ(ctx);
13745 ctx->fmtpos++;
13746 }
13747 }
13748 else if (arg->ch >= '0' && arg->ch <= '9') {
13749 arg->width = arg->ch - '0';
13750 while (--ctx->fmtcnt >= 0) {
13751 arg->ch = FORMAT_READ(ctx);
13752 ctx->fmtpos++;
13753 if (arg->ch < '0' || arg->ch > '9')
13754 break;
13755 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13756 mixing signed and unsigned comparison. Since arg->ch is between
13757 '0' and '9', casting to int is safe. */
13758 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13759 PyErr_SetString(PyExc_ValueError,
13760 "width too big");
13761 return -1;
13762 }
13763 arg->width = arg->width*10 + (arg->ch - '0');
13764 }
13765 }
13766
13767 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020013768 if (arg->ch == '.') {
13769 arg->prec = 0;
13770 if (--ctx->fmtcnt >= 0) {
13771 arg->ch = FORMAT_READ(ctx);
13772 ctx->fmtpos++;
13773 }
13774 if (arg->ch == '*') {
13775 v = unicode_format_getnextarg(ctx);
13776 if (v == NULL)
13777 return -1;
13778 if (!PyLong_Check(v)) {
13779 PyErr_SetString(PyExc_TypeError,
13780 "* wants int");
13781 return -1;
13782 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013783 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013784 if (arg->prec == -1 && PyErr_Occurred())
13785 return -1;
13786 if (arg->prec < 0)
13787 arg->prec = 0;
13788 if (--ctx->fmtcnt >= 0) {
13789 arg->ch = FORMAT_READ(ctx);
13790 ctx->fmtpos++;
13791 }
13792 }
13793 else if (arg->ch >= '0' && arg->ch <= '9') {
13794 arg->prec = arg->ch - '0';
13795 while (--ctx->fmtcnt >= 0) {
13796 arg->ch = FORMAT_READ(ctx);
13797 ctx->fmtpos++;
13798 if (arg->ch < '0' || arg->ch > '9')
13799 break;
13800 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13801 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013802 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013803 return -1;
13804 }
13805 arg->prec = arg->prec*10 + (arg->ch - '0');
13806 }
13807 }
13808 }
13809
13810 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13811 if (ctx->fmtcnt >= 0) {
13812 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13813 if (--ctx->fmtcnt >= 0) {
13814 arg->ch = FORMAT_READ(ctx);
13815 ctx->fmtpos++;
13816 }
13817 }
13818 }
13819 if (ctx->fmtcnt < 0) {
13820 PyErr_SetString(PyExc_ValueError,
13821 "incomplete format");
13822 return -1;
13823 }
13824 return 0;
13825
13826#undef FORMAT_READ
13827}
13828
13829/* Format one argument. Supported conversion specifiers:
13830
13831 - "s", "r", "a": any type
13832 - "i", "d", "u", "o", "x", "X": int
13833 - "e", "E", "f", "F", "g", "G": float
13834 - "c": int or str (1 character)
13835
Victor Stinner8dbd4212012-12-04 09:30:24 +010013836 When possible, the output is written directly into the Unicode writer
13837 (ctx->writer). A string is created when padding is required.
13838
Victor Stinnera47082312012-10-04 02:19:54 +020013839 Return 0 if the argument has been formatted into *p_str,
13840 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010013841 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020013842static int
13843unicode_format_arg_format(struct unicode_formatter_t *ctx,
13844 struct unicode_format_arg_t *arg,
13845 PyObject **p_str)
13846{
13847 PyObject *v;
13848 _PyUnicodeWriter *writer = &ctx->writer;
13849
13850 if (ctx->fmtcnt == 0)
13851 ctx->writer.overallocate = 0;
13852
13853 if (arg->ch == '%') {
13854 if (_PyUnicodeWriter_Prepare(writer, 1, '%') == -1)
13855 return -1;
13856 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '%');
13857 writer->pos += 1;
13858 return 1;
13859 }
13860
13861 v = unicode_format_getnextarg(ctx);
13862 if (v == NULL)
13863 return -1;
13864
Victor Stinnera47082312012-10-04 02:19:54 +020013865
13866 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020013867 case 's':
13868 case 'r':
13869 case 'a':
13870 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
13871 /* Fast path */
13872 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
13873 return -1;
13874 return 1;
13875 }
13876
13877 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
13878 *p_str = v;
13879 Py_INCREF(*p_str);
13880 }
13881 else {
13882 if (arg->ch == 's')
13883 *p_str = PyObject_Str(v);
13884 else if (arg->ch == 'r')
13885 *p_str = PyObject_Repr(v);
13886 else
13887 *p_str = PyObject_ASCII(v);
13888 }
13889 break;
13890
13891 case 'i':
13892 case 'd':
13893 case 'u':
13894 case 'o':
13895 case 'x':
13896 case 'X':
13897 {
13898 int ret = mainformatlong(v, arg, p_str, writer);
13899 if (ret != 0)
13900 return ret;
13901 arg->sign = 1;
13902 break;
13903 }
13904
13905 case 'e':
13906 case 'E':
13907 case 'f':
13908 case 'F':
13909 case 'g':
13910 case 'G':
13911 if (arg->width == -1 && arg->prec == -1
13912 && !(arg->flags & (F_SIGN | F_BLANK)))
13913 {
13914 /* Fast path */
13915 if (formatfloat(v, arg, NULL, writer) == -1)
13916 return -1;
13917 return 1;
13918 }
13919
13920 arg->sign = 1;
13921 if (formatfloat(v, arg, p_str, NULL) == -1)
13922 return -1;
13923 break;
13924
13925 case 'c':
13926 {
13927 Py_UCS4 ch = formatchar(v);
13928 if (ch == (Py_UCS4) -1)
13929 return -1;
13930 if (arg->width == -1 && arg->prec == -1) {
13931 /* Fast path */
13932 if (_PyUnicodeWriter_Prepare(writer, 1, ch) == -1)
13933 return -1;
13934 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13935 writer->pos += 1;
13936 return 1;
13937 }
13938 *p_str = PyUnicode_FromOrdinal(ch);
13939 break;
13940 }
13941
13942 default:
13943 PyErr_Format(PyExc_ValueError,
13944 "unsupported format character '%c' (0x%x) "
13945 "at index %zd",
13946 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
13947 (int)arg->ch,
13948 ctx->fmtpos - 1);
13949 return -1;
13950 }
13951 if (*p_str == NULL)
13952 return -1;
13953 assert (PyUnicode_Check(*p_str));
13954 return 0;
13955}
13956
13957static int
13958unicode_format_arg_output(struct unicode_formatter_t *ctx,
13959 struct unicode_format_arg_t *arg,
13960 PyObject *str)
13961{
13962 Py_ssize_t len;
13963 enum PyUnicode_Kind kind;
13964 void *pbuf;
13965 Py_ssize_t pindex;
13966 Py_UCS4 signchar;
13967 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020013968 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020013969 Py_ssize_t sublen;
13970 _PyUnicodeWriter *writer = &ctx->writer;
13971 Py_UCS4 fill;
13972
13973 fill = ' ';
13974 if (arg->sign && arg->flags & F_ZERO)
13975 fill = '0';
13976
13977 if (PyUnicode_READY(str) == -1)
13978 return -1;
13979
13980 len = PyUnicode_GET_LENGTH(str);
13981 if ((arg->width == -1 || arg->width <= len)
13982 && (arg->prec == -1 || arg->prec >= len)
13983 && !(arg->flags & (F_SIGN | F_BLANK)))
13984 {
13985 /* Fast path */
13986 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
13987 return -1;
13988 return 0;
13989 }
13990
13991 /* Truncate the string for "s", "r" and "a" formats
13992 if the precision is set */
13993 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
13994 if (arg->prec >= 0 && len > arg->prec)
13995 len = arg->prec;
13996 }
13997
13998 /* Adjust sign and width */
13999 kind = PyUnicode_KIND(str);
14000 pbuf = PyUnicode_DATA(str);
14001 pindex = 0;
14002 signchar = '\0';
14003 if (arg->sign) {
14004 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14005 if (ch == '-' || ch == '+') {
14006 signchar = ch;
14007 len--;
14008 pindex++;
14009 }
14010 else if (arg->flags & F_SIGN)
14011 signchar = '+';
14012 else if (arg->flags & F_BLANK)
14013 signchar = ' ';
14014 else
14015 arg->sign = 0;
14016 }
14017 if (arg->width < len)
14018 arg->width = len;
14019
14020 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014021 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014022 if (!(arg->flags & F_LJUST)) {
14023 if (arg->sign) {
14024 if ((arg->width-1) > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014025 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014026 }
14027 else {
14028 if (arg->width > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014029 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014030 }
14031 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014032 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14033 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
14034 maxchar = MAX_MAXCHAR(maxchar, strmaxchar);
14035 }
14036
Victor Stinnera47082312012-10-04 02:19:54 +020014037 buflen = arg->width;
14038 if (arg->sign && len == arg->width)
14039 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014040 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014041 return -1;
14042
14043 /* Write the sign if needed */
14044 if (arg->sign) {
14045 if (fill != ' ') {
14046 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14047 writer->pos += 1;
14048 }
14049 if (arg->width > len)
14050 arg->width--;
14051 }
14052
14053 /* Write the numeric prefix for "x", "X" and "o" formats
14054 if the alternate form is used.
14055 For example, write "0x" for the "%#x" format. */
14056 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14057 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14058 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14059 if (fill != ' ') {
14060 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14061 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14062 writer->pos += 2;
14063 pindex += 2;
14064 }
14065 arg->width -= 2;
14066 if (arg->width < 0)
14067 arg->width = 0;
14068 len -= 2;
14069 }
14070
14071 /* Pad left with the fill character if needed */
14072 if (arg->width > len && !(arg->flags & F_LJUST)) {
14073 sublen = arg->width - len;
14074 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14075 writer->pos += sublen;
14076 arg->width = len;
14077 }
14078
14079 /* If padding with spaces: write sign if needed and/or numeric prefix if
14080 the alternate form is used */
14081 if (fill == ' ') {
14082 if (arg->sign) {
14083 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14084 writer->pos += 1;
14085 }
14086 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14087 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14088 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14089 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14090 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14091 writer->pos += 2;
14092 pindex += 2;
14093 }
14094 }
14095
14096 /* Write characters */
14097 if (len) {
14098 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14099 str, pindex, len);
14100 writer->pos += len;
14101 }
14102
14103 /* Pad right with the fill character if needed */
14104 if (arg->width > len) {
14105 sublen = arg->width - len;
14106 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14107 writer->pos += sublen;
14108 }
14109 return 0;
14110}
14111
14112/* Helper of PyUnicode_Format(): format one arg.
14113 Return 0 on success, raise an exception and return -1 on error. */
14114static int
14115unicode_format_arg(struct unicode_formatter_t *ctx)
14116{
14117 struct unicode_format_arg_t arg;
14118 PyObject *str;
14119 int ret;
14120
Victor Stinner8dbd4212012-12-04 09:30:24 +010014121 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14122 arg.flags = 0;
14123 arg.width = -1;
14124 arg.prec = -1;
14125 arg.sign = 0;
14126 str = NULL;
14127
Victor Stinnera47082312012-10-04 02:19:54 +020014128 ret = unicode_format_arg_parse(ctx, &arg);
14129 if (ret == -1)
14130 return -1;
14131
14132 ret = unicode_format_arg_format(ctx, &arg, &str);
14133 if (ret == -1)
14134 return -1;
14135
14136 if (ret != 1) {
14137 ret = unicode_format_arg_output(ctx, &arg, str);
14138 Py_DECREF(str);
14139 if (ret == -1)
14140 return -1;
14141 }
14142
14143 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14144 PyErr_SetString(PyExc_TypeError,
14145 "not all arguments converted during string formatting");
14146 return -1;
14147 }
14148 return 0;
14149}
14150
Alexander Belopolsky40018472011-02-26 01:02:56 +000014151PyObject *
14152PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014153{
Victor Stinnera47082312012-10-04 02:19:54 +020014154 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014155
Guido van Rossumd57fd912000-03-10 22:53:23 +000014156 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014157 PyErr_BadInternalCall();
14158 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014159 }
Victor Stinnera47082312012-10-04 02:19:54 +020014160
14161 ctx.fmtstr = PyUnicode_FromObject(format);
14162 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014163 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014164 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14165 Py_DECREF(ctx.fmtstr);
14166 return NULL;
14167 }
14168 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14169 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14170 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14171 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014172
Victor Stinnera47082312012-10-04 02:19:54 +020014173 _PyUnicodeWriter_Init(&ctx.writer, ctx.fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014174
Guido van Rossumd57fd912000-03-10 22:53:23 +000014175 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014176 ctx.arglen = PyTuple_Size(args);
14177 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014178 }
14179 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014180 ctx.arglen = -1;
14181 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014182 }
Victor Stinnera47082312012-10-04 02:19:54 +020014183 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014184 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014185 ctx.dict = args;
14186 else
14187 ctx.dict = NULL;
14188 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014189
Victor Stinnera47082312012-10-04 02:19:54 +020014190 while (--ctx.fmtcnt >= 0) {
14191 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014192 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014193
14194 nonfmtpos = ctx.fmtpos++;
14195 while (ctx.fmtcnt >= 0 &&
14196 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14197 ctx.fmtpos++;
14198 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014199 }
Victor Stinnera47082312012-10-04 02:19:54 +020014200 if (ctx.fmtcnt < 0) {
14201 ctx.fmtpos--;
14202 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014203 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014204
Victor Stinnercfc4c132013-04-03 01:48:39 +020014205 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14206 nonfmtpos, ctx.fmtpos) < 0)
14207 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014208 }
14209 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014210 ctx.fmtpos++;
14211 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014212 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014213 }
14214 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014215
Victor Stinnera47082312012-10-04 02:19:54 +020014216 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014217 PyErr_SetString(PyExc_TypeError,
14218 "not all arguments converted during string formatting");
14219 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014220 }
14221
Victor Stinnera47082312012-10-04 02:19:54 +020014222 if (ctx.args_owned) {
14223 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014224 }
Victor Stinnera47082312012-10-04 02:19:54 +020014225 Py_DECREF(ctx.fmtstr);
14226 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014227
Benjamin Peterson29060642009-01-31 22:14:21 +000014228 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014229 Py_DECREF(ctx.fmtstr);
14230 _PyUnicodeWriter_Dealloc(&ctx.writer);
14231 if (ctx.args_owned) {
14232 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014233 }
14234 return NULL;
14235}
14236
Jeremy Hylton938ace62002-07-17 16:30:39 +000014237static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014238unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14239
Tim Peters6d6c1a32001-08-02 04:15:00 +000014240static PyObject *
14241unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14242{
Benjamin Peterson29060642009-01-31 22:14:21 +000014243 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014244 static char *kwlist[] = {"object", "encoding", "errors", 0};
14245 char *encoding = NULL;
14246 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014247
Benjamin Peterson14339b62009-01-31 16:36:08 +000014248 if (type != &PyUnicode_Type)
14249 return unicode_subtype_new(type, args, kwds);
14250 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014251 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014252 return NULL;
14253 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014254 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014255 if (encoding == NULL && errors == NULL)
14256 return PyObject_Str(x);
14257 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014258 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014259}
14260
Guido van Rossume023fe02001-08-30 03:12:59 +000014261static PyObject *
14262unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14263{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014264 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014265 Py_ssize_t length, char_size;
14266 int share_wstr, share_utf8;
14267 unsigned int kind;
14268 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014269
Benjamin Peterson14339b62009-01-31 16:36:08 +000014270 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014271
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014272 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014273 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014274 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014275 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014276 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014277 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014278 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014279 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014280
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014281 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014282 if (self == NULL) {
14283 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 return NULL;
14285 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014286 kind = PyUnicode_KIND(unicode);
14287 length = PyUnicode_GET_LENGTH(unicode);
14288
14289 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014290#ifdef Py_DEBUG
14291 _PyUnicode_HASH(self) = -1;
14292#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014293 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014294#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014295 _PyUnicode_STATE(self).interned = 0;
14296 _PyUnicode_STATE(self).kind = kind;
14297 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014298 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014299 _PyUnicode_STATE(self).ready = 1;
14300 _PyUnicode_WSTR(self) = NULL;
14301 _PyUnicode_UTF8_LENGTH(self) = 0;
14302 _PyUnicode_UTF8(self) = NULL;
14303 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014304 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014305
14306 share_utf8 = 0;
14307 share_wstr = 0;
14308 if (kind == PyUnicode_1BYTE_KIND) {
14309 char_size = 1;
14310 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14311 share_utf8 = 1;
14312 }
14313 else if (kind == PyUnicode_2BYTE_KIND) {
14314 char_size = 2;
14315 if (sizeof(wchar_t) == 2)
14316 share_wstr = 1;
14317 }
14318 else {
14319 assert(kind == PyUnicode_4BYTE_KIND);
14320 char_size = 4;
14321 if (sizeof(wchar_t) == 4)
14322 share_wstr = 1;
14323 }
14324
14325 /* Ensure we won't overflow the length. */
14326 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14327 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014328 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014329 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014330 data = PyObject_MALLOC((length + 1) * char_size);
14331 if (data == NULL) {
14332 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014333 goto onError;
14334 }
14335
Victor Stinnerc3c74152011-10-02 20:39:55 +020014336 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014337 if (share_utf8) {
14338 _PyUnicode_UTF8_LENGTH(self) = length;
14339 _PyUnicode_UTF8(self) = data;
14340 }
14341 if (share_wstr) {
14342 _PyUnicode_WSTR_LENGTH(self) = length;
14343 _PyUnicode_WSTR(self) = (wchar_t *)data;
14344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014345
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014346 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014347 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014348 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014349#ifdef Py_DEBUG
14350 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14351#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014352 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014353 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014354
14355onError:
14356 Py_DECREF(unicode);
14357 Py_DECREF(self);
14358 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014359}
14360
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014361PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014362"str(object='') -> str\n\
14363str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014364\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014365Create a new string object from the given object. If encoding or\n\
14366errors is specified, then the object must expose a data buffer\n\
14367that will be decoded using the given encoding and error handler.\n\
14368Otherwise, returns the result of object.__str__() (if defined)\n\
14369or repr(object).\n\
14370encoding defaults to sys.getdefaultencoding().\n\
14371errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014372
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014373static PyObject *unicode_iter(PyObject *seq);
14374
Guido van Rossumd57fd912000-03-10 22:53:23 +000014375PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014376 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014377 "str", /* tp_name */
14378 sizeof(PyUnicodeObject), /* tp_size */
14379 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014380 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014381 (destructor)unicode_dealloc, /* tp_dealloc */
14382 0, /* tp_print */
14383 0, /* tp_getattr */
14384 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014385 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014386 unicode_repr, /* tp_repr */
14387 &unicode_as_number, /* tp_as_number */
14388 &unicode_as_sequence, /* tp_as_sequence */
14389 &unicode_as_mapping, /* tp_as_mapping */
14390 (hashfunc) unicode_hash, /* tp_hash*/
14391 0, /* tp_call*/
14392 (reprfunc) unicode_str, /* tp_str */
14393 PyObject_GenericGetAttr, /* tp_getattro */
14394 0, /* tp_setattro */
14395 0, /* tp_as_buffer */
14396 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014397 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014398 unicode_doc, /* tp_doc */
14399 0, /* tp_traverse */
14400 0, /* tp_clear */
14401 PyUnicode_RichCompare, /* tp_richcompare */
14402 0, /* tp_weaklistoffset */
14403 unicode_iter, /* tp_iter */
14404 0, /* tp_iternext */
14405 unicode_methods, /* tp_methods */
14406 0, /* tp_members */
14407 0, /* tp_getset */
14408 &PyBaseObject_Type, /* tp_base */
14409 0, /* tp_dict */
14410 0, /* tp_descr_get */
14411 0, /* tp_descr_set */
14412 0, /* tp_dictoffset */
14413 0, /* tp_init */
14414 0, /* tp_alloc */
14415 unicode_new, /* tp_new */
14416 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014417};
14418
14419/* Initialize the Unicode implementation */
14420
Victor Stinner3a50e702011-10-18 21:21:00 +020014421int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014422{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014423 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014424 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014425 0x000A, /* LINE FEED */
14426 0x000D, /* CARRIAGE RETURN */
14427 0x001C, /* FILE SEPARATOR */
14428 0x001D, /* GROUP SEPARATOR */
14429 0x001E, /* RECORD SEPARATOR */
14430 0x0085, /* NEXT LINE */
14431 0x2028, /* LINE SEPARATOR */
14432 0x2029, /* PARAGRAPH SEPARATOR */
14433 };
14434
Fred Drakee4315f52000-05-09 19:53:39 +000014435 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014436 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014437 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014438 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014439 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014440
Guido van Rossumcacfc072002-05-24 19:01:59 +000014441 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014442 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014443
14444 /* initialize the linebreak bloom filter */
14445 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014446 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014447 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014448
14449 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014450
Benjamin Petersonc4311282012-10-30 23:21:10 -040014451 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14452 Py_FatalError("Can't initialize field name iterator type");
14453
14454 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14455 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014456
Victor Stinner3a50e702011-10-18 21:21:00 +020014457#ifdef HAVE_MBCS
14458 winver.dwOSVersionInfoSize = sizeof(winver);
14459 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14460 PyErr_SetFromWindowsErr(0);
14461 return -1;
14462 }
14463#endif
14464 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014465}
14466
14467/* Finalize the Unicode implementation */
14468
Christian Heimesa156e092008-02-16 07:38:31 +000014469int
14470PyUnicode_ClearFreeList(void)
14471{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014472 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014473}
14474
Guido van Rossumd57fd912000-03-10 22:53:23 +000014475void
Thomas Wouters78890102000-07-22 19:25:51 +000014476_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014477{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014478 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014479
Serhiy Storchaka05997252013-01-26 12:14:02 +020014480 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014481
Serhiy Storchaka05997252013-01-26 12:14:02 +020014482 for (i = 0; i < 256; i++)
14483 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014484 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014485 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014486}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014487
Walter Dörwald16807132007-05-25 13:52:07 +000014488void
14489PyUnicode_InternInPlace(PyObject **p)
14490{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014491 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014492 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014493#ifdef Py_DEBUG
14494 assert(s != NULL);
14495 assert(_PyUnicode_CHECK(s));
14496#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014497 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014498 return;
14499#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014500 /* If it's a subclass, we don't really know what putting
14501 it in the interned dict might do. */
14502 if (!PyUnicode_CheckExact(s))
14503 return;
14504 if (PyUnicode_CHECK_INTERNED(s))
14505 return;
14506 if (interned == NULL) {
14507 interned = PyDict_New();
14508 if (interned == NULL) {
14509 PyErr_Clear(); /* Don't leave an exception */
14510 return;
14511 }
14512 }
14513 /* It might be that the GetItem call fails even
14514 though the key is present in the dictionary,
14515 namely when this happens during a stack overflow. */
14516 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014517 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014518 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014519
Benjamin Peterson29060642009-01-31 22:14:21 +000014520 if (t) {
14521 Py_INCREF(t);
14522 Py_DECREF(*p);
14523 *p = t;
14524 return;
14525 }
Walter Dörwald16807132007-05-25 13:52:07 +000014526
Benjamin Peterson14339b62009-01-31 16:36:08 +000014527 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014528 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014529 PyErr_Clear();
14530 PyThreadState_GET()->recursion_critical = 0;
14531 return;
14532 }
14533 PyThreadState_GET()->recursion_critical = 0;
14534 /* The two references in interned are not counted by refcnt.
14535 The deallocator will take care of this */
14536 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014537 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014538}
14539
14540void
14541PyUnicode_InternImmortal(PyObject **p)
14542{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014543 PyUnicode_InternInPlace(p);
14544 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014545 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014546 Py_INCREF(*p);
14547 }
Walter Dörwald16807132007-05-25 13:52:07 +000014548}
14549
14550PyObject *
14551PyUnicode_InternFromString(const char *cp)
14552{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014553 PyObject *s = PyUnicode_FromString(cp);
14554 if (s == NULL)
14555 return NULL;
14556 PyUnicode_InternInPlace(&s);
14557 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014558}
14559
Alexander Belopolsky40018472011-02-26 01:02:56 +000014560void
14561_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014562{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014563 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014564 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014565 Py_ssize_t i, n;
14566 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014567
Benjamin Peterson14339b62009-01-31 16:36:08 +000014568 if (interned == NULL || !PyDict_Check(interned))
14569 return;
14570 keys = PyDict_Keys(interned);
14571 if (keys == NULL || !PyList_Check(keys)) {
14572 PyErr_Clear();
14573 return;
14574 }
Walter Dörwald16807132007-05-25 13:52:07 +000014575
Benjamin Peterson14339b62009-01-31 16:36:08 +000014576 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14577 detector, interned unicode strings are not forcibly deallocated;
14578 rather, we give them their stolen references back, and then clear
14579 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014580
Benjamin Peterson14339b62009-01-31 16:36:08 +000014581 n = PyList_GET_SIZE(keys);
14582 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014583 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014584 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014585 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014586 if (PyUnicode_READY(s) == -1) {
14587 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014588 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014590 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014591 case SSTATE_NOT_INTERNED:
14592 /* XXX Shouldn't happen */
14593 break;
14594 case SSTATE_INTERNED_IMMORTAL:
14595 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014596 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014597 break;
14598 case SSTATE_INTERNED_MORTAL:
14599 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014600 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014601 break;
14602 default:
14603 Py_FatalError("Inconsistent interned string state.");
14604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014605 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014606 }
14607 fprintf(stderr, "total size of all interned strings: "
14608 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14609 "mortal/immortal\n", mortal_size, immortal_size);
14610 Py_DECREF(keys);
14611 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014612 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014613}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014614
14615
14616/********************* Unicode Iterator **************************/
14617
14618typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014619 PyObject_HEAD
14620 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014621 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014622} unicodeiterobject;
14623
14624static void
14625unicodeiter_dealloc(unicodeiterobject *it)
14626{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014627 _PyObject_GC_UNTRACK(it);
14628 Py_XDECREF(it->it_seq);
14629 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014630}
14631
14632static int
14633unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14634{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014635 Py_VISIT(it->it_seq);
14636 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014637}
14638
14639static PyObject *
14640unicodeiter_next(unicodeiterobject *it)
14641{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014642 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014643
Benjamin Peterson14339b62009-01-31 16:36:08 +000014644 assert(it != NULL);
14645 seq = it->it_seq;
14646 if (seq == NULL)
14647 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014648 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014649
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014650 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14651 int kind = PyUnicode_KIND(seq);
14652 void *data = PyUnicode_DATA(seq);
14653 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14654 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014655 if (item != NULL)
14656 ++it->it_index;
14657 return item;
14658 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014659
Benjamin Peterson14339b62009-01-31 16:36:08 +000014660 Py_DECREF(seq);
14661 it->it_seq = NULL;
14662 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014663}
14664
14665static PyObject *
14666unicodeiter_len(unicodeiterobject *it)
14667{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014668 Py_ssize_t len = 0;
14669 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014670 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014671 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014672}
14673
14674PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14675
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014676static PyObject *
14677unicodeiter_reduce(unicodeiterobject *it)
14678{
14679 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014680 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014681 it->it_seq, it->it_index);
14682 } else {
14683 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14684 if (u == NULL)
14685 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014686 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014687 }
14688}
14689
14690PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14691
14692static PyObject *
14693unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14694{
14695 Py_ssize_t index = PyLong_AsSsize_t(state);
14696 if (index == -1 && PyErr_Occurred())
14697 return NULL;
14698 if (index < 0)
14699 index = 0;
14700 it->it_index = index;
14701 Py_RETURN_NONE;
14702}
14703
14704PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14705
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014706static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014707 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014708 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014709 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14710 reduce_doc},
14711 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14712 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014713 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014714};
14715
14716PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014717 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14718 "str_iterator", /* tp_name */
14719 sizeof(unicodeiterobject), /* tp_basicsize */
14720 0, /* tp_itemsize */
14721 /* methods */
14722 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14723 0, /* tp_print */
14724 0, /* tp_getattr */
14725 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014726 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014727 0, /* tp_repr */
14728 0, /* tp_as_number */
14729 0, /* tp_as_sequence */
14730 0, /* tp_as_mapping */
14731 0, /* tp_hash */
14732 0, /* tp_call */
14733 0, /* tp_str */
14734 PyObject_GenericGetAttr, /* tp_getattro */
14735 0, /* tp_setattro */
14736 0, /* tp_as_buffer */
14737 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14738 0, /* tp_doc */
14739 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14740 0, /* tp_clear */
14741 0, /* tp_richcompare */
14742 0, /* tp_weaklistoffset */
14743 PyObject_SelfIter, /* tp_iter */
14744 (iternextfunc)unicodeiter_next, /* tp_iternext */
14745 unicodeiter_methods, /* tp_methods */
14746 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014747};
14748
14749static PyObject *
14750unicode_iter(PyObject *seq)
14751{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014752 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014753
Benjamin Peterson14339b62009-01-31 16:36:08 +000014754 if (!PyUnicode_Check(seq)) {
14755 PyErr_BadInternalCall();
14756 return NULL;
14757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014758 if (PyUnicode_READY(seq) == -1)
14759 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014760 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14761 if (it == NULL)
14762 return NULL;
14763 it->it_index = 0;
14764 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014765 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014766 _PyObject_GC_TRACK(it);
14767 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014768}
14769
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014770
14771size_t
14772Py_UNICODE_strlen(const Py_UNICODE *u)
14773{
14774 int res = 0;
14775 while(*u++)
14776 res++;
14777 return res;
14778}
14779
14780Py_UNICODE*
14781Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14782{
14783 Py_UNICODE *u = s1;
14784 while ((*u++ = *s2++));
14785 return s1;
14786}
14787
14788Py_UNICODE*
14789Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14790{
14791 Py_UNICODE *u = s1;
14792 while ((*u++ = *s2++))
14793 if (n-- == 0)
14794 break;
14795 return s1;
14796}
14797
14798Py_UNICODE*
14799Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14800{
14801 Py_UNICODE *u1 = s1;
14802 u1 += Py_UNICODE_strlen(u1);
14803 Py_UNICODE_strcpy(u1, s2);
14804 return s1;
14805}
14806
14807int
14808Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14809{
14810 while (*s1 && *s2 && *s1 == *s2)
14811 s1++, s2++;
14812 if (*s1 && *s2)
14813 return (*s1 < *s2) ? -1 : +1;
14814 if (*s1)
14815 return 1;
14816 if (*s2)
14817 return -1;
14818 return 0;
14819}
14820
14821int
14822Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14823{
14824 register Py_UNICODE u1, u2;
14825 for (; n != 0; n--) {
14826 u1 = *s1;
14827 u2 = *s2;
14828 if (u1 != u2)
14829 return (u1 < u2) ? -1 : +1;
14830 if (u1 == '\0')
14831 return 0;
14832 s1++;
14833 s2++;
14834 }
14835 return 0;
14836}
14837
14838Py_UNICODE*
14839Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14840{
14841 const Py_UNICODE *p;
14842 for (p = s; *p; p++)
14843 if (*p == c)
14844 return (Py_UNICODE*)p;
14845 return NULL;
14846}
14847
14848Py_UNICODE*
14849Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14850{
14851 const Py_UNICODE *p;
14852 p = s + Py_UNICODE_strlen(s);
14853 while (p != s) {
14854 p--;
14855 if (*p == c)
14856 return (Py_UNICODE*)p;
14857 }
14858 return NULL;
14859}
Victor Stinner331ea922010-08-10 16:37:20 +000014860
Victor Stinner71133ff2010-09-01 23:43:53 +000014861Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014862PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014863{
Victor Stinner577db2c2011-10-11 22:12:48 +020014864 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014865 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014867 if (!PyUnicode_Check(unicode)) {
14868 PyErr_BadArgument();
14869 return NULL;
14870 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014871 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014872 if (u == NULL)
14873 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014874 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014875 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014876 PyErr_NoMemory();
14877 return NULL;
14878 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014879 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014880 size *= sizeof(Py_UNICODE);
14881 copy = PyMem_Malloc(size);
14882 if (copy == NULL) {
14883 PyErr_NoMemory();
14884 return NULL;
14885 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014886 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014887 return copy;
14888}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014889
Georg Brandl66c221e2010-10-14 07:04:07 +000014890/* A _string module, to export formatter_parser and formatter_field_name_split
14891 to the string.Formatter class implemented in Python. */
14892
14893static PyMethodDef _string_methods[] = {
14894 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14895 METH_O, PyDoc_STR("split the argument as a field name")},
14896 {"formatter_parser", (PyCFunction) formatter_parser,
14897 METH_O, PyDoc_STR("parse the argument as a format string")},
14898 {NULL, NULL}
14899};
14900
14901static struct PyModuleDef _string_module = {
14902 PyModuleDef_HEAD_INIT,
14903 "_string",
14904 PyDoc_STR("string helper module"),
14905 0,
14906 _string_methods,
14907 NULL,
14908 NULL,
14909 NULL,
14910 NULL
14911};
14912
14913PyMODINIT_FUNC
14914PyInit__string(void)
14915{
14916 return PyModule_Create(&_string_module);
14917}
14918
14919
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014920#ifdef __cplusplus
14921}
14922#endif