blob: 6b63157266c236e7060b8458d51adeb024f89377 [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 {
10378#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 2
10379 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10380 /* normalize result of wmemcmp() into the range [-1; 1] */
10381 if (cmp < 0)
10382 return -1;
10383 if (cmp > 0)
10384 return 1;
10385#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010386 COMPARE(Py_UCS2, Py_UCS2);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010387#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010388 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010389 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010390 case PyUnicode_4BYTE_KIND:
10391 COMPARE(Py_UCS2, Py_UCS4);
10392 break;
10393 default:
10394 assert(0);
10395 }
10396 break;
10397 }
10398 case PyUnicode_4BYTE_KIND:
10399 {
10400 switch(kind2) {
10401 case PyUnicode_1BYTE_KIND:
10402 COMPARE(Py_UCS4, Py_UCS1);
10403 break;
10404 case PyUnicode_2BYTE_KIND:
10405 COMPARE(Py_UCS4, Py_UCS2);
10406 break;
10407 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010408 {
10409#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10410 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10411 /* normalize result of wmemcmp() into the range [-1; 1] */
10412 if (cmp < 0)
10413 return -1;
10414 if (cmp > 0)
10415 return 1;
10416#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010417 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010418#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010419 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010420 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010421 default:
10422 assert(0);
10423 }
10424 break;
10425 }
10426 default:
10427 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010428 }
10429
Victor Stinner770e19e2012-10-04 22:59:45 +020010430 if (len1 == len2)
10431 return 0;
10432 if (len1 < len2)
10433 return -1;
10434 else
10435 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010436
10437#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010438}
10439
Victor Stinnere5567ad2012-10-23 02:48:49 +020010440static int
10441unicode_compare_eq(PyObject *str1, PyObject *str2)
10442{
10443 int kind;
10444 void *data1, *data2;
10445 Py_ssize_t len;
10446 int cmp;
10447
10448 /* a string is equal to itself */
10449 if (str1 == str2)
10450 return 1;
10451
10452 len = PyUnicode_GET_LENGTH(str1);
10453 if (PyUnicode_GET_LENGTH(str2) != len)
10454 return 0;
10455 kind = PyUnicode_KIND(str1);
10456 if (PyUnicode_KIND(str2) != kind)
10457 return 0;
10458 data1 = PyUnicode_DATA(str1);
10459 data2 = PyUnicode_DATA(str2);
10460
10461 cmp = memcmp(data1, data2, len * kind);
10462 return (cmp == 0);
10463}
10464
10465
Alexander Belopolsky40018472011-02-26 01:02:56 +000010466int
10467PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10470 if (PyUnicode_READY(left) == -1 ||
10471 PyUnicode_READY(right) == -1)
10472 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010473 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010475 PyErr_Format(PyExc_TypeError,
10476 "Can't compare %.100s and %.100s",
10477 left->ob_type->tp_name,
10478 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010479 return -1;
10480}
10481
Martin v. Löwis5b222132007-06-10 09:51:05 +000010482int
10483PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 Py_ssize_t i;
10486 int kind;
10487 void *data;
10488 Py_UCS4 chr;
10489
Victor Stinner910337b2011-10-03 03:20:16 +020010490 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 if (PyUnicode_READY(uni) == -1)
10492 return -1;
10493 kind = PyUnicode_KIND(uni);
10494 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010495 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10497 if (chr != str[i])
10498 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010499 /* This check keeps Python strings that end in '\0' from comparing equal
10500 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010502 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010503 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010504 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010505 return 0;
10506}
10507
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010508
Benjamin Peterson29060642009-01-31 22:14:21 +000010509#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010510 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010511
Alexander Belopolsky40018472011-02-26 01:02:56 +000010512PyObject *
10513PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010514{
10515 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010516 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010517
Victor Stinnere5567ad2012-10-23 02:48:49 +020010518 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10519 Py_RETURN_NOTIMPLEMENTED;
10520
10521 if (PyUnicode_READY(left) == -1 ||
10522 PyUnicode_READY(right) == -1)
10523 return NULL;
10524
10525 if (op == Py_EQ || op == Py_NE) {
10526 result = unicode_compare_eq(left, right);
10527 if (op == Py_EQ)
10528 v = TEST_COND(result);
10529 else
10530 v = TEST_COND(!result);
10531 }
10532 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010533 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010534
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010535 /* Convert the return value to a Boolean */
10536 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010537 case Py_LE:
10538 v = TEST_COND(result <= 0);
10539 break;
10540 case Py_GE:
10541 v = TEST_COND(result >= 0);
10542 break;
10543 case Py_LT:
10544 v = TEST_COND(result == -1);
10545 break;
10546 case Py_GT:
10547 v = TEST_COND(result == 1);
10548 break;
10549 default:
10550 PyErr_BadArgument();
10551 return NULL;
10552 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010553 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010554 Py_INCREF(v);
10555 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010556}
10557
Alexander Belopolsky40018472011-02-26 01:02:56 +000010558int
10559PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010560{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010561 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 int kind1, kind2, kind;
10563 void *buf1, *buf2;
10564 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010565 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010566
10567 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568 sub = PyUnicode_FromObject(element);
10569 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010570 PyErr_Format(PyExc_TypeError,
10571 "'in <string>' requires string as left operand, not %s",
10572 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010573 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010574 }
10575
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010577 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010578 Py_DECREF(sub);
10579 return -1;
10580 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010581 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10582 Py_DECREF(sub);
10583 Py_DECREF(str);
10584 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 kind1 = PyUnicode_KIND(str);
10587 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010588 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 buf1 = PyUnicode_DATA(str);
10590 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010591 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010592 if (kind2 > kind) {
10593 Py_DECREF(sub);
10594 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010595 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010596 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010597 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010598 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 if (!buf2) {
10600 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010601 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 return -1;
10603 }
10604 len1 = PyUnicode_GET_LENGTH(str);
10605 len2 = PyUnicode_GET_LENGTH(sub);
10606
Benjamin Petersonead6b532011-12-20 17:23:42 -060010607 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 case PyUnicode_1BYTE_KIND:
10609 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10610 break;
10611 case PyUnicode_2BYTE_KIND:
10612 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10613 break;
10614 case PyUnicode_4BYTE_KIND:
10615 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10616 break;
10617 default:
10618 result = -1;
10619 assert(0);
10620 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010621
10622 Py_DECREF(str);
10623 Py_DECREF(sub);
10624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 if (kind2 != kind)
10626 PyMem_Free(buf2);
10627
Guido van Rossum403d68b2000-03-13 15:55:09 +000010628 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010629}
10630
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631/* Concat to string or Unicode object giving a new Unicode object. */
10632
Alexander Belopolsky40018472011-02-26 01:02:56 +000010633PyObject *
10634PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010637 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010638 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639
10640 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010646 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647
10648 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010649 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010650 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010653 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010654 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 }
10657
Victor Stinner488fa492011-12-12 00:01:39 +010010658 u_len = PyUnicode_GET_LENGTH(u);
10659 v_len = PyUnicode_GET_LENGTH(v);
10660 if (u_len > PY_SSIZE_T_MAX - v_len) {
10661 PyErr_SetString(PyExc_OverflowError,
10662 "strings are too large to concat");
10663 goto onError;
10664 }
10665 new_len = u_len + v_len;
10666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010668 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010669 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670
Guido van Rossumd57fd912000-03-10 22:53:23 +000010671 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010672 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010674 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010675 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10676 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677 Py_DECREF(u);
10678 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010679 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681
Benjamin Peterson29060642009-01-31 22:14:21 +000010682 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683 Py_XDECREF(u);
10684 Py_XDECREF(v);
10685 return NULL;
10686}
10687
Walter Dörwald1ab83302007-05-18 17:15:44 +000010688void
Victor Stinner23e56682011-10-03 03:54:37 +020010689PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010690{
Victor Stinner23e56682011-10-03 03:54:37 +020010691 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010692 Py_UCS4 maxchar, maxchar2;
10693 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010694
10695 if (p_left == NULL) {
10696 if (!PyErr_Occurred())
10697 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010698 return;
10699 }
Victor Stinner23e56682011-10-03 03:54:37 +020010700 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010701 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010702 if (!PyErr_Occurred())
10703 PyErr_BadInternalCall();
10704 goto error;
10705 }
10706
Benjamin Petersonbac79492012-01-14 13:34:47 -050010707 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010708 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010709 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010710 goto error;
10711
Victor Stinner488fa492011-12-12 00:01:39 +010010712 /* Shortcuts */
10713 if (left == unicode_empty) {
10714 Py_DECREF(left);
10715 Py_INCREF(right);
10716 *p_left = right;
10717 return;
10718 }
10719 if (right == unicode_empty)
10720 return;
10721
10722 left_len = PyUnicode_GET_LENGTH(left);
10723 right_len = PyUnicode_GET_LENGTH(right);
10724 if (left_len > PY_SSIZE_T_MAX - right_len) {
10725 PyErr_SetString(PyExc_OverflowError,
10726 "strings are too large to concat");
10727 goto error;
10728 }
10729 new_len = left_len + right_len;
10730
10731 if (unicode_modifiable(left)
10732 && PyUnicode_CheckExact(right)
10733 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010734 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10735 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010736 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010737 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010738 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10739 {
10740 /* append inplace */
10741 if (unicode_resize(p_left, new_len) != 0) {
10742 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10743 * deallocated so it cannot be put back into
10744 * 'variable'. The MemoryError is raised when there
10745 * is no value in 'variable', which might (very
10746 * remotely) be a cause of incompatibilities.
10747 */
10748 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010749 }
Victor Stinner488fa492011-12-12 00:01:39 +010010750 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010751 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010752 }
Victor Stinner488fa492011-12-12 00:01:39 +010010753 else {
10754 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10755 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010756 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010757
Victor Stinner488fa492011-12-12 00:01:39 +010010758 /* Concat the two Unicode strings */
10759 res = PyUnicode_New(new_len, maxchar);
10760 if (res == NULL)
10761 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010762 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10763 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010764 Py_DECREF(left);
10765 *p_left = res;
10766 }
10767 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010768 return;
10769
10770error:
Victor Stinner488fa492011-12-12 00:01:39 +010010771 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010772}
10773
10774void
10775PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10776{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010777 PyUnicode_Append(pleft, right);
10778 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010779}
10780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010781PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010782 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010784Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010785string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010786interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010787
10788static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010789unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010790{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010791 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010792 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010793 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 int kind1, kind2, kind;
10796 void *buf1, *buf2;
10797 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798
Jesus Ceaac451502011-04-20 17:09:23 +020010799 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10800 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010801 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010803 kind1 = PyUnicode_KIND(self);
10804 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010805 if (kind2 > kind1)
10806 return PyLong_FromLong(0);
10807 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010808 buf1 = PyUnicode_DATA(self);
10809 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010811 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 if (!buf2) {
10813 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010814 return NULL;
10815 }
10816 len1 = PyUnicode_GET_LENGTH(self);
10817 len2 = PyUnicode_GET_LENGTH(substring);
10818
10819 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010820 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010821 case PyUnicode_1BYTE_KIND:
10822 iresult = ucs1lib_count(
10823 ((Py_UCS1*)buf1) + start, end - start,
10824 buf2, len2, PY_SSIZE_T_MAX
10825 );
10826 break;
10827 case PyUnicode_2BYTE_KIND:
10828 iresult = ucs2lib_count(
10829 ((Py_UCS2*)buf1) + start, end - start,
10830 buf2, len2, PY_SSIZE_T_MAX
10831 );
10832 break;
10833 case PyUnicode_4BYTE_KIND:
10834 iresult = ucs4lib_count(
10835 ((Py_UCS4*)buf1) + start, end - start,
10836 buf2, len2, PY_SSIZE_T_MAX
10837 );
10838 break;
10839 default:
10840 assert(0); iresult = 0;
10841 }
10842
10843 result = PyLong_FromSsize_t(iresult);
10844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010845 if (kind2 != kind)
10846 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847
10848 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010849
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850 return result;
10851}
10852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010853PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010854 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010856Encode S using the codec registered for encoding. Default encoding\n\
10857is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010858handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010859a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10860'xmlcharrefreplace' as well as any other name registered with\n\
10861codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862
10863static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010864unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010865{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010866 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867 char *encoding = NULL;
10868 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010869
Benjamin Peterson308d6372009-09-18 21:42:35 +000010870 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10871 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010873 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010874}
10875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010876PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010877 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878\n\
10879Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010880If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881
10882static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010883unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 Py_ssize_t i, j, line_pos, src_len, incr;
10886 Py_UCS4 ch;
10887 PyObject *u;
10888 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010889 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010891 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010892
10893 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010895
Antoine Pitrou22425222011-10-04 19:10:51 +020010896 if (PyUnicode_READY(self) == -1)
10897 return NULL;
10898
Thomas Wouters7e474022000-07-16 12:04:32 +000010899 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010900 src_len = PyUnicode_GET_LENGTH(self);
10901 i = j = line_pos = 0;
10902 kind = PyUnicode_KIND(self);
10903 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010904 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010905 for (; i < src_len; i++) {
10906 ch = PyUnicode_READ(kind, src_data, i);
10907 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010908 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010909 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010910 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010911 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010912 goto overflow;
10913 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010914 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010915 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010916 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010919 goto overflow;
10920 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010922 if (ch == '\n' || ch == '\r')
10923 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010925 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010926 if (!found)
10927 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010928
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010930 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931 if (!u)
10932 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010933 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934
Antoine Pitroue71d5742011-10-04 15:55:09 +020010935 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936
Antoine Pitroue71d5742011-10-04 15:55:09 +020010937 for (; i < src_len; i++) {
10938 ch = PyUnicode_READ(kind, src_data, i);
10939 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010940 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010941 incr = tabsize - (line_pos % tabsize);
10942 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010943 FILL(kind, dest_data, ' ', j, incr);
10944 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010945 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010946 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010947 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010948 line_pos++;
10949 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010950 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010951 if (ch == '\n' || ch == '\r')
10952 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010954 }
10955 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010956 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010957
Antoine Pitroue71d5742011-10-04 15:55:09 +020010958 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010959 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10960 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010961}
10962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010963PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010964 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965\n\
10966Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010967such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968arguments start and end are interpreted as in slice notation.\n\
10969\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010970Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010971
10972static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010973unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010975 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010976 Py_ssize_t start;
10977 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010978 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979
Jesus Ceaac451502011-04-20 17:09:23 +020010980 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10981 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 if (PyUnicode_READY(self) == -1)
10985 return NULL;
10986 if (PyUnicode_READY(substring) == -1)
10987 return NULL;
10988
Victor Stinner7931d9a2011-11-04 00:22:48 +010010989 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990
10991 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 if (result == -2)
10994 return NULL;
10995
Christian Heimes217cfd12007-12-02 14:31:20 +000010996 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997}
10998
10999static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011000unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011002 void *data;
11003 enum PyUnicode_Kind kind;
11004 Py_UCS4 ch;
11005 PyObject *res;
11006
11007 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11008 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011010 }
11011 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11012 PyErr_SetString(PyExc_IndexError, "string index out of range");
11013 return NULL;
11014 }
11015 kind = PyUnicode_KIND(self);
11016 data = PyUnicode_DATA(self);
11017 ch = PyUnicode_READ(kind, data, index);
11018 if (ch < 256)
11019 return get_latin1_char(ch);
11020
11021 res = PyUnicode_New(1, ch);
11022 if (res == NULL)
11023 return NULL;
11024 kind = PyUnicode_KIND(res);
11025 data = PyUnicode_DATA(res);
11026 PyUnicode_WRITE(kind, data, 0, ch);
11027 assert(_PyUnicode_CheckConsistency(res, 1));
11028 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029}
11030
Guido van Rossumc2504932007-09-18 19:42:40 +000011031/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011032 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011033static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011034unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035{
Guido van Rossumc2504932007-09-18 19:42:40 +000011036 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011037 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011038
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011039#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011040 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011041#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011042 if (_PyUnicode_HASH(self) != -1)
11043 return _PyUnicode_HASH(self);
11044 if (PyUnicode_READY(self) == -1)
11045 return -1;
11046 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011047 /*
11048 We make the hash of the empty string be 0, rather than using
11049 (prefix ^ suffix), since this slightly obfuscates the hash secret
11050 */
11051 if (len == 0) {
11052 _PyUnicode_HASH(self) = 0;
11053 return 0;
11054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055
11056 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011057#define HASH(P) \
11058 x ^= (Py_uhash_t) *P << 7; \
11059 while (--len >= 0) \
11060 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061
Georg Brandl2fb477c2012-02-21 00:33:36 +010011062 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011063 switch (PyUnicode_KIND(self)) {
11064 case PyUnicode_1BYTE_KIND: {
11065 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11066 HASH(c);
11067 break;
11068 }
11069 case PyUnicode_2BYTE_KIND: {
11070 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11071 HASH(s);
11072 break;
11073 }
11074 default: {
11075 Py_UCS4 *l;
11076 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11077 "Impossible switch case in unicode_hash");
11078 l = PyUnicode_4BYTE_DATA(self);
11079 HASH(l);
11080 break;
11081 }
11082 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011083 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11084 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011085
Guido van Rossumc2504932007-09-18 19:42:40 +000011086 if (x == -1)
11087 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011088 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011089 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011093PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011094 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011096Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097
11098static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011101 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011102 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011103 Py_ssize_t start;
11104 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105
Jesus Ceaac451502011-04-20 17:09:23 +020011106 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11107 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 if (PyUnicode_READY(self) == -1)
11111 return NULL;
11112 if (PyUnicode_READY(substring) == -1)
11113 return NULL;
11114
Victor Stinner7931d9a2011-11-04 00:22:48 +010011115 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116
11117 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 if (result == -2)
11120 return NULL;
11121
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122 if (result < 0) {
11123 PyErr_SetString(PyExc_ValueError, "substring not found");
11124 return NULL;
11125 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011126
Christian Heimes217cfd12007-12-02 14:31:20 +000011127 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128}
11129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011131 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011133Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011134at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135
11136static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011137unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 Py_ssize_t i, length;
11140 int kind;
11141 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142 int cased;
11143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011144 if (PyUnicode_READY(self) == -1)
11145 return NULL;
11146 length = PyUnicode_GET_LENGTH(self);
11147 kind = PyUnicode_KIND(self);
11148 data = PyUnicode_DATA(self);
11149
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 if (length == 1)
11152 return PyBool_FromLong(
11153 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011155 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011157 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011158
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 for (i = 0; i < length; i++) {
11161 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011162
Benjamin Peterson29060642009-01-31 22:14:21 +000011163 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11164 return PyBool_FromLong(0);
11165 else if (!cased && Py_UNICODE_ISLOWER(ch))
11166 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011168 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169}
11170
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011171PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011172 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011174Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011175at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176
11177static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011178unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011180 Py_ssize_t i, length;
11181 int kind;
11182 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183 int cased;
11184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 if (PyUnicode_READY(self) == -1)
11186 return NULL;
11187 length = PyUnicode_GET_LENGTH(self);
11188 kind = PyUnicode_KIND(self);
11189 data = PyUnicode_DATA(self);
11190
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 if (length == 1)
11193 return PyBool_FromLong(
11194 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011196 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011199
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 for (i = 0; i < length; i++) {
11202 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011203
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11205 return PyBool_FromLong(0);
11206 else if (!cased && Py_UNICODE_ISUPPER(ch))
11207 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011209 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210}
11211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011212PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011213 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011215Return True if S is a titlecased string and there is at least one\n\
11216character in S, i.e. upper- and titlecase characters may only\n\
11217follow uncased characters and lowercase characters only cased ones.\n\
11218Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
11220static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011221unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 Py_ssize_t i, length;
11224 int kind;
11225 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226 int cased, previous_is_cased;
11227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 if (PyUnicode_READY(self) == -1)
11229 return NULL;
11230 length = PyUnicode_GET_LENGTH(self);
11231 kind = PyUnicode_KIND(self);
11232 data = PyUnicode_DATA(self);
11233
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235 if (length == 1) {
11236 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11237 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11238 (Py_UNICODE_ISUPPER(ch) != 0));
11239 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011241 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011243 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011244
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 cased = 0;
11246 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 for (i = 0; i < length; i++) {
11248 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011249
Benjamin Peterson29060642009-01-31 22:14:21 +000011250 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11251 if (previous_is_cased)
11252 return PyBool_FromLong(0);
11253 previous_is_cased = 1;
11254 cased = 1;
11255 }
11256 else if (Py_UNICODE_ISLOWER(ch)) {
11257 if (!previous_is_cased)
11258 return PyBool_FromLong(0);
11259 previous_is_cased = 1;
11260 cased = 1;
11261 }
11262 else
11263 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011265 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266}
11267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011268PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011269 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011271Return True if all characters in S are whitespace\n\
11272and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273
11274static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011275unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 Py_ssize_t i, length;
11278 int kind;
11279 void *data;
11280
11281 if (PyUnicode_READY(self) == -1)
11282 return NULL;
11283 length = PyUnicode_GET_LENGTH(self);
11284 kind = PyUnicode_KIND(self);
11285 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288 if (length == 1)
11289 return PyBool_FromLong(
11290 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011292 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011293 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 for (i = 0; i < length; i++) {
11297 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011298 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011299 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011301 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302}
11303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011304PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011305 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011306\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011307Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011308and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011309
11310static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011311unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 Py_ssize_t i, length;
11314 int kind;
11315 void *data;
11316
11317 if (PyUnicode_READY(self) == -1)
11318 return NULL;
11319 length = PyUnicode_GET_LENGTH(self);
11320 kind = PyUnicode_KIND(self);
11321 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011323 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 if (length == 1)
11325 return PyBool_FromLong(
11326 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327
11328 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011330 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 for (i = 0; i < length; i++) {
11333 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011334 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011336 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011337}
11338
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011339PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011340 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011341\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011342Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011343and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011344
11345static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011346unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011347{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 int kind;
11349 void *data;
11350 Py_ssize_t len, i;
11351
11352 if (PyUnicode_READY(self) == -1)
11353 return NULL;
11354
11355 kind = PyUnicode_KIND(self);
11356 data = PyUnicode_DATA(self);
11357 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011358
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011359 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 if (len == 1) {
11361 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11362 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11363 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364
11365 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011368
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 for (i = 0; i < len; i++) {
11370 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011371 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011372 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011373 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011374 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011375}
11376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011380Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011381False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382
11383static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011384unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 Py_ssize_t i, length;
11387 int kind;
11388 void *data;
11389
11390 if (PyUnicode_READY(self) == -1)
11391 return NULL;
11392 length = PyUnicode_GET_LENGTH(self);
11393 kind = PyUnicode_KIND(self);
11394 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 if (length == 1)
11398 return PyBool_FromLong(
11399 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011401 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 for (i = 0; i < length; i++) {
11406 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011407 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011409 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410}
11411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011413 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011415Return True if all characters in S are digits\n\
11416and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
11418static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011419unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 Py_ssize_t i, length;
11422 int kind;
11423 void *data;
11424
11425 if (PyUnicode_READY(self) == -1)
11426 return NULL;
11427 length = PyUnicode_GET_LENGTH(self);
11428 kind = PyUnicode_KIND(self);
11429 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 if (length == 1) {
11433 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11434 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11435 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011437 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 for (i = 0; i < length; i++) {
11442 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011445 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446}
11447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011448PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011451Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011452False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453
11454static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011455unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 Py_ssize_t i, length;
11458 int kind;
11459 void *data;
11460
11461 if (PyUnicode_READY(self) == -1)
11462 return NULL;
11463 length = PyUnicode_GET_LENGTH(self);
11464 kind = PyUnicode_KIND(self);
11465 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (length == 1)
11469 return PyBool_FromLong(
11470 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011472 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 for (i = 0; i < length; i++) {
11477 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011480 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481}
11482
Martin v. Löwis47383402007-08-15 07:32:56 +000011483int
11484PyUnicode_IsIdentifier(PyObject *self)
11485{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 int kind;
11487 void *data;
11488 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011489 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 if (PyUnicode_READY(self) == -1) {
11492 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 }
11495
11496 /* Special case for empty strings */
11497 if (PyUnicode_GET_LENGTH(self) == 0)
11498 return 0;
11499 kind = PyUnicode_KIND(self);
11500 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011501
11502 /* PEP 3131 says that the first character must be in
11503 XID_Start and subsequent characters in XID_Continue,
11504 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011505 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011506 letters, digits, underscore). However, given the current
11507 definition of XID_Start and XID_Continue, it is sufficient
11508 to check just for these, except that _ must be allowed
11509 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011511 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011512 return 0;
11513
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011514 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011517 return 1;
11518}
11519
11520PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011521 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011522\n\
11523Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011524to the language definition.\n\
11525\n\
11526Use keyword.iskeyword() to test for reserved identifiers\n\
11527such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011528
11529static PyObject*
11530unicode_isidentifier(PyObject *self)
11531{
11532 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11533}
11534
Georg Brandl559e5d72008-06-11 18:37:52 +000011535PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011536 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011537\n\
11538Return True if all characters in S are considered\n\
11539printable in repr() or S is empty, False otherwise.");
11540
11541static PyObject*
11542unicode_isprintable(PyObject *self)
11543{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544 Py_ssize_t i, length;
11545 int kind;
11546 void *data;
11547
11548 if (PyUnicode_READY(self) == -1)
11549 return NULL;
11550 length = PyUnicode_GET_LENGTH(self);
11551 kind = PyUnicode_KIND(self);
11552 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011553
11554 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 if (length == 1)
11556 return PyBool_FromLong(
11557 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 for (i = 0; i < length; i++) {
11560 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011561 Py_RETURN_FALSE;
11562 }
11563 }
11564 Py_RETURN_TRUE;
11565}
11566
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011567PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011568 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569\n\
11570Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011571iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572
11573static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011574unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011576 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577}
11578
Martin v. Löwis18e16552006-02-15 17:27:45 +000011579static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011580unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011582 if (PyUnicode_READY(self) == -1)
11583 return -1;
11584 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585}
11586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011590Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011591done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
11593static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011594unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011596 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 Py_UCS4 fillchar = ' ';
11598
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011599 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600 return NULL;
11601
Benjamin Petersonbac79492012-01-14 13:34:47 -050011602 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011603 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604
Victor Stinnerc4b49542011-12-11 22:44:26 +010011605 if (PyUnicode_GET_LENGTH(self) >= width)
11606 return unicode_result_unchanged(self);
11607
11608 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609}
11610
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011611PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011612 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011614Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615
11616static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011617unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011619 if (PyUnicode_READY(self) == -1)
11620 return NULL;
11621 if (PyUnicode_IS_ASCII(self))
11622 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011623 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624}
11625
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011626#define LEFTSTRIP 0
11627#define RIGHTSTRIP 1
11628#define BOTHSTRIP 2
11629
11630/* Arrays indexed by above */
11631static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11632
11633#define STRIPNAME(i) (stripformat[i]+3)
11634
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011635/* externally visible for str.strip(unicode) */
11636PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011637_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011638{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 void *data;
11640 int kind;
11641 Py_ssize_t i, j, len;
11642 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011643 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11646 return NULL;
11647
11648 kind = PyUnicode_KIND(self);
11649 data = PyUnicode_DATA(self);
11650 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011651 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11653 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011654 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011655
Benjamin Peterson14339b62009-01-31 16:36:08 +000011656 i = 0;
11657 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011658 while (i < len) {
11659 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11660 if (!BLOOM(sepmask, ch))
11661 break;
11662 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11663 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 i++;
11665 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011666 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011667
Benjamin Peterson14339b62009-01-31 16:36:08 +000011668 j = len;
11669 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011670 j--;
11671 while (j >= i) {
11672 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11673 if (!BLOOM(sepmask, ch))
11674 break;
11675 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11676 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011677 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011678 }
11679
Benjamin Peterson29060642009-01-31 22:14:21 +000011680 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011681 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011682
Victor Stinner7931d9a2011-11-04 00:22:48 +010011683 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684}
11685
11686PyObject*
11687PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11688{
11689 unsigned char *data;
11690 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011691 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692
Victor Stinnerde636f32011-10-01 03:55:54 +020011693 if (PyUnicode_READY(self) == -1)
11694 return NULL;
11695
Victor Stinner684d5fd2012-05-03 02:32:34 +020011696 length = PyUnicode_GET_LENGTH(self);
11697 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011698
Victor Stinner684d5fd2012-05-03 02:32:34 +020011699 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011700 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701
Victor Stinnerde636f32011-10-01 03:55:54 +020011702 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011703 PyErr_SetString(PyExc_IndexError, "string index out of range");
11704 return NULL;
11705 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011706 if (start >= length || end < start)
11707 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011708
Victor Stinner684d5fd2012-05-03 02:32:34 +020011709 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011710 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011711 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011712 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011713 }
11714 else {
11715 kind = PyUnicode_KIND(self);
11716 data = PyUnicode_1BYTE_DATA(self);
11717 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011718 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011719 length);
11720 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722
11723static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011724do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 Py_ssize_t len, i, j;
11727
11728 if (PyUnicode_READY(self) == -1)
11729 return NULL;
11730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011732
Victor Stinnercc7af722013-04-09 22:39:24 +020011733 if (PyUnicode_IS_ASCII(self)) {
11734 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
11735
11736 i = 0;
11737 if (striptype != RIGHTSTRIP) {
11738 while (i < len) {
11739 Py_UCS4 ch = data[i];
11740 if (!_Py_ascii_whitespace[ch])
11741 break;
11742 i++;
11743 }
11744 }
11745
11746 j = len;
11747 if (striptype != LEFTSTRIP) {
11748 j--;
11749 while (j >= i) {
11750 Py_UCS4 ch = data[j];
11751 if (!_Py_ascii_whitespace[ch])
11752 break;
11753 j--;
11754 }
11755 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011756 }
11757 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011758 else {
11759 int kind = PyUnicode_KIND(self);
11760 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011761
Victor Stinnercc7af722013-04-09 22:39:24 +020011762 i = 0;
11763 if (striptype != RIGHTSTRIP) {
11764 while (i < len) {
11765 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11766 if (!Py_UNICODE_ISSPACE(ch))
11767 break;
11768 i++;
11769 }
Victor Stinner9c79e412013-04-09 22:21:08 +020011770 }
Victor Stinnercc7af722013-04-09 22:39:24 +020011771
11772 j = len;
11773 if (striptype != LEFTSTRIP) {
11774 j--;
11775 while (j >= i) {
11776 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11777 if (!Py_UNICODE_ISSPACE(ch))
11778 break;
11779 j--;
11780 }
11781 j++;
11782 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011783 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
Victor Stinner7931d9a2011-11-04 00:22:48 +010011785 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786}
11787
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
11789static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011790do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011791{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011792 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011793
Benjamin Peterson14339b62009-01-31 16:36:08 +000011794 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11795 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796
Benjamin Peterson14339b62009-01-31 16:36:08 +000011797 if (sep != NULL && sep != Py_None) {
11798 if (PyUnicode_Check(sep))
11799 return _PyUnicode_XStrip(self, striptype, sep);
11800 else {
11801 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011802 "%s arg must be None or str",
11803 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011804 return NULL;
11805 }
11806 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807
Benjamin Peterson14339b62009-01-31 16:36:08 +000011808 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011809}
11810
11811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011812PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011814\n\
11815Return a copy of the string S with leading and trailing\n\
11816whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011817If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818
11819static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011820unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011821{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011822 if (PyTuple_GET_SIZE(args) == 0)
11823 return do_strip(self, BOTHSTRIP); /* Common case */
11824 else
11825 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011826}
11827
11828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011829PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011830 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011831\n\
11832Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011833If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834
11835static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011836unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011837{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011838 if (PyTuple_GET_SIZE(args) == 0)
11839 return do_strip(self, LEFTSTRIP); /* Common case */
11840 else
11841 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011842}
11843
11844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011845PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011846 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011847\n\
11848Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011849If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011850
11851static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011852unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011853{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011854 if (PyTuple_GET_SIZE(args) == 0)
11855 return do_strip(self, RIGHTSTRIP); /* Common case */
11856 else
11857 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011858}
11859
11860
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011862unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011864 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866
Serhiy Storchaka05997252013-01-26 12:14:02 +020011867 if (len < 1)
11868 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
Victor Stinnerc4b49542011-12-11 22:44:26 +010011870 /* no repeat, return original string */
11871 if (len == 1)
11872 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011873
Benjamin Petersonbac79492012-01-14 13:34:47 -050011874 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 return NULL;
11876
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011877 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011878 PyErr_SetString(PyExc_OverflowError,
11879 "repeated string is too long");
11880 return NULL;
11881 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011883
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011884 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 if (!u)
11886 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011887 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (PyUnicode_GET_LENGTH(str) == 1) {
11890 const int kind = PyUnicode_KIND(str);
11891 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011892 if (kind == PyUnicode_1BYTE_KIND) {
11893 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011894 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011895 }
11896 else if (kind == PyUnicode_2BYTE_KIND) {
11897 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011898 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011899 ucs2[n] = fill_char;
11900 } else {
11901 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11902 assert(kind == PyUnicode_4BYTE_KIND);
11903 for (n = 0; n < len; ++n)
11904 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 }
11907 else {
11908 /* number of characters copied this far */
11909 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011910 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 char *to = (char *) PyUnicode_DATA(u);
11912 Py_MEMCPY(to, PyUnicode_DATA(str),
11913 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 n = (done <= nchars-done) ? done : nchars-done;
11916 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011917 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011918 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919 }
11920
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011921 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011922 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923}
11924
Alexander Belopolsky40018472011-02-26 01:02:56 +000011925PyObject *
11926PyUnicode_Replace(PyObject *obj,
11927 PyObject *subobj,
11928 PyObject *replobj,
11929 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930{
11931 PyObject *self;
11932 PyObject *str1;
11933 PyObject *str2;
11934 PyObject *result;
11935
11936 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011937 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011938 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011940 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011941 Py_DECREF(self);
11942 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943 }
11944 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011945 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011946 Py_DECREF(self);
11947 Py_DECREF(str1);
11948 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011950 if (PyUnicode_READY(self) == -1 ||
11951 PyUnicode_READY(str1) == -1 ||
11952 PyUnicode_READY(str2) == -1)
11953 result = NULL;
11954 else
11955 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956 Py_DECREF(self);
11957 Py_DECREF(str1);
11958 Py_DECREF(str2);
11959 return result;
11960}
11961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011962PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011963 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964\n\
11965Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011966old replaced by new. If the optional argument count is\n\
11967given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968
11969static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 PyObject *str1;
11973 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011974 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975 PyObject *result;
11976
Martin v. Löwis18e16552006-02-15 17:27:45 +000011977 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011979 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011980 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011982 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 return NULL;
11984 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011985 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011986 Py_DECREF(str1);
11987 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011988 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011989 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11990 result = NULL;
11991 else
11992 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993
11994 Py_DECREF(str1);
11995 Py_DECREF(str2);
11996 return result;
11997}
11998
Alexander Belopolsky40018472011-02-26 01:02:56 +000011999static PyObject *
12000unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012002 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012003 Py_ssize_t isize;
12004 Py_ssize_t osize, squote, dquote, i, o;
12005 Py_UCS4 max, quote;
12006 int ikind, okind;
12007 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012010 return NULL;
12011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 isize = PyUnicode_GET_LENGTH(unicode);
12013 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 /* Compute length of output, quote characters, and
12016 maximum character */
12017 osize = 2; /* quotes */
12018 max = 127;
12019 squote = dquote = 0;
12020 ikind = PyUnicode_KIND(unicode);
12021 for (i = 0; i < isize; i++) {
12022 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12023 switch (ch) {
12024 case '\'': squote++; osize++; break;
12025 case '"': dquote++; osize++; break;
12026 case '\\': case '\t': case '\r': case '\n':
12027 osize += 2; break;
12028 default:
12029 /* Fast-path ASCII */
12030 if (ch < ' ' || ch == 0x7f)
12031 osize += 4; /* \xHH */
12032 else if (ch < 0x7f)
12033 osize++;
12034 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12035 osize++;
12036 max = ch > max ? ch : max;
12037 }
12038 else if (ch < 0x100)
12039 osize += 4; /* \xHH */
12040 else if (ch < 0x10000)
12041 osize += 6; /* \uHHHH */
12042 else
12043 osize += 10; /* \uHHHHHHHH */
12044 }
12045 }
12046
12047 quote = '\'';
12048 if (squote) {
12049 if (dquote)
12050 /* Both squote and dquote present. Use squote,
12051 and escape them */
12052 osize += squote;
12053 else
12054 quote = '"';
12055 }
12056
12057 repr = PyUnicode_New(osize, max);
12058 if (repr == NULL)
12059 return NULL;
12060 okind = PyUnicode_KIND(repr);
12061 odata = PyUnicode_DATA(repr);
12062
12063 PyUnicode_WRITE(okind, odata, 0, quote);
12064 PyUnicode_WRITE(okind, odata, osize-1, quote);
12065
12066 for (i = 0, o = 1; i < isize; i++) {
12067 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012068
12069 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 if ((ch == quote) || (ch == '\\')) {
12071 PyUnicode_WRITE(okind, odata, o++, '\\');
12072 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012073 continue;
12074 }
12075
Benjamin Peterson29060642009-01-31 22:14:21 +000012076 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012077 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012078 PyUnicode_WRITE(okind, odata, o++, '\\');
12079 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012080 }
12081 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 PyUnicode_WRITE(okind, odata, o++, '\\');
12083 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012084 }
12085 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086 PyUnicode_WRITE(okind, odata, o++, '\\');
12087 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012088 }
12089
12090 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012091 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012092 PyUnicode_WRITE(okind, odata, o++, '\\');
12093 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012094 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12095 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012096 }
12097
Georg Brandl559e5d72008-06-11 18:37:52 +000012098 /* Copy ASCII characters as-is */
12099 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012100 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012101 }
12102
Benjamin Peterson29060642009-01-31 22:14:21 +000012103 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012104 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012105 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012106 (categories Z* and C* except ASCII space)
12107 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012109 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012110 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12114 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012115 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012116 /* Map 16-bit characters to '\uxxxx' */
12117 else if (ch <= 0xffff) {
12118 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012119 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12120 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12121 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12122 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012123 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012124 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012125 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012126 PyUnicode_WRITE(okind, odata, o++, 'U');
12127 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12128 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12129 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12130 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012131 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12132 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12133 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12134 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012135 }
12136 }
12137 /* Copy characters as-is */
12138 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012140 }
12141 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012144 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012145 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146}
12147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012148PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012149 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150\n\
12151Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012152such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153arguments start and end are interpreted as in slice notation.\n\
12154\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012155Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156
12157static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012160 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012161 Py_ssize_t start;
12162 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012163 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164
Jesus Ceaac451502011-04-20 17:09:23 +020012165 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12166 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012167 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 if (PyUnicode_READY(self) == -1)
12170 return NULL;
12171 if (PyUnicode_READY(substring) == -1)
12172 return NULL;
12173
Victor Stinner7931d9a2011-11-04 00:22:48 +010012174 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
12176 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178 if (result == -2)
12179 return NULL;
12180
Christian Heimes217cfd12007-12-02 14:31:20 +000012181 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182}
12183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012184PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012185 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012187Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
12189static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012192 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012193 Py_ssize_t start;
12194 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012195 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196
Jesus Ceaac451502011-04-20 17:09:23 +020012197 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12198 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012199 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 if (PyUnicode_READY(self) == -1)
12202 return NULL;
12203 if (PyUnicode_READY(substring) == -1)
12204 return NULL;
12205
Victor Stinner7931d9a2011-11-04 00:22:48 +010012206 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207
12208 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210 if (result == -2)
12211 return NULL;
12212
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213 if (result < 0) {
12214 PyErr_SetString(PyExc_ValueError, "substring not found");
12215 return NULL;
12216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217
Christian Heimes217cfd12007-12-02 14:31:20 +000012218 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219}
12220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012221PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012222 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012224Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012225done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226
12227static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012228unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012230 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231 Py_UCS4 fillchar = ' ';
12232
Victor Stinnere9a29352011-10-01 02:14:59 +020012233 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012234 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012235
Benjamin Petersonbac79492012-01-14 13:34:47 -050012236 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237 return NULL;
12238
Victor Stinnerc4b49542011-12-11 22:44:26 +010012239 if (PyUnicode_GET_LENGTH(self) >= width)
12240 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241
Victor Stinnerc4b49542011-12-11 22:44:26 +010012242 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243}
12244
Alexander Belopolsky40018472011-02-26 01:02:56 +000012245PyObject *
12246PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247{
12248 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012249
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250 s = PyUnicode_FromObject(s);
12251 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012252 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012253 if (sep != NULL) {
12254 sep = PyUnicode_FromObject(sep);
12255 if (sep == NULL) {
12256 Py_DECREF(s);
12257 return NULL;
12258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259 }
12260
Victor Stinner9310abb2011-10-05 00:59:23 +020012261 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262
12263 Py_DECREF(s);
12264 Py_XDECREF(sep);
12265 return result;
12266}
12267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012268PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012269 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270\n\
12271Return a list of the words in S, using sep as the\n\
12272delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012273splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012274whitespace string is a separator and empty strings are\n\
12275removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276
12277static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012278unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012280 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012282 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012284 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12285 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286 return NULL;
12287
12288 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012289 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012291 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012293 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294}
12295
Thomas Wouters477c8d52006-05-27 19:21:47 +000012296PyObject *
12297PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12298{
12299 PyObject* str_obj;
12300 PyObject* sep_obj;
12301 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 int kind1, kind2, kind;
12303 void *buf1 = NULL, *buf2 = NULL;
12304 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012305
12306 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012307 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012308 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012309 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012310 if (!sep_obj) {
12311 Py_DECREF(str_obj);
12312 return NULL;
12313 }
12314 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12315 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012316 Py_DECREF(str_obj);
12317 return NULL;
12318 }
12319
Victor Stinner14f8f022011-10-05 20:58:25 +020012320 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012322 kind = Py_MAX(kind1, kind2);
12323 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012325 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 if (!buf1)
12327 goto onError;
12328 buf2 = PyUnicode_DATA(sep_obj);
12329 if (kind2 != kind)
12330 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12331 if (!buf2)
12332 goto onError;
12333 len1 = PyUnicode_GET_LENGTH(str_obj);
12334 len2 = PyUnicode_GET_LENGTH(sep_obj);
12335
Benjamin Petersonead6b532011-12-20 17:23:42 -060012336 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012338 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12339 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12340 else
12341 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 break;
12343 case PyUnicode_2BYTE_KIND:
12344 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12345 break;
12346 case PyUnicode_4BYTE_KIND:
12347 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12348 break;
12349 default:
12350 assert(0);
12351 out = 0;
12352 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012353
12354 Py_DECREF(sep_obj);
12355 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 if (kind1 != kind)
12357 PyMem_Free(buf1);
12358 if (kind2 != kind)
12359 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012360
12361 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 onError:
12363 Py_DECREF(sep_obj);
12364 Py_DECREF(str_obj);
12365 if (kind1 != kind && buf1)
12366 PyMem_Free(buf1);
12367 if (kind2 != kind && buf2)
12368 PyMem_Free(buf2);
12369 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012370}
12371
12372
12373PyObject *
12374PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12375{
12376 PyObject* str_obj;
12377 PyObject* sep_obj;
12378 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 int kind1, kind2, kind;
12380 void *buf1 = NULL, *buf2 = NULL;
12381 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012382
12383 str_obj = PyUnicode_FromObject(str_in);
12384 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012385 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012386 sep_obj = PyUnicode_FromObject(sep_in);
12387 if (!sep_obj) {
12388 Py_DECREF(str_obj);
12389 return NULL;
12390 }
12391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 kind1 = PyUnicode_KIND(str_in);
12393 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012394 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 buf1 = PyUnicode_DATA(str_in);
12396 if (kind1 != kind)
12397 buf1 = _PyUnicode_AsKind(str_in, kind);
12398 if (!buf1)
12399 goto onError;
12400 buf2 = PyUnicode_DATA(sep_obj);
12401 if (kind2 != kind)
12402 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12403 if (!buf2)
12404 goto onError;
12405 len1 = PyUnicode_GET_LENGTH(str_obj);
12406 len2 = PyUnicode_GET_LENGTH(sep_obj);
12407
Benjamin Petersonead6b532011-12-20 17:23:42 -060012408 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012410 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12411 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12412 else
12413 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 break;
12415 case PyUnicode_2BYTE_KIND:
12416 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12417 break;
12418 case PyUnicode_4BYTE_KIND:
12419 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12420 break;
12421 default:
12422 assert(0);
12423 out = 0;
12424 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012425
12426 Py_DECREF(sep_obj);
12427 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012428 if (kind1 != kind)
12429 PyMem_Free(buf1);
12430 if (kind2 != kind)
12431 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012432
12433 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 onError:
12435 Py_DECREF(sep_obj);
12436 Py_DECREF(str_obj);
12437 if (kind1 != kind && buf1)
12438 PyMem_Free(buf1);
12439 if (kind2 != kind && buf2)
12440 PyMem_Free(buf2);
12441 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012442}
12443
12444PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012445 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012446\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012447Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012448the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012449found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450
12451static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012452unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012453{
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012455}
12456
12457PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012458 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012459\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012460Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012461the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012462separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463
12464static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012465unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012466{
Victor Stinner9310abb2011-10-05 00:59:23 +020012467 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012468}
12469
Alexander Belopolsky40018472011-02-26 01:02:56 +000012470PyObject *
12471PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012472{
12473 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012474
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012475 s = PyUnicode_FromObject(s);
12476 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012477 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012478 if (sep != NULL) {
12479 sep = PyUnicode_FromObject(sep);
12480 if (sep == NULL) {
12481 Py_DECREF(s);
12482 return NULL;
12483 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012484 }
12485
Victor Stinner9310abb2011-10-05 00:59:23 +020012486 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012487
12488 Py_DECREF(s);
12489 Py_XDECREF(sep);
12490 return result;
12491}
12492
12493PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012494 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012495\n\
12496Return a list of the words in S, using sep as the\n\
12497delimiter string, starting at the end of the string and\n\
12498working to the front. If maxsplit is given, at most maxsplit\n\
12499splits are done. If sep is not specified, any whitespace string\n\
12500is a separator.");
12501
12502static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012503unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012504{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012505 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012506 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012507 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012508
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012509 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12510 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012511 return NULL;
12512
12513 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012514 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012515 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012516 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012517 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012518 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012519}
12520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012521PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012522 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523\n\
12524Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012525Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012526is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527
12528static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012529unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012531 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012532 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012534 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12535 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536 return NULL;
12537
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012538 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539}
12540
12541static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012542PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012544 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545}
12546
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012547PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012548 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549\n\
12550Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012551and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552
12553static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012554unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012556 if (PyUnicode_READY(self) == -1)
12557 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012558 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559}
12560
Georg Brandlceee0772007-11-27 23:48:05 +000012561PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012562 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012563\n\
12564Return a translation table usable for str.translate().\n\
12565If there is only one argument, it must be a dictionary mapping Unicode\n\
12566ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012567Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012568If there are two arguments, they must be strings of equal length, and\n\
12569in the resulting dictionary, each character in x will be mapped to the\n\
12570character at the same position in y. If there is a third argument, it\n\
12571must be a string, whose characters will be mapped to None in the result.");
12572
12573static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012574unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012575{
12576 PyObject *x, *y = NULL, *z = NULL;
12577 PyObject *new = NULL, *key, *value;
12578 Py_ssize_t i = 0;
12579 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012580
Georg Brandlceee0772007-11-27 23:48:05 +000012581 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12582 return NULL;
12583 new = PyDict_New();
12584 if (!new)
12585 return NULL;
12586 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 int x_kind, y_kind, z_kind;
12588 void *x_data, *y_data, *z_data;
12589
Georg Brandlceee0772007-11-27 23:48:05 +000012590 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012591 if (!PyUnicode_Check(x)) {
12592 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12593 "be a string if there is a second argument");
12594 goto err;
12595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012596 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012597 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12598 "arguments must have equal length");
12599 goto err;
12600 }
12601 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602 x_kind = PyUnicode_KIND(x);
12603 y_kind = PyUnicode_KIND(y);
12604 x_data = PyUnicode_DATA(x);
12605 y_data = PyUnicode_DATA(y);
12606 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12607 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012608 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012609 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012610 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012611 if (!value) {
12612 Py_DECREF(key);
12613 goto err;
12614 }
Georg Brandlceee0772007-11-27 23:48:05 +000012615 res = PyDict_SetItem(new, key, value);
12616 Py_DECREF(key);
12617 Py_DECREF(value);
12618 if (res < 0)
12619 goto err;
12620 }
12621 /* create entries for deleting chars in z */
12622 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 z_kind = PyUnicode_KIND(z);
12624 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012625 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012627 if (!key)
12628 goto err;
12629 res = PyDict_SetItem(new, key, Py_None);
12630 Py_DECREF(key);
12631 if (res < 0)
12632 goto err;
12633 }
12634 }
12635 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 int kind;
12637 void *data;
12638
Georg Brandlceee0772007-11-27 23:48:05 +000012639 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012640 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012641 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12642 "to maketrans it must be a dict");
12643 goto err;
12644 }
12645 /* copy entries into the new dict, converting string keys to int keys */
12646 while (PyDict_Next(x, &i, &key, &value)) {
12647 if (PyUnicode_Check(key)) {
12648 /* convert string keys to integer keys */
12649 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012650 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012651 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12652 "table must be of length 1");
12653 goto err;
12654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 kind = PyUnicode_KIND(key);
12656 data = PyUnicode_DATA(key);
12657 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012658 if (!newkey)
12659 goto err;
12660 res = PyDict_SetItem(new, newkey, value);
12661 Py_DECREF(newkey);
12662 if (res < 0)
12663 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012664 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012665 /* just keep integer keys */
12666 if (PyDict_SetItem(new, key, value) < 0)
12667 goto err;
12668 } else {
12669 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12670 "be strings or integers");
12671 goto err;
12672 }
12673 }
12674 }
12675 return new;
12676 err:
12677 Py_DECREF(new);
12678 return NULL;
12679}
12680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012681PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012682 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683\n\
12684Return a copy of the string S, where all characters have been mapped\n\
12685through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012686Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012687Unmapped characters are left untouched. Characters mapped to None\n\
12688are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689
12690static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012693 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694}
12695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012696PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012697 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012699Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700
12701static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012702unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012704 if (PyUnicode_READY(self) == -1)
12705 return NULL;
12706 if (PyUnicode_IS_ASCII(self))
12707 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012708 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709}
12710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012711PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012712 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012714Pad a numeric string S with zeros on the left, to fill a field\n\
12715of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716
12717static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012718unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012720 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012721 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012722 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 int kind;
12724 void *data;
12725 Py_UCS4 chr;
12726
Martin v. Löwis18e16552006-02-15 17:27:45 +000012727 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728 return NULL;
12729
Benjamin Petersonbac79492012-01-14 13:34:47 -050012730 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012731 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732
Victor Stinnerc4b49542011-12-11 22:44:26 +010012733 if (PyUnicode_GET_LENGTH(self) >= width)
12734 return unicode_result_unchanged(self);
12735
12736 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737
12738 u = pad(self, fill, 0, '0');
12739
Walter Dörwald068325e2002-04-15 13:36:47 +000012740 if (u == NULL)
12741 return NULL;
12742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 kind = PyUnicode_KIND(u);
12744 data = PyUnicode_DATA(u);
12745 chr = PyUnicode_READ(kind, data, fill);
12746
12747 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012748 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012749 PyUnicode_WRITE(kind, data, 0, chr);
12750 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751 }
12752
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012753 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012754 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012756
12757#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012758static PyObject *
12759unicode__decimal2ascii(PyObject *self)
12760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012762}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763#endif
12764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012765PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012768Return True if S starts with the specified prefix, False otherwise.\n\
12769With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012770With optional end, stop comparing S at that position.\n\
12771prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772
12773static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012774unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012775 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012777 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012778 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012779 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012780 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012781 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782
Jesus Ceaac451502011-04-20 17:09:23 +020012783 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012784 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012785 if (PyTuple_Check(subobj)) {
12786 Py_ssize_t i;
12787 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012788 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012789 if (substring == NULL)
12790 return NULL;
12791 result = tailmatch(self, substring, start, end, -1);
12792 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012793 if (result == -1)
12794 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012795 if (result) {
12796 Py_RETURN_TRUE;
12797 }
12798 }
12799 /* nothing matched */
12800 Py_RETURN_FALSE;
12801 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012802 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012803 if (substring == NULL) {
12804 if (PyErr_ExceptionMatches(PyExc_TypeError))
12805 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12806 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012807 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012808 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012809 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012811 if (result == -1)
12812 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012813 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814}
12815
12816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012817PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012818 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012820Return True if S ends with the specified suffix, False otherwise.\n\
12821With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012822With optional end, stop comparing S at that position.\n\
12823suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824
12825static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012826unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012829 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012830 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012831 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012832 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012833 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834
Jesus Ceaac451502011-04-20 17:09:23 +020012835 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012836 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012837 if (PyTuple_Check(subobj)) {
12838 Py_ssize_t i;
12839 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012840 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012841 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012842 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012843 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012844 result = tailmatch(self, substring, start, end, +1);
12845 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010012846 if (result == -1)
12847 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012848 if (result) {
12849 Py_RETURN_TRUE;
12850 }
12851 }
12852 Py_RETURN_FALSE;
12853 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012854 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012855 if (substring == NULL) {
12856 if (PyErr_ExceptionMatches(PyExc_TypeError))
12857 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12858 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012859 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012860 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012861 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010012862 if (result == -1)
12863 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012864 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012865 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866}
12867
Victor Stinner202fdca2012-05-07 12:47:02 +020012868Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012869_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012870{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012871 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012872 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12873 writer->data = PyUnicode_DATA(writer->buffer);
12874 writer->kind = PyUnicode_KIND(writer->buffer);
12875}
12876
Victor Stinnerd3f08822012-05-29 12:57:52 +020012877void
12878_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012879{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012880 memset(writer, 0, sizeof(*writer));
12881#ifdef Py_DEBUG
12882 writer->kind = 5; /* invalid kind */
12883#endif
12884 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012885 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012886}
12887
Victor Stinnerd3f08822012-05-29 12:57:52 +020012888int
12889_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12890 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012891{
12892 Py_ssize_t newlen;
12893 PyObject *newbuffer;
12894
Victor Stinnerd3f08822012-05-29 12:57:52 +020012895 assert(length > 0);
12896
Victor Stinner202fdca2012-05-07 12:47:02 +020012897 if (length > PY_SSIZE_T_MAX - writer->pos) {
12898 PyErr_NoMemory();
12899 return -1;
12900 }
12901 newlen = writer->pos + length;
12902
Victor Stinnerd3f08822012-05-29 12:57:52 +020012903 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012904 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012905 /* overallocate 25% to limit the number of resize */
12906 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12907 newlen += newlen / 4;
12908 if (newlen < writer->min_length)
12909 newlen = writer->min_length;
12910 }
12911 writer->buffer = PyUnicode_New(newlen, maxchar);
12912 if (writer->buffer == NULL)
12913 return -1;
12914 _PyUnicodeWriter_Update(writer);
12915 return 0;
12916 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012917
Victor Stinnerd3f08822012-05-29 12:57:52 +020012918 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012919 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012920 /* overallocate 25% to limit the number of resize */
12921 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12922 newlen += newlen / 4;
12923 if (newlen < writer->min_length)
12924 newlen = writer->min_length;
12925 }
12926
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012927 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012928 /* resize + widen */
12929 newbuffer = PyUnicode_New(newlen, maxchar);
12930 if (newbuffer == NULL)
12931 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012932 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12933 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012934 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012935 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012936 }
12937 else {
12938 newbuffer = resize_compact(writer->buffer, newlen);
12939 if (newbuffer == NULL)
12940 return -1;
12941 }
12942 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012943 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012944 }
12945 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012946 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012947 newbuffer = PyUnicode_New(writer->size, maxchar);
12948 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012949 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012950 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12951 writer->buffer, 0, writer->pos);
12952 Py_DECREF(writer->buffer);
12953 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012954 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012955 }
12956 return 0;
12957}
12958
Victor Stinnerd3f08822012-05-29 12:57:52 +020012959int
12960_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12961{
12962 Py_UCS4 maxchar;
12963 Py_ssize_t len;
12964
12965 if (PyUnicode_READY(str) == -1)
12966 return -1;
12967 len = PyUnicode_GET_LENGTH(str);
12968 if (len == 0)
12969 return 0;
12970 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12971 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012972 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012973 Py_INCREF(str);
12974 writer->buffer = str;
12975 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012976 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012977 writer->size = 0;
12978 writer->pos += len;
12979 return 0;
12980 }
12981 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12982 return -1;
12983 }
12984 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12985 str, 0, len);
12986 writer->pos += len;
12987 return 0;
12988}
12989
Victor Stinnere215d962012-10-06 23:03:36 +020012990int
Victor Stinnercfc4c132013-04-03 01:48:39 +020012991_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
12992 Py_ssize_t start, Py_ssize_t end)
12993{
12994 Py_UCS4 maxchar;
12995 Py_ssize_t len;
12996
12997 if (PyUnicode_READY(str) == -1)
12998 return -1;
12999
13000 assert(0 <= start);
13001 assert(end <= PyUnicode_GET_LENGTH(str));
13002 assert(start <= end);
13003
13004 if (end == 0)
13005 return 0;
13006
13007 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13008 return _PyUnicodeWriter_WriteStr(writer, str);
13009
13010 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13011 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13012 else
13013 maxchar = writer->maxchar;
13014 len = end - start;
13015
13016 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13017 return -1;
13018
13019 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13020 str, start, len);
13021 writer->pos += len;
13022 return 0;
13023}
13024
13025int
Victor Stinnere215d962012-10-06 23:03:36 +020013026_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
13027{
13028 Py_UCS4 maxchar;
13029
13030 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13031 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13032 return -1;
13033 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13034 writer->pos += len;
13035 return 0;
13036}
13037
Victor Stinnerd3f08822012-05-29 12:57:52 +020013038PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013039_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013040{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013041 if (writer->pos == 0) {
13042 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013043 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013044 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013045 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020013046 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
13047 return writer->buffer;
13048 }
13049 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13050 PyObject *newbuffer;
13051 newbuffer = resize_compact(writer->buffer, writer->pos);
13052 if (newbuffer == NULL) {
13053 Py_DECREF(writer->buffer);
13054 return NULL;
13055 }
13056 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013057 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020013058 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner2cb16aa2013-03-06 19:28:37 +010013059 return unicode_result_ready(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013060}
13061
Victor Stinnerd3f08822012-05-29 12:57:52 +020013062void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013063_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013064{
13065 Py_CLEAR(writer->buffer);
13066}
13067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013068#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013069
13070PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013071 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013072\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013073Return a formatted version of S, using substitutions from args and kwargs.\n\
13074The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013075
Eric Smith27bbca62010-11-04 17:06:58 +000013076PyDoc_STRVAR(format_map__doc__,
13077 "S.format_map(mapping) -> str\n\
13078\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013079Return a formatted version of S, using substitutions from mapping.\n\
13080The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013081
Eric Smith4a7d76d2008-05-30 18:10:19 +000013082static PyObject *
13083unicode__format__(PyObject* self, PyObject* args)
13084{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013085 PyObject *format_spec;
13086 _PyUnicodeWriter writer;
13087 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013088
13089 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13090 return NULL;
13091
Victor Stinnerd3f08822012-05-29 12:57:52 +020013092 if (PyUnicode_READY(self) == -1)
13093 return NULL;
13094 _PyUnicodeWriter_Init(&writer, 0);
13095 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13096 self, format_spec, 0,
13097 PyUnicode_GET_LENGTH(format_spec));
13098 if (ret == -1) {
13099 _PyUnicodeWriter_Dealloc(&writer);
13100 return NULL;
13101 }
13102 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013103}
13104
Eric Smith8c663262007-08-25 02:26:07 +000013105PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013106 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013107\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013108Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013109
13110static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013111unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013112{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013113 Py_ssize_t size;
13114
13115 /* If it's a compact object, account for base structure +
13116 character data. */
13117 if (PyUnicode_IS_COMPACT_ASCII(v))
13118 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13119 else if (PyUnicode_IS_COMPACT(v))
13120 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013121 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013122 else {
13123 /* If it is a two-block object, account for base object, and
13124 for character block if present. */
13125 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013126 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013128 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 }
13130 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013131 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013132 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013134 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013135 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136
13137 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013138}
13139
13140PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013141 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013142
13143static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013144unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013145{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013146 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013147 if (!copy)
13148 return NULL;
13149 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013150}
13151
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013153 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013154 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013155 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13156 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013157 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13158 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013159 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013160 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13161 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13162 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13163 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13164 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013165 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013166 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13167 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13168 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013169 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013170 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13171 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13172 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013173 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013174 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013175 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013176 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013177 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13178 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13179 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13180 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13181 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13182 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13183 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13184 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13185 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13186 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13187 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13188 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13189 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13190 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013191 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013192 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013193 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013194 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013195 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013196 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013197 {"maketrans", (PyCFunction) unicode_maketrans,
13198 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013199 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013200#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013201 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013202 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203#endif
13204
Benjamin Peterson14339b62009-01-31 16:36:08 +000013205 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206 {NULL, NULL}
13207};
13208
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013209static PyObject *
13210unicode_mod(PyObject *v, PyObject *w)
13211{
Brian Curtindfc80e32011-08-10 20:28:54 -050013212 if (!PyUnicode_Check(v))
13213 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013215}
13216
13217static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013218 0, /*nb_add*/
13219 0, /*nb_subtract*/
13220 0, /*nb_multiply*/
13221 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013222};
13223
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013225 (lenfunc) unicode_length, /* sq_length */
13226 PyUnicode_Concat, /* sq_concat */
13227 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13228 (ssizeargfunc) unicode_getitem, /* sq_item */
13229 0, /* sq_slice */
13230 0, /* sq_ass_item */
13231 0, /* sq_ass_slice */
13232 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233};
13234
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013235static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013236unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013237{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013238 if (PyUnicode_READY(self) == -1)
13239 return NULL;
13240
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013241 if (PyIndex_Check(item)) {
13242 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013243 if (i == -1 && PyErr_Occurred())
13244 return NULL;
13245 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013246 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013247 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013248 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013249 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013250 PyObject *result;
13251 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013252 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013253 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013254
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013255 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013257 return NULL;
13258 }
13259
13260 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013261 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013263 slicelength == PyUnicode_GET_LENGTH(self)) {
13264 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013265 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013266 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013267 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013268 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013269 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013270 src_kind = PyUnicode_KIND(self);
13271 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013272 if (!PyUnicode_IS_ASCII(self)) {
13273 kind_limit = kind_maxchar_limit(src_kind);
13274 max_char = 0;
13275 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13276 ch = PyUnicode_READ(src_kind, src_data, cur);
13277 if (ch > max_char) {
13278 max_char = ch;
13279 if (max_char >= kind_limit)
13280 break;
13281 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013282 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013283 }
Victor Stinner55c99112011-10-13 01:17:06 +020013284 else
13285 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013286 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013287 if (result == NULL)
13288 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013289 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013290 dest_data = PyUnicode_DATA(result);
13291
13292 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013293 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13294 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013295 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013296 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013297 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013298 } else {
13299 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13300 return NULL;
13301 }
13302}
13303
13304static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013305 (lenfunc)unicode_length, /* mp_length */
13306 (binaryfunc)unicode_subscript, /* mp_subscript */
13307 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013308};
13309
Guido van Rossumd57fd912000-03-10 22:53:23 +000013310
Guido van Rossumd57fd912000-03-10 22:53:23 +000013311/* Helpers for PyUnicode_Format() */
13312
Victor Stinnera47082312012-10-04 02:19:54 +020013313struct unicode_formatter_t {
13314 PyObject *args;
13315 int args_owned;
13316 Py_ssize_t arglen, argidx;
13317 PyObject *dict;
13318
13319 enum PyUnicode_Kind fmtkind;
13320 Py_ssize_t fmtcnt, fmtpos;
13321 void *fmtdata;
13322 PyObject *fmtstr;
13323
13324 _PyUnicodeWriter writer;
13325};
13326
13327struct unicode_format_arg_t {
13328 Py_UCS4 ch;
13329 int flags;
13330 Py_ssize_t width;
13331 int prec;
13332 int sign;
13333};
13334
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013336unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337{
Victor Stinnera47082312012-10-04 02:19:54 +020013338 Py_ssize_t argidx = ctx->argidx;
13339
13340 if (argidx < ctx->arglen) {
13341 ctx->argidx++;
13342 if (ctx->arglen < 0)
13343 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 else
Victor Stinnera47082312012-10-04 02:19:54 +020013345 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346 }
13347 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349 return NULL;
13350}
13351
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013352/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353
Victor Stinnera47082312012-10-04 02:19:54 +020013354/* Format a float into the writer if the writer is not NULL, or into *p_output
13355 otherwise.
13356
13357 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013358static int
Victor Stinnera47082312012-10-04 02:19:54 +020013359formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13360 PyObject **p_output,
13361 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013362{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013363 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013365 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013366 int prec;
13367 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013368
Guido van Rossumd57fd912000-03-10 22:53:23 +000013369 x = PyFloat_AsDouble(v);
13370 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013371 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013372
Victor Stinnera47082312012-10-04 02:19:54 +020013373 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013374 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013375 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013376
Victor Stinnera47082312012-10-04 02:19:54 +020013377 if (arg->flags & F_ALT)
13378 dtoa_flags = Py_DTSF_ALT;
13379 else
13380 dtoa_flags = 0;
13381 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013382 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013383 return -1;
13384 len = strlen(p);
13385 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013386 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13387 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013388 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013389 }
Victor Stinner184252a2012-06-16 02:57:41 +020013390 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013391 writer->pos += len;
13392 }
13393 else
13394 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013395 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013396 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013397}
13398
Victor Stinnerd0880d52012-04-27 23:40:13 +020013399/* formatlong() emulates the format codes d, u, o, x and X, and
13400 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13401 * Python's regular ints.
13402 * Return value: a new PyUnicodeObject*, or NULL if error.
13403 * The output string is of the form
13404 * "-"? ("0x" | "0X")? digit+
13405 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13406 * set in flags. The case of hex digits will be correct,
13407 * There will be at least prec digits, zero-filled on the left if
13408 * necessary to get that many.
13409 * val object to be converted
13410 * flags bitmask of format flags; only F_ALT is looked at
13411 * prec minimum number of digits; 0-fill on left if needed
13412 * type a character in [duoxX]; u acts the same as d
13413 *
13414 * CAUTION: o, x and X conversions on regular ints can never
13415 * produce a '-' sign, but can for Python's unbounded ints.
13416 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013417static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013418formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013419{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013420 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013421 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013422 Py_ssize_t i;
13423 int sign; /* 1 if '-', else 0 */
13424 int len; /* number of characters */
13425 Py_ssize_t llen;
13426 int numdigits; /* len == numnondigits + numdigits */
13427 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013428 int prec = arg->prec;
13429 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013430
Victor Stinnerd0880d52012-04-27 23:40:13 +020013431 /* Avoid exceeding SSIZE_T_MAX */
13432 if (prec > INT_MAX-3) {
13433 PyErr_SetString(PyExc_OverflowError,
13434 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013435 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013436 }
13437
13438 assert(PyLong_Check(val));
13439
13440 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013441 default:
13442 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013443 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013444 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013445 case 'u':
13446 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013447 if (PyBool_Check(val))
13448 result = PyNumber_ToBase(val, 10);
13449 else
13450 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013451 break;
13452 case 'o':
13453 numnondigits = 2;
13454 result = PyNumber_ToBase(val, 8);
13455 break;
13456 case 'x':
13457 case 'X':
13458 numnondigits = 2;
13459 result = PyNumber_ToBase(val, 16);
13460 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013461 }
13462 if (!result)
13463 return NULL;
13464
13465 assert(unicode_modifiable(result));
13466 assert(PyUnicode_IS_READY(result));
13467 assert(PyUnicode_IS_ASCII(result));
13468
13469 /* To modify the string in-place, there can only be one reference. */
13470 if (Py_REFCNT(result) != 1) {
13471 PyErr_BadInternalCall();
13472 return NULL;
13473 }
13474 buf = PyUnicode_DATA(result);
13475 llen = PyUnicode_GET_LENGTH(result);
13476 if (llen > INT_MAX) {
13477 PyErr_SetString(PyExc_ValueError,
13478 "string too large in _PyBytes_FormatLong");
13479 return NULL;
13480 }
13481 len = (int)llen;
13482 sign = buf[0] == '-';
13483 numnondigits += sign;
13484 numdigits = len - numnondigits;
13485 assert(numdigits > 0);
13486
13487 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013488 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013489 (type == 'o' || type == 'x' || type == 'X'))) {
13490 assert(buf[sign] == '0');
13491 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13492 buf[sign+1] == 'o');
13493 numnondigits -= 2;
13494 buf += 2;
13495 len -= 2;
13496 if (sign)
13497 buf[0] = '-';
13498 assert(len == numnondigits + numdigits);
13499 assert(numdigits > 0);
13500 }
13501
13502 /* Fill with leading zeroes to meet minimum width. */
13503 if (prec > numdigits) {
13504 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13505 numnondigits + prec);
13506 char *b1;
13507 if (!r1) {
13508 Py_DECREF(result);
13509 return NULL;
13510 }
13511 b1 = PyBytes_AS_STRING(r1);
13512 for (i = 0; i < numnondigits; ++i)
13513 *b1++ = *buf++;
13514 for (i = 0; i < prec - numdigits; i++)
13515 *b1++ = '0';
13516 for (i = 0; i < numdigits; i++)
13517 *b1++ = *buf++;
13518 *b1 = '\0';
13519 Py_DECREF(result);
13520 result = r1;
13521 buf = PyBytes_AS_STRING(result);
13522 len = numnondigits + prec;
13523 }
13524
13525 /* Fix up case for hex conversions. */
13526 if (type == 'X') {
13527 /* Need to convert all lower case letters to upper case.
13528 and need to convert 0x to 0X (and -0x to -0X). */
13529 for (i = 0; i < len; i++)
13530 if (buf[i] >= 'a' && buf[i] <= 'x')
13531 buf[i] -= 'a'-'A';
13532 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013533 if (!PyUnicode_Check(result)
13534 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013535 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013536 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013537 Py_DECREF(result);
13538 result = unicode;
13539 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013540 else if (len != PyUnicode_GET_LENGTH(result)) {
13541 if (PyUnicode_Resize(&result, len) < 0)
13542 Py_CLEAR(result);
13543 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013544 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013545}
13546
Victor Stinner621ef3d2012-10-02 00:33:47 +020013547/* Format an integer.
13548 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013549 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013550 * -1 and raise an exception on error */
13551static int
Victor Stinnera47082312012-10-04 02:19:54 +020013552mainformatlong(PyObject *v,
13553 struct unicode_format_arg_t *arg,
13554 PyObject **p_output,
13555 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013556{
13557 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013558 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013559
13560 if (!PyNumber_Check(v))
13561 goto wrongtype;
13562
13563 if (!PyLong_Check(v)) {
13564 iobj = PyNumber_Long(v);
13565 if (iobj == NULL) {
13566 if (PyErr_ExceptionMatches(PyExc_TypeError))
13567 goto wrongtype;
13568 return -1;
13569 }
13570 assert(PyLong_Check(iobj));
13571 }
13572 else {
13573 iobj = v;
13574 Py_INCREF(iobj);
13575 }
13576
13577 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013578 && arg->width == -1 && arg->prec == -1
13579 && !(arg->flags & (F_SIGN | F_BLANK))
13580 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013581 {
13582 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013583 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013584 int base;
13585
Victor Stinnera47082312012-10-04 02:19:54 +020013586 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013587 {
13588 default:
13589 assert(0 && "'type' not in [diuoxX]");
13590 case 'd':
13591 case 'i':
13592 case 'u':
13593 base = 10;
13594 break;
13595 case 'o':
13596 base = 8;
13597 break;
13598 case 'x':
13599 case 'X':
13600 base = 16;
13601 break;
13602 }
13603
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013604 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13605 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013606 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013607 }
13608 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013609 return 1;
13610 }
13611
Victor Stinnera47082312012-10-04 02:19:54 +020013612 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013613 Py_DECREF(iobj);
13614 if (res == NULL)
13615 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013616 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013617 return 0;
13618
13619wrongtype:
13620 PyErr_Format(PyExc_TypeError,
13621 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013622 "not %.200s",
13623 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013624 return -1;
13625}
13626
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013627static Py_UCS4
13628formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013629{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013630 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013631 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013632 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013633 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 goto onError;
13636 }
13637 else {
13638 /* Integer input truncated to a character */
13639 long x;
13640 x = PyLong_AsLong(v);
13641 if (x == -1 && PyErr_Occurred())
13642 goto onError;
13643
Victor Stinner8faf8212011-12-08 22:14:11 +010013644 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 PyErr_SetString(PyExc_OverflowError,
13646 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013647 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013648 }
13649
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013650 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013651 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013652
Benjamin Peterson29060642009-01-31 22:14:21 +000013653 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013654 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013656 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013657}
13658
Victor Stinnera47082312012-10-04 02:19:54 +020013659/* Parse options of an argument: flags, width, precision.
13660 Handle also "%(name)" syntax.
13661
13662 Return 0 if the argument has been formatted into arg->str.
13663 Return 1 if the argument has been written into ctx->writer,
13664 Raise an exception and return -1 on error. */
13665static int
13666unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13667 struct unicode_format_arg_t *arg)
13668{
13669#define FORMAT_READ(ctx) \
13670 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13671
13672 PyObject *v;
13673
Victor Stinnera47082312012-10-04 02:19:54 +020013674 if (arg->ch == '(') {
13675 /* Get argument value from a dictionary. Example: "%(name)s". */
13676 Py_ssize_t keystart;
13677 Py_ssize_t keylen;
13678 PyObject *key;
13679 int pcount = 1;
13680
13681 if (ctx->dict == NULL) {
13682 PyErr_SetString(PyExc_TypeError,
13683 "format requires a mapping");
13684 return -1;
13685 }
13686 ++ctx->fmtpos;
13687 --ctx->fmtcnt;
13688 keystart = ctx->fmtpos;
13689 /* Skip over balanced parentheses */
13690 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13691 arg->ch = FORMAT_READ(ctx);
13692 if (arg->ch == ')')
13693 --pcount;
13694 else if (arg->ch == '(')
13695 ++pcount;
13696 ctx->fmtpos++;
13697 }
13698 keylen = ctx->fmtpos - keystart - 1;
13699 if (ctx->fmtcnt < 0 || pcount > 0) {
13700 PyErr_SetString(PyExc_ValueError,
13701 "incomplete format key");
13702 return -1;
13703 }
13704 key = PyUnicode_Substring(ctx->fmtstr,
13705 keystart, keystart + keylen);
13706 if (key == NULL)
13707 return -1;
13708 if (ctx->args_owned) {
13709 Py_DECREF(ctx->args);
13710 ctx->args_owned = 0;
13711 }
13712 ctx->args = PyObject_GetItem(ctx->dict, key);
13713 Py_DECREF(key);
13714 if (ctx->args == NULL)
13715 return -1;
13716 ctx->args_owned = 1;
13717 ctx->arglen = -1;
13718 ctx->argidx = -2;
13719 }
13720
13721 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020013722 while (--ctx->fmtcnt >= 0) {
13723 arg->ch = FORMAT_READ(ctx);
13724 ctx->fmtpos++;
13725 switch (arg->ch) {
13726 case '-': arg->flags |= F_LJUST; continue;
13727 case '+': arg->flags |= F_SIGN; continue;
13728 case ' ': arg->flags |= F_BLANK; continue;
13729 case '#': arg->flags |= F_ALT; continue;
13730 case '0': arg->flags |= F_ZERO; continue;
13731 }
13732 break;
13733 }
13734
13735 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020013736 if (arg->ch == '*') {
13737 v = unicode_format_getnextarg(ctx);
13738 if (v == NULL)
13739 return -1;
13740 if (!PyLong_Check(v)) {
13741 PyErr_SetString(PyExc_TypeError,
13742 "* wants int");
13743 return -1;
13744 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013745 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013746 if (arg->width == -1 && PyErr_Occurred())
13747 return -1;
13748 if (arg->width < 0) {
13749 arg->flags |= F_LJUST;
13750 arg->width = -arg->width;
13751 }
13752 if (--ctx->fmtcnt >= 0) {
13753 arg->ch = FORMAT_READ(ctx);
13754 ctx->fmtpos++;
13755 }
13756 }
13757 else if (arg->ch >= '0' && arg->ch <= '9') {
13758 arg->width = arg->ch - '0';
13759 while (--ctx->fmtcnt >= 0) {
13760 arg->ch = FORMAT_READ(ctx);
13761 ctx->fmtpos++;
13762 if (arg->ch < '0' || arg->ch > '9')
13763 break;
13764 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13765 mixing signed and unsigned comparison. Since arg->ch is between
13766 '0' and '9', casting to int is safe. */
13767 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13768 PyErr_SetString(PyExc_ValueError,
13769 "width too big");
13770 return -1;
13771 }
13772 arg->width = arg->width*10 + (arg->ch - '0');
13773 }
13774 }
13775
13776 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020013777 if (arg->ch == '.') {
13778 arg->prec = 0;
13779 if (--ctx->fmtcnt >= 0) {
13780 arg->ch = FORMAT_READ(ctx);
13781 ctx->fmtpos++;
13782 }
13783 if (arg->ch == '*') {
13784 v = unicode_format_getnextarg(ctx);
13785 if (v == NULL)
13786 return -1;
13787 if (!PyLong_Check(v)) {
13788 PyErr_SetString(PyExc_TypeError,
13789 "* wants int");
13790 return -1;
13791 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020013792 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020013793 if (arg->prec == -1 && PyErr_Occurred())
13794 return -1;
13795 if (arg->prec < 0)
13796 arg->prec = 0;
13797 if (--ctx->fmtcnt >= 0) {
13798 arg->ch = FORMAT_READ(ctx);
13799 ctx->fmtpos++;
13800 }
13801 }
13802 else if (arg->ch >= '0' && arg->ch <= '9') {
13803 arg->prec = arg->ch - '0';
13804 while (--ctx->fmtcnt >= 0) {
13805 arg->ch = FORMAT_READ(ctx);
13806 ctx->fmtpos++;
13807 if (arg->ch < '0' || arg->ch > '9')
13808 break;
13809 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13810 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013811 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013812 return -1;
13813 }
13814 arg->prec = arg->prec*10 + (arg->ch - '0');
13815 }
13816 }
13817 }
13818
13819 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13820 if (ctx->fmtcnt >= 0) {
13821 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13822 if (--ctx->fmtcnt >= 0) {
13823 arg->ch = FORMAT_READ(ctx);
13824 ctx->fmtpos++;
13825 }
13826 }
13827 }
13828 if (ctx->fmtcnt < 0) {
13829 PyErr_SetString(PyExc_ValueError,
13830 "incomplete format");
13831 return -1;
13832 }
13833 return 0;
13834
13835#undef FORMAT_READ
13836}
13837
13838/* Format one argument. Supported conversion specifiers:
13839
13840 - "s", "r", "a": any type
13841 - "i", "d", "u", "o", "x", "X": int
13842 - "e", "E", "f", "F", "g", "G": float
13843 - "c": int or str (1 character)
13844
Victor Stinner8dbd4212012-12-04 09:30:24 +010013845 When possible, the output is written directly into the Unicode writer
13846 (ctx->writer). A string is created when padding is required.
13847
Victor Stinnera47082312012-10-04 02:19:54 +020013848 Return 0 if the argument has been formatted into *p_str,
13849 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010013850 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020013851static int
13852unicode_format_arg_format(struct unicode_formatter_t *ctx,
13853 struct unicode_format_arg_t *arg,
13854 PyObject **p_str)
13855{
13856 PyObject *v;
13857 _PyUnicodeWriter *writer = &ctx->writer;
13858
13859 if (ctx->fmtcnt == 0)
13860 ctx->writer.overallocate = 0;
13861
13862 if (arg->ch == '%') {
13863 if (_PyUnicodeWriter_Prepare(writer, 1, '%') == -1)
13864 return -1;
13865 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '%');
13866 writer->pos += 1;
13867 return 1;
13868 }
13869
13870 v = unicode_format_getnextarg(ctx);
13871 if (v == NULL)
13872 return -1;
13873
Victor Stinnera47082312012-10-04 02:19:54 +020013874
13875 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020013876 case 's':
13877 case 'r':
13878 case 'a':
13879 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
13880 /* Fast path */
13881 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
13882 return -1;
13883 return 1;
13884 }
13885
13886 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
13887 *p_str = v;
13888 Py_INCREF(*p_str);
13889 }
13890 else {
13891 if (arg->ch == 's')
13892 *p_str = PyObject_Str(v);
13893 else if (arg->ch == 'r')
13894 *p_str = PyObject_Repr(v);
13895 else
13896 *p_str = PyObject_ASCII(v);
13897 }
13898 break;
13899
13900 case 'i':
13901 case 'd':
13902 case 'u':
13903 case 'o':
13904 case 'x':
13905 case 'X':
13906 {
13907 int ret = mainformatlong(v, arg, p_str, writer);
13908 if (ret != 0)
13909 return ret;
13910 arg->sign = 1;
13911 break;
13912 }
13913
13914 case 'e':
13915 case 'E':
13916 case 'f':
13917 case 'F':
13918 case 'g':
13919 case 'G':
13920 if (arg->width == -1 && arg->prec == -1
13921 && !(arg->flags & (F_SIGN | F_BLANK)))
13922 {
13923 /* Fast path */
13924 if (formatfloat(v, arg, NULL, writer) == -1)
13925 return -1;
13926 return 1;
13927 }
13928
13929 arg->sign = 1;
13930 if (formatfloat(v, arg, p_str, NULL) == -1)
13931 return -1;
13932 break;
13933
13934 case 'c':
13935 {
13936 Py_UCS4 ch = formatchar(v);
13937 if (ch == (Py_UCS4) -1)
13938 return -1;
13939 if (arg->width == -1 && arg->prec == -1) {
13940 /* Fast path */
13941 if (_PyUnicodeWriter_Prepare(writer, 1, ch) == -1)
13942 return -1;
13943 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13944 writer->pos += 1;
13945 return 1;
13946 }
13947 *p_str = PyUnicode_FromOrdinal(ch);
13948 break;
13949 }
13950
13951 default:
13952 PyErr_Format(PyExc_ValueError,
13953 "unsupported format character '%c' (0x%x) "
13954 "at index %zd",
13955 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
13956 (int)arg->ch,
13957 ctx->fmtpos - 1);
13958 return -1;
13959 }
13960 if (*p_str == NULL)
13961 return -1;
13962 assert (PyUnicode_Check(*p_str));
13963 return 0;
13964}
13965
13966static int
13967unicode_format_arg_output(struct unicode_formatter_t *ctx,
13968 struct unicode_format_arg_t *arg,
13969 PyObject *str)
13970{
13971 Py_ssize_t len;
13972 enum PyUnicode_Kind kind;
13973 void *pbuf;
13974 Py_ssize_t pindex;
13975 Py_UCS4 signchar;
13976 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020013977 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020013978 Py_ssize_t sublen;
13979 _PyUnicodeWriter *writer = &ctx->writer;
13980 Py_UCS4 fill;
13981
13982 fill = ' ';
13983 if (arg->sign && arg->flags & F_ZERO)
13984 fill = '0';
13985
13986 if (PyUnicode_READY(str) == -1)
13987 return -1;
13988
13989 len = PyUnicode_GET_LENGTH(str);
13990 if ((arg->width == -1 || arg->width <= len)
13991 && (arg->prec == -1 || arg->prec >= len)
13992 && !(arg->flags & (F_SIGN | F_BLANK)))
13993 {
13994 /* Fast path */
13995 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
13996 return -1;
13997 return 0;
13998 }
13999
14000 /* Truncate the string for "s", "r" and "a" formats
14001 if the precision is set */
14002 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14003 if (arg->prec >= 0 && len > arg->prec)
14004 len = arg->prec;
14005 }
14006
14007 /* Adjust sign and width */
14008 kind = PyUnicode_KIND(str);
14009 pbuf = PyUnicode_DATA(str);
14010 pindex = 0;
14011 signchar = '\0';
14012 if (arg->sign) {
14013 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14014 if (ch == '-' || ch == '+') {
14015 signchar = ch;
14016 len--;
14017 pindex++;
14018 }
14019 else if (arg->flags & F_SIGN)
14020 signchar = '+';
14021 else if (arg->flags & F_BLANK)
14022 signchar = ' ';
14023 else
14024 arg->sign = 0;
14025 }
14026 if (arg->width < len)
14027 arg->width = len;
14028
14029 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014030 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014031 if (!(arg->flags & F_LJUST)) {
14032 if (arg->sign) {
14033 if ((arg->width-1) > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014034 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014035 }
14036 else {
14037 if (arg->width > len)
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014038 maxchar = MAX_MAXCHAR(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014039 }
14040 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014041 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14042 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
14043 maxchar = MAX_MAXCHAR(maxchar, strmaxchar);
14044 }
14045
Victor Stinnera47082312012-10-04 02:19:54 +020014046 buflen = arg->width;
14047 if (arg->sign && len == arg->width)
14048 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014049 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014050 return -1;
14051
14052 /* Write the sign if needed */
14053 if (arg->sign) {
14054 if (fill != ' ') {
14055 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14056 writer->pos += 1;
14057 }
14058 if (arg->width > len)
14059 arg->width--;
14060 }
14061
14062 /* Write the numeric prefix for "x", "X" and "o" formats
14063 if the alternate form is used.
14064 For example, write "0x" for the "%#x" format. */
14065 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14066 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14067 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14068 if (fill != ' ') {
14069 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14070 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14071 writer->pos += 2;
14072 pindex += 2;
14073 }
14074 arg->width -= 2;
14075 if (arg->width < 0)
14076 arg->width = 0;
14077 len -= 2;
14078 }
14079
14080 /* Pad left with the fill character if needed */
14081 if (arg->width > len && !(arg->flags & F_LJUST)) {
14082 sublen = arg->width - len;
14083 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14084 writer->pos += sublen;
14085 arg->width = len;
14086 }
14087
14088 /* If padding with spaces: write sign if needed and/or numeric prefix if
14089 the alternate form is used */
14090 if (fill == ' ') {
14091 if (arg->sign) {
14092 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14093 writer->pos += 1;
14094 }
14095 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14096 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14097 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14098 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14099 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14100 writer->pos += 2;
14101 pindex += 2;
14102 }
14103 }
14104
14105 /* Write characters */
14106 if (len) {
14107 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14108 str, pindex, len);
14109 writer->pos += len;
14110 }
14111
14112 /* Pad right with the fill character if needed */
14113 if (arg->width > len) {
14114 sublen = arg->width - len;
14115 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14116 writer->pos += sublen;
14117 }
14118 return 0;
14119}
14120
14121/* Helper of PyUnicode_Format(): format one arg.
14122 Return 0 on success, raise an exception and return -1 on error. */
14123static int
14124unicode_format_arg(struct unicode_formatter_t *ctx)
14125{
14126 struct unicode_format_arg_t arg;
14127 PyObject *str;
14128 int ret;
14129
Victor Stinner8dbd4212012-12-04 09:30:24 +010014130 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14131 arg.flags = 0;
14132 arg.width = -1;
14133 arg.prec = -1;
14134 arg.sign = 0;
14135 str = NULL;
14136
Victor Stinnera47082312012-10-04 02:19:54 +020014137 ret = unicode_format_arg_parse(ctx, &arg);
14138 if (ret == -1)
14139 return -1;
14140
14141 ret = unicode_format_arg_format(ctx, &arg, &str);
14142 if (ret == -1)
14143 return -1;
14144
14145 if (ret != 1) {
14146 ret = unicode_format_arg_output(ctx, &arg, str);
14147 Py_DECREF(str);
14148 if (ret == -1)
14149 return -1;
14150 }
14151
14152 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14153 PyErr_SetString(PyExc_TypeError,
14154 "not all arguments converted during string formatting");
14155 return -1;
14156 }
14157 return 0;
14158}
14159
Alexander Belopolsky40018472011-02-26 01:02:56 +000014160PyObject *
14161PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014162{
Victor Stinnera47082312012-10-04 02:19:54 +020014163 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014164
Guido van Rossumd57fd912000-03-10 22:53:23 +000014165 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014166 PyErr_BadInternalCall();
14167 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014168 }
Victor Stinnera47082312012-10-04 02:19:54 +020014169
14170 ctx.fmtstr = PyUnicode_FromObject(format);
14171 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014172 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014173 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14174 Py_DECREF(ctx.fmtstr);
14175 return NULL;
14176 }
14177 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14178 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14179 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14180 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014181
Victor Stinnera47082312012-10-04 02:19:54 +020014182 _PyUnicodeWriter_Init(&ctx.writer, ctx.fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014183
Guido van Rossumd57fd912000-03-10 22:53:23 +000014184 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014185 ctx.arglen = PyTuple_Size(args);
14186 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014187 }
14188 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014189 ctx.arglen = -1;
14190 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014191 }
Victor Stinnera47082312012-10-04 02:19:54 +020014192 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014193 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014194 ctx.dict = args;
14195 else
14196 ctx.dict = NULL;
14197 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014198
Victor Stinnera47082312012-10-04 02:19:54 +020014199 while (--ctx.fmtcnt >= 0) {
14200 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014201 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014202
14203 nonfmtpos = ctx.fmtpos++;
14204 while (ctx.fmtcnt >= 0 &&
14205 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14206 ctx.fmtpos++;
14207 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014208 }
Victor Stinnera47082312012-10-04 02:19:54 +020014209 if (ctx.fmtcnt < 0) {
14210 ctx.fmtpos--;
14211 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014212 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014213
Victor Stinnercfc4c132013-04-03 01:48:39 +020014214 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14215 nonfmtpos, ctx.fmtpos) < 0)
14216 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014217 }
14218 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014219 ctx.fmtpos++;
14220 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014221 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014222 }
14223 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014224
Victor Stinnera47082312012-10-04 02:19:54 +020014225 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014226 PyErr_SetString(PyExc_TypeError,
14227 "not all arguments converted during string formatting");
14228 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014229 }
14230
Victor Stinnera47082312012-10-04 02:19:54 +020014231 if (ctx.args_owned) {
14232 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014233 }
Victor Stinnera47082312012-10-04 02:19:54 +020014234 Py_DECREF(ctx.fmtstr);
14235 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014236
Benjamin Peterson29060642009-01-31 22:14:21 +000014237 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014238 Py_DECREF(ctx.fmtstr);
14239 _PyUnicodeWriter_Dealloc(&ctx.writer);
14240 if (ctx.args_owned) {
14241 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014242 }
14243 return NULL;
14244}
14245
Jeremy Hylton938ace62002-07-17 16:30:39 +000014246static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014247unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14248
Tim Peters6d6c1a32001-08-02 04:15:00 +000014249static PyObject *
14250unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14251{
Benjamin Peterson29060642009-01-31 22:14:21 +000014252 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014253 static char *kwlist[] = {"object", "encoding", "errors", 0};
14254 char *encoding = NULL;
14255 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014256
Benjamin Peterson14339b62009-01-31 16:36:08 +000014257 if (type != &PyUnicode_Type)
14258 return unicode_subtype_new(type, args, kwds);
14259 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014260 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014261 return NULL;
14262 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014263 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014264 if (encoding == NULL && errors == NULL)
14265 return PyObject_Str(x);
14266 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014267 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014268}
14269
Guido van Rossume023fe02001-08-30 03:12:59 +000014270static PyObject *
14271unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14272{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014273 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014274 Py_ssize_t length, char_size;
14275 int share_wstr, share_utf8;
14276 unsigned int kind;
14277 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014278
Benjamin Peterson14339b62009-01-31 16:36:08 +000014279 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014280
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014281 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014282 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014283 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014284 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014285 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014286 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014287 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014288 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014289
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014290 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014291 if (self == NULL) {
14292 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014293 return NULL;
14294 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014295 kind = PyUnicode_KIND(unicode);
14296 length = PyUnicode_GET_LENGTH(unicode);
14297
14298 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014299#ifdef Py_DEBUG
14300 _PyUnicode_HASH(self) = -1;
14301#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014302 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014303#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014304 _PyUnicode_STATE(self).interned = 0;
14305 _PyUnicode_STATE(self).kind = kind;
14306 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014307 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014308 _PyUnicode_STATE(self).ready = 1;
14309 _PyUnicode_WSTR(self) = NULL;
14310 _PyUnicode_UTF8_LENGTH(self) = 0;
14311 _PyUnicode_UTF8(self) = NULL;
14312 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014313 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014314
14315 share_utf8 = 0;
14316 share_wstr = 0;
14317 if (kind == PyUnicode_1BYTE_KIND) {
14318 char_size = 1;
14319 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14320 share_utf8 = 1;
14321 }
14322 else if (kind == PyUnicode_2BYTE_KIND) {
14323 char_size = 2;
14324 if (sizeof(wchar_t) == 2)
14325 share_wstr = 1;
14326 }
14327 else {
14328 assert(kind == PyUnicode_4BYTE_KIND);
14329 char_size = 4;
14330 if (sizeof(wchar_t) == 4)
14331 share_wstr = 1;
14332 }
14333
14334 /* Ensure we won't overflow the length. */
14335 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14336 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014337 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014338 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014339 data = PyObject_MALLOC((length + 1) * char_size);
14340 if (data == NULL) {
14341 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014342 goto onError;
14343 }
14344
Victor Stinnerc3c74152011-10-02 20:39:55 +020014345 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014346 if (share_utf8) {
14347 _PyUnicode_UTF8_LENGTH(self) = length;
14348 _PyUnicode_UTF8(self) = data;
14349 }
14350 if (share_wstr) {
14351 _PyUnicode_WSTR_LENGTH(self) = length;
14352 _PyUnicode_WSTR(self) = (wchar_t *)data;
14353 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014354
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014355 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014356 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014357 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014358#ifdef Py_DEBUG
14359 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14360#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014361 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014362 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014363
14364onError:
14365 Py_DECREF(unicode);
14366 Py_DECREF(self);
14367 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014368}
14369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014370PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014371"str(object='') -> str\n\
14372str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014373\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014374Create a new string object from the given object. If encoding or\n\
14375errors is specified, then the object must expose a data buffer\n\
14376that will be decoded using the given encoding and error handler.\n\
14377Otherwise, returns the result of object.__str__() (if defined)\n\
14378or repr(object).\n\
14379encoding defaults to sys.getdefaultencoding().\n\
14380errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014381
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014382static PyObject *unicode_iter(PyObject *seq);
14383
Guido van Rossumd57fd912000-03-10 22:53:23 +000014384PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014385 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014386 "str", /* tp_name */
14387 sizeof(PyUnicodeObject), /* tp_size */
14388 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014389 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 (destructor)unicode_dealloc, /* tp_dealloc */
14391 0, /* tp_print */
14392 0, /* tp_getattr */
14393 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014394 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014395 unicode_repr, /* tp_repr */
14396 &unicode_as_number, /* tp_as_number */
14397 &unicode_as_sequence, /* tp_as_sequence */
14398 &unicode_as_mapping, /* tp_as_mapping */
14399 (hashfunc) unicode_hash, /* tp_hash*/
14400 0, /* tp_call*/
14401 (reprfunc) unicode_str, /* tp_str */
14402 PyObject_GenericGetAttr, /* tp_getattro */
14403 0, /* tp_setattro */
14404 0, /* tp_as_buffer */
14405 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014406 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014407 unicode_doc, /* tp_doc */
14408 0, /* tp_traverse */
14409 0, /* tp_clear */
14410 PyUnicode_RichCompare, /* tp_richcompare */
14411 0, /* tp_weaklistoffset */
14412 unicode_iter, /* tp_iter */
14413 0, /* tp_iternext */
14414 unicode_methods, /* tp_methods */
14415 0, /* tp_members */
14416 0, /* tp_getset */
14417 &PyBaseObject_Type, /* tp_base */
14418 0, /* tp_dict */
14419 0, /* tp_descr_get */
14420 0, /* tp_descr_set */
14421 0, /* tp_dictoffset */
14422 0, /* tp_init */
14423 0, /* tp_alloc */
14424 unicode_new, /* tp_new */
14425 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014426};
14427
14428/* Initialize the Unicode implementation */
14429
Victor Stinner3a50e702011-10-18 21:21:00 +020014430int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014431{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014432 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014433 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014434 0x000A, /* LINE FEED */
14435 0x000D, /* CARRIAGE RETURN */
14436 0x001C, /* FILE SEPARATOR */
14437 0x001D, /* GROUP SEPARATOR */
14438 0x001E, /* RECORD SEPARATOR */
14439 0x0085, /* NEXT LINE */
14440 0x2028, /* LINE SEPARATOR */
14441 0x2029, /* PARAGRAPH SEPARATOR */
14442 };
14443
Fred Drakee4315f52000-05-09 19:53:39 +000014444 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014445 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014446 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014447 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014448 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014449
Guido van Rossumcacfc072002-05-24 19:01:59 +000014450 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014451 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014452
14453 /* initialize the linebreak bloom filter */
14454 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014455 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014456 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014457
14458 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014459
Benjamin Petersonc4311282012-10-30 23:21:10 -040014460 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14461 Py_FatalError("Can't initialize field name iterator type");
14462
14463 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14464 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014465
Victor Stinner3a50e702011-10-18 21:21:00 +020014466#ifdef HAVE_MBCS
14467 winver.dwOSVersionInfoSize = sizeof(winver);
14468 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14469 PyErr_SetFromWindowsErr(0);
14470 return -1;
14471 }
14472#endif
14473 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014474}
14475
14476/* Finalize the Unicode implementation */
14477
Christian Heimesa156e092008-02-16 07:38:31 +000014478int
14479PyUnicode_ClearFreeList(void)
14480{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014481 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014482}
14483
Guido van Rossumd57fd912000-03-10 22:53:23 +000014484void
Thomas Wouters78890102000-07-22 19:25:51 +000014485_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014486{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014487 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014488
Serhiy Storchaka05997252013-01-26 12:14:02 +020014489 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014490
Serhiy Storchaka05997252013-01-26 12:14:02 +020014491 for (i = 0; i < 256; i++)
14492 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014493 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014494 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014495}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014496
Walter Dörwald16807132007-05-25 13:52:07 +000014497void
14498PyUnicode_InternInPlace(PyObject **p)
14499{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014500 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014501 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014502#ifdef Py_DEBUG
14503 assert(s != NULL);
14504 assert(_PyUnicode_CHECK(s));
14505#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014506 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014507 return;
14508#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014509 /* If it's a subclass, we don't really know what putting
14510 it in the interned dict might do. */
14511 if (!PyUnicode_CheckExact(s))
14512 return;
14513 if (PyUnicode_CHECK_INTERNED(s))
14514 return;
14515 if (interned == NULL) {
14516 interned = PyDict_New();
14517 if (interned == NULL) {
14518 PyErr_Clear(); /* Don't leave an exception */
14519 return;
14520 }
14521 }
14522 /* It might be that the GetItem call fails even
14523 though the key is present in the dictionary,
14524 namely when this happens during a stack overflow. */
14525 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014526 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014527 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014528
Benjamin Peterson29060642009-01-31 22:14:21 +000014529 if (t) {
14530 Py_INCREF(t);
14531 Py_DECREF(*p);
14532 *p = t;
14533 return;
14534 }
Walter Dörwald16807132007-05-25 13:52:07 +000014535
Benjamin Peterson14339b62009-01-31 16:36:08 +000014536 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014537 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014538 PyErr_Clear();
14539 PyThreadState_GET()->recursion_critical = 0;
14540 return;
14541 }
14542 PyThreadState_GET()->recursion_critical = 0;
14543 /* The two references in interned are not counted by refcnt.
14544 The deallocator will take care of this */
14545 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014546 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014547}
14548
14549void
14550PyUnicode_InternImmortal(PyObject **p)
14551{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014552 PyUnicode_InternInPlace(p);
14553 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014554 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014555 Py_INCREF(*p);
14556 }
Walter Dörwald16807132007-05-25 13:52:07 +000014557}
14558
14559PyObject *
14560PyUnicode_InternFromString(const char *cp)
14561{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014562 PyObject *s = PyUnicode_FromString(cp);
14563 if (s == NULL)
14564 return NULL;
14565 PyUnicode_InternInPlace(&s);
14566 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014567}
14568
Alexander Belopolsky40018472011-02-26 01:02:56 +000014569void
14570_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014571{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014572 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014573 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014574 Py_ssize_t i, n;
14575 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014576
Benjamin Peterson14339b62009-01-31 16:36:08 +000014577 if (interned == NULL || !PyDict_Check(interned))
14578 return;
14579 keys = PyDict_Keys(interned);
14580 if (keys == NULL || !PyList_Check(keys)) {
14581 PyErr_Clear();
14582 return;
14583 }
Walter Dörwald16807132007-05-25 13:52:07 +000014584
Benjamin Peterson14339b62009-01-31 16:36:08 +000014585 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14586 detector, interned unicode strings are not forcibly deallocated;
14587 rather, we give them their stolen references back, and then clear
14588 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014589
Benjamin Peterson14339b62009-01-31 16:36:08 +000014590 n = PyList_GET_SIZE(keys);
14591 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014592 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014593 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014594 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014595 if (PyUnicode_READY(s) == -1) {
14596 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014597 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014598 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014599 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014600 case SSTATE_NOT_INTERNED:
14601 /* XXX Shouldn't happen */
14602 break;
14603 case SSTATE_INTERNED_IMMORTAL:
14604 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014605 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014606 break;
14607 case SSTATE_INTERNED_MORTAL:
14608 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014609 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014610 break;
14611 default:
14612 Py_FatalError("Inconsistent interned string state.");
14613 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014614 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014615 }
14616 fprintf(stderr, "total size of all interned strings: "
14617 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14618 "mortal/immortal\n", mortal_size, immortal_size);
14619 Py_DECREF(keys);
14620 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014621 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014622}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014623
14624
14625/********************* Unicode Iterator **************************/
14626
14627typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014628 PyObject_HEAD
14629 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014630 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014631} unicodeiterobject;
14632
14633static void
14634unicodeiter_dealloc(unicodeiterobject *it)
14635{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014636 _PyObject_GC_UNTRACK(it);
14637 Py_XDECREF(it->it_seq);
14638 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014639}
14640
14641static int
14642unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14643{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014644 Py_VISIT(it->it_seq);
14645 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014646}
14647
14648static PyObject *
14649unicodeiter_next(unicodeiterobject *it)
14650{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014651 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014652
Benjamin Peterson14339b62009-01-31 16:36:08 +000014653 assert(it != NULL);
14654 seq = it->it_seq;
14655 if (seq == NULL)
14656 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014657 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014659 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14660 int kind = PyUnicode_KIND(seq);
14661 void *data = PyUnicode_DATA(seq);
14662 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14663 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014664 if (item != NULL)
14665 ++it->it_index;
14666 return item;
14667 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014668
Benjamin Peterson14339b62009-01-31 16:36:08 +000014669 Py_DECREF(seq);
14670 it->it_seq = NULL;
14671 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014672}
14673
14674static PyObject *
14675unicodeiter_len(unicodeiterobject *it)
14676{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014677 Py_ssize_t len = 0;
14678 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014679 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014680 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014681}
14682
14683PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14684
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014685static PyObject *
14686unicodeiter_reduce(unicodeiterobject *it)
14687{
14688 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014689 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014690 it->it_seq, it->it_index);
14691 } else {
14692 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14693 if (u == NULL)
14694 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014695 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014696 }
14697}
14698
14699PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14700
14701static PyObject *
14702unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14703{
14704 Py_ssize_t index = PyLong_AsSsize_t(state);
14705 if (index == -1 && PyErr_Occurred())
14706 return NULL;
14707 if (index < 0)
14708 index = 0;
14709 it->it_index = index;
14710 Py_RETURN_NONE;
14711}
14712
14713PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14714
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014715static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014716 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014717 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014718 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14719 reduce_doc},
14720 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14721 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014722 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014723};
14724
14725PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014726 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14727 "str_iterator", /* tp_name */
14728 sizeof(unicodeiterobject), /* tp_basicsize */
14729 0, /* tp_itemsize */
14730 /* methods */
14731 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14732 0, /* tp_print */
14733 0, /* tp_getattr */
14734 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014735 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014736 0, /* tp_repr */
14737 0, /* tp_as_number */
14738 0, /* tp_as_sequence */
14739 0, /* tp_as_mapping */
14740 0, /* tp_hash */
14741 0, /* tp_call */
14742 0, /* tp_str */
14743 PyObject_GenericGetAttr, /* tp_getattro */
14744 0, /* tp_setattro */
14745 0, /* tp_as_buffer */
14746 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14747 0, /* tp_doc */
14748 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14749 0, /* tp_clear */
14750 0, /* tp_richcompare */
14751 0, /* tp_weaklistoffset */
14752 PyObject_SelfIter, /* tp_iter */
14753 (iternextfunc)unicodeiter_next, /* tp_iternext */
14754 unicodeiter_methods, /* tp_methods */
14755 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014756};
14757
14758static PyObject *
14759unicode_iter(PyObject *seq)
14760{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014761 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014762
Benjamin Peterson14339b62009-01-31 16:36:08 +000014763 if (!PyUnicode_Check(seq)) {
14764 PyErr_BadInternalCall();
14765 return NULL;
14766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014767 if (PyUnicode_READY(seq) == -1)
14768 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014769 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14770 if (it == NULL)
14771 return NULL;
14772 it->it_index = 0;
14773 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014774 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014775 _PyObject_GC_TRACK(it);
14776 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014777}
14778
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014779
14780size_t
14781Py_UNICODE_strlen(const Py_UNICODE *u)
14782{
14783 int res = 0;
14784 while(*u++)
14785 res++;
14786 return res;
14787}
14788
14789Py_UNICODE*
14790Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14791{
14792 Py_UNICODE *u = s1;
14793 while ((*u++ = *s2++));
14794 return s1;
14795}
14796
14797Py_UNICODE*
14798Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14799{
14800 Py_UNICODE *u = s1;
14801 while ((*u++ = *s2++))
14802 if (n-- == 0)
14803 break;
14804 return s1;
14805}
14806
14807Py_UNICODE*
14808Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14809{
14810 Py_UNICODE *u1 = s1;
14811 u1 += Py_UNICODE_strlen(u1);
14812 Py_UNICODE_strcpy(u1, s2);
14813 return s1;
14814}
14815
14816int
14817Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14818{
14819 while (*s1 && *s2 && *s1 == *s2)
14820 s1++, s2++;
14821 if (*s1 && *s2)
14822 return (*s1 < *s2) ? -1 : +1;
14823 if (*s1)
14824 return 1;
14825 if (*s2)
14826 return -1;
14827 return 0;
14828}
14829
14830int
14831Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14832{
14833 register Py_UNICODE u1, u2;
14834 for (; n != 0; n--) {
14835 u1 = *s1;
14836 u2 = *s2;
14837 if (u1 != u2)
14838 return (u1 < u2) ? -1 : +1;
14839 if (u1 == '\0')
14840 return 0;
14841 s1++;
14842 s2++;
14843 }
14844 return 0;
14845}
14846
14847Py_UNICODE*
14848Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14849{
14850 const Py_UNICODE *p;
14851 for (p = s; *p; p++)
14852 if (*p == c)
14853 return (Py_UNICODE*)p;
14854 return NULL;
14855}
14856
14857Py_UNICODE*
14858Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14859{
14860 const Py_UNICODE *p;
14861 p = s + Py_UNICODE_strlen(s);
14862 while (p != s) {
14863 p--;
14864 if (*p == c)
14865 return (Py_UNICODE*)p;
14866 }
14867 return NULL;
14868}
Victor Stinner331ea922010-08-10 16:37:20 +000014869
Victor Stinner71133ff2010-09-01 23:43:53 +000014870Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014871PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014872{
Victor Stinner577db2c2011-10-11 22:12:48 +020014873 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014874 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014876 if (!PyUnicode_Check(unicode)) {
14877 PyErr_BadArgument();
14878 return NULL;
14879 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014880 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014881 if (u == NULL)
14882 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014883 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014884 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014885 PyErr_NoMemory();
14886 return NULL;
14887 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014888 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014889 size *= sizeof(Py_UNICODE);
14890 copy = PyMem_Malloc(size);
14891 if (copy == NULL) {
14892 PyErr_NoMemory();
14893 return NULL;
14894 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014895 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014896 return copy;
14897}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014898
Georg Brandl66c221e2010-10-14 07:04:07 +000014899/* A _string module, to export formatter_parser and formatter_field_name_split
14900 to the string.Formatter class implemented in Python. */
14901
14902static PyMethodDef _string_methods[] = {
14903 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14904 METH_O, PyDoc_STR("split the argument as a field name")},
14905 {"formatter_parser", (PyCFunction) formatter_parser,
14906 METH_O, PyDoc_STR("parse the argument as a format string")},
14907 {NULL, NULL}
14908};
14909
14910static struct PyModuleDef _string_module = {
14911 PyModuleDef_HEAD_INIT,
14912 "_string",
14913 PyDoc_STR("string helper module"),
14914 0,
14915 _string_methods,
14916 NULL,
14917 NULL,
14918 NULL,
14919 NULL
14920};
14921
14922PyMODINIT_FUNC
14923PyInit__string(void)
14924{
14925 return PyModule_Create(&_string_module);
14926}
14927
14928
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014929#ifdef __cplusplus
14930}
14931#endif