blob: a149177a09fbaae12b5d11818fae44a6166e4a1f [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
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Endianness switches; defaults to little endian */
51
52#ifdef WORDS_BIGENDIAN
53# define BYTEORDER_IS_BIG_ENDIAN
54#else
55# define BYTEORDER_IS_LITTLE_ENDIAN
56#endif
57
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000058/* --- Globals ------------------------------------------------------------
59
Serhiy Storchaka05997252013-01-26 12:14:02 +020060NOTE: In the interpreter's initialization phase, some globals are currently
61 initialized dynamically as needed. In the process Unicode objects may
62 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000063
64*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000065
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000066
67#ifdef __cplusplus
68extern "C" {
69#endif
70
Victor Stinner8faf8212011-12-08 22:14:11 +010071/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
72#define MAX_UNICODE 0x10ffff
73
Victor Stinner910337b2011-10-03 03:20:16 +020074#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020075# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020076#else
77# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
78#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020079
Victor Stinnere90fe6a2011-10-01 16:48:13 +020080#define _PyUnicode_UTF8(op) \
81 (((PyCompactUnicodeObject*)(op))->utf8)
82#define PyUnicode_UTF8(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 ((char*)((PyASCIIObject*)(op) + 1)) : \
87 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020088#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 (((PyCompactUnicodeObject*)(op))->utf8_length)
90#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020091 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020092 assert(PyUnicode_IS_READY(op)), \
93 PyUnicode_IS_COMPACT_ASCII(op) ? \
94 ((PyASCIIObject*)(op))->length : \
95 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020096#define _PyUnicode_WSTR(op) \
97 (((PyASCIIObject*)(op))->wstr)
98#define _PyUnicode_WSTR_LENGTH(op) \
99 (((PyCompactUnicodeObject*)(op))->wstr_length)
100#define _PyUnicode_LENGTH(op) \
101 (((PyASCIIObject *)(op))->length)
102#define _PyUnicode_STATE(op) \
103 (((PyASCIIObject *)(op))->state)
104#define _PyUnicode_HASH(op) \
105 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_KIND(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200109#define _PyUnicode_GET_LENGTH(op) \
110 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200112#define _PyUnicode_DATA_ANY(op) \
113 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200114
Victor Stinner910337b2011-10-03 03:20:16 +0200115#undef PyUnicode_READY
116#define PyUnicode_READY(op) \
117 (assert(_PyUnicode_CHECK(op)), \
118 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200119 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100120 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200121
Victor Stinnerc379ead2011-10-03 12:52:27 +0200122#define _PyUnicode_SHARE_UTF8(op) \
123 (assert(_PyUnicode_CHECK(op)), \
124 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
125 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
126#define _PyUnicode_SHARE_WSTR(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
129
Victor Stinner829c0ad2011-10-03 01:08:02 +0200130/* true if the Unicode object has an allocated UTF-8 memory block
131 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200132#define _PyUnicode_HAS_UTF8_MEMORY(op) \
133 (assert(_PyUnicode_CHECK(op)), \
134 (!PyUnicode_IS_COMPACT_ASCII(op) \
135 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200136 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
137
Victor Stinner03490912011-10-03 23:45:12 +0200138/* true if the Unicode object has an allocated wstr memory block
139 (not shared with other data) */
140#define _PyUnicode_HAS_WSTR_MEMORY(op) \
141 (assert(_PyUnicode_CHECK(op)), \
142 (_PyUnicode_WSTR(op) && \
143 (!PyUnicode_IS_READY(op) || \
144 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
145
Victor Stinner910337b2011-10-03 03:20:16 +0200146/* Generic helper macro to convert characters of different types.
147 from_type and to_type have to be valid type names, begin and end
148 are pointers to the source characters which should be of type
149 "from_type *". to is a pointer of type "to_type *" and points to the
150 buffer where the result characters are written to. */
151#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
152 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200153 to_type *_to = (to_type *) to; \
154 const from_type *_iter = (begin); \
155 const from_type *_end = (end); \
156 Py_ssize_t n = (_end) - (_iter); \
157 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200158 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200159 while (_iter < (_unrolled_end)) { \
160 _to[0] = (to_type) _iter[0]; \
161 _to[1] = (to_type) _iter[1]; \
162 _to[2] = (to_type) _iter[2]; \
163 _to[3] = (to_type) _iter[3]; \
164 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200165 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200166 while (_iter < (_end)) \
167 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200168 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200169
Walter Dörwald16807132007-05-25 13:52:07 +0000170/* This dictionary holds all interned unicode strings. Note that references
171 to strings in this dictionary are *not* counted in the string's ob_refcnt.
172 When the interned string reaches a refcnt of 0 the string deallocation
173 function will delete the reference from this dictionary.
174
175 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000176 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000177*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200178static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000179
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000180/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200181static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200184 do { \
185 if (unicode_empty != NULL) \
186 Py_INCREF(unicode_empty); \
187 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200188 unicode_empty = PyUnicode_New(0, 0); \
189 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200190 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
192 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200193 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000195
Serhiy Storchaka678db842013-01-26 12:16:36 +0200196#define _Py_RETURN_UNICODE_EMPTY() \
197 do { \
198 _Py_INCREF_UNICODE_EMPTY(); \
199 return unicode_empty; \
200 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000201
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200202/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200203static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200204
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205/* Single character Unicode strings in the Latin-1 range are being
206 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000208
Christian Heimes190d79e2008-01-30 11:58:22 +0000209/* Fast detection of the most frequent whitespace characters */
210const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000212/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000213/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000214/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000215/* case 0x000C: * FORM FEED */
216/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000217 0, 1, 1, 1, 1, 1, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000219/* case 0x001C: * FILE SEPARATOR */
220/* case 0x001D: * GROUP SEPARATOR */
221/* case 0x001E: * RECORD SEPARATOR */
222/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000223 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000224/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 1, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
228 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000229
Benjamin Peterson14339b62009-01-31 16:36:08 +0000230 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,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
237 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000238};
239
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200240/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200241static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200242static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100243static int unicode_modifiable(PyObject *unicode);
244
Victor Stinnerfe226c02011-10-03 03:52:20 +0200245
Alexander Belopolsky40018472011-02-26 01:02:56 +0000246static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100247_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200248static PyObject *
249_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
250static PyObject *
251_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
252
253static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000255 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100256 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000257 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
258
Alexander Belopolsky40018472011-02-26 01:02:56 +0000259static void
260raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300261 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100262 PyObject *unicode,
263 Py_ssize_t startpos, Py_ssize_t endpos,
264 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000265
Christian Heimes190d79e2008-01-30 11:58:22 +0000266/* Same for linebreaks */
267static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000270/* 0x000B, * LINE TABULATION */
271/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000272/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000273 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000274 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000275/* 0x001C, * FILE SEPARATOR */
276/* 0x001D, * GROUP SEPARATOR */
277/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000278 0, 0, 0, 0, 1, 1, 1, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000283
Benjamin Peterson14339b62009-01-31 16:36:08 +0000284 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,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000292};
293
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300294/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
295 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000297PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000298{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000299#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000300 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000301#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000302 /* This is actually an illegal character, so it should
303 not be passed to unichr. */
304 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000305#endif
306}
307
Victor Stinner910337b2011-10-03 03:20:16 +0200308#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200309int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100310_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200311{
312 PyASCIIObject *ascii;
313 unsigned int kind;
314
315 assert(PyUnicode_Check(op));
316
317 ascii = (PyASCIIObject *)op;
318 kind = ascii->state.kind;
319
Victor Stinnera3b334d2011-10-03 13:53:37 +0200320 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200322 assert(ascii->state.ready == 1);
323 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200325 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200326 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200327
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 if (ascii->state.compact == 1) {
329 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200330 assert(kind == PyUnicode_1BYTE_KIND
331 || kind == PyUnicode_2BYTE_KIND
332 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200334 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200335 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100336 }
337 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200338 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
339
340 data = unicode->data.any;
341 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->length == 0);
343 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200344 assert(ascii->state.compact == 0);
345 assert(ascii->state.ascii == 0);
346 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100347 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200348 assert(ascii->wstr != NULL);
349 assert(data == NULL);
350 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200351 }
352 else {
353 assert(kind == PyUnicode_1BYTE_KIND
354 || kind == PyUnicode_2BYTE_KIND
355 || kind == PyUnicode_4BYTE_KIND);
356 assert(ascii->state.compact == 0);
357 assert(ascii->state.ready == 1);
358 assert(data != NULL);
359 if (ascii->state.ascii) {
360 assert (compact->utf8 == data);
361 assert (compact->utf8_length == ascii->length);
362 }
363 else
364 assert (compact->utf8 != data);
365 }
366 }
367 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200368 if (
369#if SIZEOF_WCHAR_T == 2
370 kind == PyUnicode_2BYTE_KIND
371#else
372 kind == PyUnicode_4BYTE_KIND
373#endif
374 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200375 {
376 assert(ascii->wstr == data);
377 assert(compact->wstr_length == ascii->length);
378 } else
379 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200380 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200381
382 if (compact->utf8 == NULL)
383 assert(compact->utf8_length == 0);
384 if (ascii->wstr == NULL)
385 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200386 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 /* check that the best kind is used */
388 if (check_content && kind != PyUnicode_WCHAR_KIND)
389 {
390 Py_ssize_t i;
391 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200392 void *data;
393 Py_UCS4 ch;
394
395 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200396 for (i=0; i < ascii->length; i++)
397 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200398 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200399 if (ch > maxchar)
400 maxchar = ch;
401 }
402 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100403 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100405 assert(maxchar <= 255);
406 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200407 else
408 assert(maxchar < 128);
409 }
Victor Stinner77faf692011-11-20 18:56:05 +0100410 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200411 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100412 assert(maxchar <= 0xFFFF);
413 }
414 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200415 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100416 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100417 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200418 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200419 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400420 return 1;
421}
Victor Stinner910337b2011-10-03 03:20:16 +0200422#endif
423
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100424static PyObject*
425unicode_result_wchar(PyObject *unicode)
426{
427#ifndef Py_DEBUG
428 Py_ssize_t len;
429
430 assert(Py_REFCNT(unicode) == 1);
431
432 len = _PyUnicode_WSTR_LENGTH(unicode);
433 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100434 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200435 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100436 }
437
438 if (len == 1) {
439 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100440 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100441 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
442 Py_DECREF(unicode);
443 return latin1_char;
444 }
445 }
446
447 if (_PyUnicode_Ready(unicode) < 0) {
448 Py_XDECREF(unicode);
449 return NULL;
450 }
451#else
452 /* don't make the result ready in debug mode to ensure that the caller
453 makes the string ready before using it */
454 assert(_PyUnicode_CheckConsistency(unicode, 1));
455#endif
456 return unicode;
457}
458
459static PyObject*
460unicode_result_ready(PyObject *unicode)
461{
462 Py_ssize_t length;
463
464 length = PyUnicode_GET_LENGTH(unicode);
465 if (length == 0) {
466 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100467 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200468 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100469 }
470 return unicode_empty;
471 }
472
473 if (length == 1) {
474 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
475 if (ch < 256) {
476 PyObject *latin1_char = unicode_latin1[ch];
477 if (latin1_char != NULL) {
478 if (unicode != latin1_char) {
479 Py_INCREF(latin1_char);
480 Py_DECREF(unicode);
481 }
482 return latin1_char;
483 }
484 else {
485 assert(_PyUnicode_CheckConsistency(unicode, 1));
486 Py_INCREF(unicode);
487 unicode_latin1[ch] = unicode;
488 return unicode;
489 }
490 }
491 }
492
493 assert(_PyUnicode_CheckConsistency(unicode, 1));
494 return unicode;
495}
496
497static PyObject*
498unicode_result(PyObject *unicode)
499{
500 assert(_PyUnicode_CHECK(unicode));
501 if (PyUnicode_IS_READY(unicode))
502 return unicode_result_ready(unicode);
503 else
504 return unicode_result_wchar(unicode);
505}
506
Victor Stinnerc4b49542011-12-11 22:44:26 +0100507static PyObject*
508unicode_result_unchanged(PyObject *unicode)
509{
510 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500511 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100512 return NULL;
513 Py_INCREF(unicode);
514 return unicode;
515 }
516 else
517 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100518 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100519}
520
Victor Stinner3a50e702011-10-18 21:21:00 +0200521#ifdef HAVE_MBCS
522static OSVERSIONINFOEX winver;
523#endif
524
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525/* --- Bloom Filters ----------------------------------------------------- */
526
527/* stuff to implement simple "bloom filters" for Unicode characters.
528 to keep things simple, we use a single bitmask, using the least 5
529 bits from each unicode characters as the bit index. */
530
531/* the linebreak mask is set up by Unicode_Init below */
532
Antoine Pitrouf068f942010-01-13 14:19:12 +0000533#if LONG_BIT >= 128
534#define BLOOM_WIDTH 128
535#elif LONG_BIT >= 64
536#define BLOOM_WIDTH 64
537#elif LONG_BIT >= 32
538#define BLOOM_WIDTH 32
539#else
540#error "LONG_BIT is smaller than 32"
541#endif
542
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543#define BLOOM_MASK unsigned long
544
Serhiy Storchaka05997252013-01-26 12:14:02 +0200545static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546
Antoine Pitrouf068f942010-01-13 14:19:12 +0000547#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
548#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Benjamin Peterson29060642009-01-31 22:14:21 +0000550#define BLOOM_LINEBREAK(ch) \
551 ((ch) < 128U ? ascii_linebreak[(ch)] : \
552 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
Alexander Belopolsky40018472011-02-26 01:02:56 +0000554Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556{
557 /* calculate simple bloom-style bitmask for a given unicode string */
558
Antoine Pitrouf068f942010-01-13 14:19:12 +0000559 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560 Py_ssize_t i;
561
562 mask = 0;
563 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200564 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565
566 return mask;
567}
568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200569#define BLOOM_MEMBER(mask, chr, str) \
570 (BLOOM(mask, chr) \
571 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200573/* Compilation of templated routines */
574
575#include "stringlib/asciilib.h"
576#include "stringlib/fastsearch.h"
577#include "stringlib/partition.h"
578#include "stringlib/split.h"
579#include "stringlib/count.h"
580#include "stringlib/find.h"
581#include "stringlib/find_max_char.h"
582#include "stringlib/localeutil.h"
583#include "stringlib/undef.h"
584
585#include "stringlib/ucs1lib.h"
586#include "stringlib/fastsearch.h"
587#include "stringlib/partition.h"
588#include "stringlib/split.h"
589#include "stringlib/count.h"
590#include "stringlib/find.h"
591#include "stringlib/find_max_char.h"
592#include "stringlib/localeutil.h"
593#include "stringlib/undef.h"
594
595#include "stringlib/ucs2lib.h"
596#include "stringlib/fastsearch.h"
597#include "stringlib/partition.h"
598#include "stringlib/split.h"
599#include "stringlib/count.h"
600#include "stringlib/find.h"
601#include "stringlib/find_max_char.h"
602#include "stringlib/localeutil.h"
603#include "stringlib/undef.h"
604
605#include "stringlib/ucs4lib.h"
606#include "stringlib/fastsearch.h"
607#include "stringlib/partition.h"
608#include "stringlib/split.h"
609#include "stringlib/count.h"
610#include "stringlib/find.h"
611#include "stringlib/find_max_char.h"
612#include "stringlib/localeutil.h"
613#include "stringlib/undef.h"
614
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200615#include "stringlib/unicodedefs.h"
616#include "stringlib/fastsearch.h"
617#include "stringlib/count.h"
618#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100619#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200620
Guido van Rossumd57fd912000-03-10 22:53:23 +0000621/* --- Unicode Object ----------------------------------------------------- */
622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200623static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200624fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200625
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200626Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
627 Py_ssize_t size, Py_UCS4 ch,
628 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200629{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200630 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
631
632 switch (kind) {
633 case PyUnicode_1BYTE_KIND:
634 {
635 Py_UCS1 ch1 = (Py_UCS1) ch;
636 if (ch1 == ch)
637 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
638 else
639 return -1;
640 }
641 case PyUnicode_2BYTE_KIND:
642 {
643 Py_UCS2 ch2 = (Py_UCS2) ch;
644 if (ch2 == ch)
645 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
646 else
647 return -1;
648 }
649 case PyUnicode_4BYTE_KIND:
650 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
651 default:
652 assert(0);
653 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200655}
656
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657static PyObject*
658resize_compact(PyObject *unicode, Py_ssize_t length)
659{
660 Py_ssize_t char_size;
661 Py_ssize_t struct_size;
662 Py_ssize_t new_size;
663 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100664 PyObject *new_unicode;
Victor Stinner79891572012-05-03 13:43:07 +0200665 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200666 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100667 assert(PyUnicode_IS_COMPACT(unicode));
668
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200669 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100670 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200671 struct_size = sizeof(PyASCIIObject);
672 else
673 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200674 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200675
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
677 PyErr_NoMemory();
678 return NULL;
679 }
680 new_size = (struct_size + (length + 1) * char_size);
681
Victor Stinner84def372011-12-11 20:04:56 +0100682 _Py_DEC_REFTOTAL;
683 _Py_ForgetReference(unicode);
684
685 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
686 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100687 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200688 PyErr_NoMemory();
689 return NULL;
690 }
Victor Stinner84def372011-12-11 20:04:56 +0100691 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200692 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100693
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200695 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200696 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100697 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200698 _PyUnicode_WSTR_LENGTH(unicode) = length;
699 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100700 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
701 PyObject_DEL(_PyUnicode_WSTR(unicode));
702 _PyUnicode_WSTR(unicode) = NULL;
703 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200704 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
705 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200706 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200707 return unicode;
708}
709
Alexander Belopolsky40018472011-02-26 01:02:56 +0000710static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200711resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712{
Victor Stinner95663112011-10-04 01:03:50 +0200713 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100714 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200715 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000717
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718 if (PyUnicode_IS_READY(unicode)) {
719 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200720 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 void *data;
722
723 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200724 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200725 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
726 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200727
728 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
729 PyErr_NoMemory();
730 return -1;
731 }
732 new_size = (length + 1) * char_size;
733
Victor Stinner7a9105a2011-12-12 00:13:42 +0100734 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
735 {
736 PyObject_DEL(_PyUnicode_UTF8(unicode));
737 _PyUnicode_UTF8(unicode) = NULL;
738 _PyUnicode_UTF8_LENGTH(unicode) = 0;
739 }
740
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 data = (PyObject *)PyObject_REALLOC(data, new_size);
742 if (data == NULL) {
743 PyErr_NoMemory();
744 return -1;
745 }
746 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200747 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200748 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200749 _PyUnicode_WSTR_LENGTH(unicode) = length;
750 }
751 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200752 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200753 _PyUnicode_UTF8_LENGTH(unicode) = length;
754 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200755 _PyUnicode_LENGTH(unicode) = length;
756 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200757 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200758 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200759 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200761 }
Victor Stinner95663112011-10-04 01:03:50 +0200762 assert(_PyUnicode_WSTR(unicode) != NULL);
763
764 /* check for integer overflow */
765 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
766 PyErr_NoMemory();
767 return -1;
768 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100769 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200770 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100771 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200772 if (!wstr) {
773 PyErr_NoMemory();
774 return -1;
775 }
776 _PyUnicode_WSTR(unicode) = wstr;
777 _PyUnicode_WSTR(unicode)[length] = 0;
778 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200779 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000780 return 0;
781}
782
Victor Stinnerfe226c02011-10-03 03:52:20 +0200783static PyObject*
784resize_copy(PyObject *unicode, Py_ssize_t length)
785{
786 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100787 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200788 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100789
Benjamin Petersonbac79492012-01-14 13:34:47 -0500790 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100791 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200792
793 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
794 if (copy == NULL)
795 return NULL;
796
797 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200798 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200799 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200800 }
801 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200802 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100803
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200804 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200805 if (w == NULL)
806 return NULL;
807 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
808 copy_length = Py_MIN(copy_length, length);
809 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
810 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200811 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200812 }
813}
814
Guido van Rossumd57fd912000-03-10 22:53:23 +0000815/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000816 Ux0000 terminated; some code (e.g. new_identifier)
817 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000818
819 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000820 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000821
822*/
823
Alexander Belopolsky40018472011-02-26 01:02:56 +0000824static PyUnicodeObject *
825_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000826{
827 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000829
Thomas Wouters477c8d52006-05-27 19:21:47 +0000830 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000831 if (length == 0 && unicode_empty != NULL) {
832 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200833 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000834 }
835
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000836 /* Ensure we won't overflow the size. */
837 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
838 return (PyUnicodeObject *)PyErr_NoMemory();
839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200840 if (length < 0) {
841 PyErr_SetString(PyExc_SystemError,
842 "Negative size passed to _PyUnicode_New");
843 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000844 }
845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200846 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
847 if (unicode == NULL)
848 return NULL;
849 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
850 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
851 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100852 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000853 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100854 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000855 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200856
Jeremy Hyltond8082792003-09-16 19:41:39 +0000857 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000858 * the caller fails before initializing str -- unicode_resize()
859 * reads str[0], and the Keep-Alive optimization can keep memory
860 * allocated for str alive across a call to unicode_dealloc(unicode).
861 * We don't want unicode_resize to read uninitialized memory in
862 * that case.
863 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200864 _PyUnicode_WSTR(unicode)[0] = 0;
865 _PyUnicode_WSTR(unicode)[length] = 0;
866 _PyUnicode_WSTR_LENGTH(unicode) = length;
867 _PyUnicode_HASH(unicode) = -1;
868 _PyUnicode_STATE(unicode).interned = 0;
869 _PyUnicode_STATE(unicode).kind = 0;
870 _PyUnicode_STATE(unicode).compact = 0;
871 _PyUnicode_STATE(unicode).ready = 0;
872 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200873 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200874 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200875 _PyUnicode_UTF8(unicode) = NULL;
876 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100877 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000878 return unicode;
879}
880
Victor Stinnerf42dc442011-10-02 23:33:16 +0200881static const char*
882unicode_kind_name(PyObject *unicode)
883{
Victor Stinner42dfd712011-10-03 14:41:45 +0200884 /* don't check consistency: unicode_kind_name() is called from
885 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200886 if (!PyUnicode_IS_COMPACT(unicode))
887 {
888 if (!PyUnicode_IS_READY(unicode))
889 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600890 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200891 {
892 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 return "legacy ascii";
895 else
896 return "legacy latin1";
897 case PyUnicode_2BYTE_KIND:
898 return "legacy UCS2";
899 case PyUnicode_4BYTE_KIND:
900 return "legacy UCS4";
901 default:
902 return "<legacy invalid kind>";
903 }
904 }
905 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600906 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200907 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200908 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200909 return "ascii";
910 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200911 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200912 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200913 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200914 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200915 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200916 default:
917 return "<invalid compact kind>";
918 }
919}
920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200921#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922/* Functions wrapping macros for use in debugger */
923char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200924 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200925}
926
927void *_PyUnicode_compact_data(void *unicode) {
928 return _PyUnicode_COMPACT_DATA(unicode);
929}
930void *_PyUnicode_data(void *unicode){
931 printf("obj %p\n", unicode);
932 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
933 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
934 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
935 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
936 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
937 return PyUnicode_DATA(unicode);
938}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200939
940void
941_PyUnicode_Dump(PyObject *op)
942{
943 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200944 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
945 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
946 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200947
Victor Stinnera849a4b2011-10-03 12:12:11 +0200948 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200949 {
950 if (ascii->state.ascii)
951 data = (ascii + 1);
952 else
953 data = (compact + 1);
954 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200955 else
956 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200957 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
958
Victor Stinnera849a4b2011-10-03 12:12:11 +0200959 if (ascii->wstr == data)
960 printf("shared ");
961 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200962
Victor Stinnera3b334d2011-10-03 13:53:37 +0200963 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200964 printf(" (%zu), ", compact->wstr_length);
965 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
966 printf("shared ");
967 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200968 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200969 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200970}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200971#endif
972
973PyObject *
974PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
975{
976 PyObject *obj;
977 PyCompactUnicodeObject *unicode;
978 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200979 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200980 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200981 Py_ssize_t char_size;
982 Py_ssize_t struct_size;
983
984 /* Optimization for empty strings */
985 if (size == 0 && unicode_empty != NULL) {
986 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200987 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200988 }
989
Victor Stinner9e9d6892011-10-04 01:02:02 +0200990 is_ascii = 0;
991 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992 struct_size = sizeof(PyCompactUnicodeObject);
993 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +0200994 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 char_size = 1;
996 is_ascii = 1;
997 struct_size = sizeof(PyASCIIObject);
998 }
999 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001000 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001001 char_size = 1;
1002 }
1003 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001004 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001005 char_size = 2;
1006 if (sizeof(wchar_t) == 2)
1007 is_sharing = 1;
1008 }
1009 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001010 if (maxchar > MAX_UNICODE) {
1011 PyErr_SetString(PyExc_SystemError,
1012 "invalid maximum character passed to PyUnicode_New");
1013 return NULL;
1014 }
Victor Stinner8f825062012-04-27 13:55:39 +02001015 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001016 char_size = 4;
1017 if (sizeof(wchar_t) == 4)
1018 is_sharing = 1;
1019 }
1020
1021 /* Ensure we won't overflow the size. */
1022 if (size < 0) {
1023 PyErr_SetString(PyExc_SystemError,
1024 "Negative size passed to PyUnicode_New");
1025 return NULL;
1026 }
1027 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1028 return PyErr_NoMemory();
1029
1030 /* Duplicated allocation code from _PyObject_New() instead of a call to
1031 * PyObject_New() so we are able to allocate space for the object and
1032 * it's data buffer.
1033 */
1034 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1035 if (obj == NULL)
1036 return PyErr_NoMemory();
1037 obj = PyObject_INIT(obj, &PyUnicode_Type);
1038 if (obj == NULL)
1039 return NULL;
1040
1041 unicode = (PyCompactUnicodeObject *)obj;
1042 if (is_ascii)
1043 data = ((PyASCIIObject*)obj) + 1;
1044 else
1045 data = unicode + 1;
1046 _PyUnicode_LENGTH(unicode) = size;
1047 _PyUnicode_HASH(unicode) = -1;
1048 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001049 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 _PyUnicode_STATE(unicode).compact = 1;
1051 _PyUnicode_STATE(unicode).ready = 1;
1052 _PyUnicode_STATE(unicode).ascii = is_ascii;
1053 if (is_ascii) {
1054 ((char*)data)[size] = 0;
1055 _PyUnicode_WSTR(unicode) = NULL;
1056 }
Victor Stinner8f825062012-04-27 13:55:39 +02001057 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 ((char*)data)[size] = 0;
1059 _PyUnicode_WSTR(unicode) = NULL;
1060 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001061 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001062 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001063 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 else {
1065 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001066 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001067 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001069 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 ((Py_UCS4*)data)[size] = 0;
1071 if (is_sharing) {
1072 _PyUnicode_WSTR_LENGTH(unicode) = size;
1073 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1074 }
1075 else {
1076 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1077 _PyUnicode_WSTR(unicode) = NULL;
1078 }
1079 }
Victor Stinner8f825062012-04-27 13:55:39 +02001080#ifdef Py_DEBUG
1081 /* Fill the data with invalid characters to detect bugs earlier.
1082 _PyUnicode_CheckConsistency(str, 1) detects invalid characters,
1083 at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII
1084 and U+FFFFFFFF is an invalid character in Unicode 6.0. */
1085 memset(data, 0xff, size * kind);
1086#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001087 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001088 return obj;
1089}
1090
1091#if SIZEOF_WCHAR_T == 2
1092/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1093 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001094 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001095
1096 This function assumes that unicode can hold one more code point than wstr
1097 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001098static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001100 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001101{
1102 const wchar_t *iter;
1103 Py_UCS4 *ucs4_out;
1104
Victor Stinner910337b2011-10-03 03:20:16 +02001105 assert(unicode != NULL);
1106 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1108 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1109
1110 for (iter = begin; iter < end; ) {
1111 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1112 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001113 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1114 && (iter+1) < end
1115 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 {
Victor Stinner551ac952011-11-29 22:58:13 +01001117 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 iter += 2;
1119 }
1120 else {
1121 *ucs4_out++ = *iter;
1122 iter++;
1123 }
1124 }
1125 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1126 _PyUnicode_GET_LENGTH(unicode)));
1127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128}
1129#endif
1130
Victor Stinnercd9950f2011-10-02 00:34:53 +02001131static int
Victor Stinner488fa492011-12-12 00:01:39 +01001132unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001133{
Victor Stinner488fa492011-12-12 00:01:39 +01001134 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001135 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001136 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001137 return -1;
1138 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001139 return 0;
1140}
1141
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001142static int
1143_copy_characters(PyObject *to, Py_ssize_t to_start,
1144 PyObject *from, Py_ssize_t from_start,
1145 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 unsigned int from_kind, to_kind;
1148 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149
Victor Stinneree4544c2012-05-09 22:24:08 +02001150 assert(0 <= how_many);
1151 assert(0 <= from_start);
1152 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001154 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001155 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156
Victor Stinnerd3f08822012-05-29 12:57:52 +02001157 assert(PyUnicode_Check(to));
1158 assert(PyUnicode_IS_READY(to));
1159 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1160
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001161 if (how_many == 0)
1162 return 0;
1163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001164 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001165 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001167 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001168
Victor Stinnerf1852262012-06-16 16:38:26 +02001169#ifdef Py_DEBUG
1170 if (!check_maxchar
1171 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1172 {
1173 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1174 Py_UCS4 ch;
1175 Py_ssize_t i;
1176 for (i=0; i < how_many; i++) {
1177 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1178 assert(ch <= to_maxchar);
1179 }
1180 }
1181#endif
1182
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001183 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001184 if (check_maxchar
1185 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1186 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001187 /* Writing Latin-1 characters into an ASCII string requires to
1188 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001189 Py_UCS4 max_char;
1190 max_char = ucs1lib_find_max_char(from_data,
1191 (Py_UCS1*)from_data + how_many);
1192 if (max_char >= 128)
1193 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001194 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001195 Py_MEMCPY((char*)to_data + to_kind * to_start,
1196 (char*)from_data + from_kind * from_start,
1197 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001199 else if (from_kind == PyUnicode_1BYTE_KIND
1200 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001201 {
1202 _PyUnicode_CONVERT_BYTES(
1203 Py_UCS1, Py_UCS2,
1204 PyUnicode_1BYTE_DATA(from) + from_start,
1205 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1206 PyUnicode_2BYTE_DATA(to) + to_start
1207 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001208 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001209 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001210 && to_kind == PyUnicode_4BYTE_KIND)
1211 {
1212 _PyUnicode_CONVERT_BYTES(
1213 Py_UCS1, Py_UCS4,
1214 PyUnicode_1BYTE_DATA(from) + from_start,
1215 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1216 PyUnicode_4BYTE_DATA(to) + to_start
1217 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001218 }
1219 else if (from_kind == PyUnicode_2BYTE_KIND
1220 && to_kind == PyUnicode_4BYTE_KIND)
1221 {
1222 _PyUnicode_CONVERT_BYTES(
1223 Py_UCS2, Py_UCS4,
1224 PyUnicode_2BYTE_DATA(from) + from_start,
1225 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1226 PyUnicode_4BYTE_DATA(to) + to_start
1227 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001228 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001229 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001230 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1231
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001232 if (!check_maxchar) {
1233 if (from_kind == PyUnicode_2BYTE_KIND
1234 && to_kind == PyUnicode_1BYTE_KIND)
1235 {
1236 _PyUnicode_CONVERT_BYTES(
1237 Py_UCS2, Py_UCS1,
1238 PyUnicode_2BYTE_DATA(from) + from_start,
1239 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1240 PyUnicode_1BYTE_DATA(to) + to_start
1241 );
1242 }
1243 else if (from_kind == PyUnicode_4BYTE_KIND
1244 && to_kind == PyUnicode_1BYTE_KIND)
1245 {
1246 _PyUnicode_CONVERT_BYTES(
1247 Py_UCS4, Py_UCS1,
1248 PyUnicode_4BYTE_DATA(from) + from_start,
1249 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1250 PyUnicode_1BYTE_DATA(to) + to_start
1251 );
1252 }
1253 else if (from_kind == PyUnicode_4BYTE_KIND
1254 && to_kind == PyUnicode_2BYTE_KIND)
1255 {
1256 _PyUnicode_CONVERT_BYTES(
1257 Py_UCS4, Py_UCS2,
1258 PyUnicode_4BYTE_DATA(from) + from_start,
1259 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1260 PyUnicode_2BYTE_DATA(to) + to_start
1261 );
1262 }
1263 else {
1264 assert(0);
1265 return -1;
1266 }
1267 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001268 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001269 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001270 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001271 Py_ssize_t i;
1272
Victor Stinnera0702ab2011-09-29 14:14:38 +02001273 for (i=0; i < how_many; i++) {
1274 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001275 if (ch > to_maxchar)
1276 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001277 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1278 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001279 }
1280 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001281 return 0;
1282}
1283
Victor Stinnerd3f08822012-05-29 12:57:52 +02001284void
1285_PyUnicode_FastCopyCharacters(
1286 PyObject *to, Py_ssize_t to_start,
1287 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001288{
1289 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1290}
1291
1292Py_ssize_t
1293PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1294 PyObject *from, Py_ssize_t from_start,
1295 Py_ssize_t how_many)
1296{
1297 int err;
1298
1299 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1300 PyErr_BadInternalCall();
1301 return -1;
1302 }
1303
Benjamin Petersonbac79492012-01-14 13:34:47 -05001304 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001305 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001306 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001307 return -1;
1308
Victor Stinnerd3f08822012-05-29 12:57:52 +02001309 if (from_start < 0) {
1310 PyErr_SetString(PyExc_IndexError, "string index out of range");
1311 return -1;
1312 }
1313 if (to_start < 0) {
1314 PyErr_SetString(PyExc_IndexError, "string index out of range");
1315 return -1;
1316 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001317 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1318 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1319 PyErr_Format(PyExc_SystemError,
1320 "Cannot write %zi characters at %zi "
1321 "in a string of %zi characters",
1322 how_many, to_start, PyUnicode_GET_LENGTH(to));
1323 return -1;
1324 }
1325
1326 if (how_many == 0)
1327 return 0;
1328
Victor Stinner488fa492011-12-12 00:01:39 +01001329 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001330 return -1;
1331
1332 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1333 if (err) {
1334 PyErr_Format(PyExc_SystemError,
1335 "Cannot copy %s characters "
1336 "into a string of %s characters",
1337 unicode_kind_name(from),
1338 unicode_kind_name(to));
1339 return -1;
1340 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001341 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342}
1343
Victor Stinner17222162011-09-28 22:15:37 +02001344/* Find the maximum code point and count the number of surrogate pairs so a
1345 correct string length can be computed before converting a string to UCS4.
1346 This function counts single surrogates as a character and not as a pair.
1347
1348 Return 0 on success, or -1 on error. */
1349static int
1350find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1351 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352{
1353 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001354 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001355
Victor Stinnerc53be962011-10-02 21:33:54 +02001356 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001357 *num_surrogates = 0;
1358 *maxchar = 0;
1359
1360 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001362 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1363 && (iter+1) < end
1364 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001365 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001366 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 iter += 2;
1369 }
1370 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001372 {
1373 ch = *iter;
1374 iter++;
1375 }
1376 if (ch > *maxchar) {
1377 *maxchar = ch;
1378 if (*maxchar > MAX_UNICODE) {
1379 PyErr_Format(PyExc_ValueError,
1380 "character U+%x is not in range [U+0000; U+10ffff]",
1381 ch);
1382 return -1;
1383 }
1384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001385 }
1386 return 0;
1387}
1388
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001389int
1390_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391{
1392 wchar_t *end;
1393 Py_UCS4 maxchar = 0;
1394 Py_ssize_t num_surrogates;
1395#if SIZEOF_WCHAR_T == 2
1396 Py_ssize_t length_wo_surrogates;
1397#endif
1398
Georg Brandl7597add2011-10-05 16:36:47 +02001399 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001400 strings were created using _PyObject_New() and where no canonical
1401 representation (the str field) has been set yet aka strings
1402 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001403 assert(_PyUnicode_CHECK(unicode));
1404 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001406 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001407 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001408 /* Actually, it should neither be interned nor be anything else: */
1409 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001412 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001413 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415
1416 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001417 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1418 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 PyErr_NoMemory();
1420 return -1;
1421 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001422 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423 _PyUnicode_WSTR(unicode), end,
1424 PyUnicode_1BYTE_DATA(unicode));
1425 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1426 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1427 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1428 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001429 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001430 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001431 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001432 }
1433 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001434 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001435 _PyUnicode_UTF8(unicode) = NULL;
1436 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437 }
1438 PyObject_FREE(_PyUnicode_WSTR(unicode));
1439 _PyUnicode_WSTR(unicode) = NULL;
1440 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1441 }
1442 /* In this case we might have to convert down from 4-byte native
1443 wchar_t to 2-byte unicode. */
1444 else if (maxchar < 65536) {
1445 assert(num_surrogates == 0 &&
1446 "FindMaxCharAndNumSurrogatePairs() messed up");
1447
Victor Stinner506f5922011-09-28 22:34:18 +02001448#if SIZEOF_WCHAR_T == 2
1449 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001450 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001451 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1452 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1453 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001454 _PyUnicode_UTF8(unicode) = NULL;
1455 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001456#else
1457 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001459 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001460 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001461 PyErr_NoMemory();
1462 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463 }
Victor Stinner506f5922011-09-28 22:34:18 +02001464 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1465 _PyUnicode_WSTR(unicode), end,
1466 PyUnicode_2BYTE_DATA(unicode));
1467 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1468 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1469 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001470 _PyUnicode_UTF8(unicode) = NULL;
1471 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001472 PyObject_FREE(_PyUnicode_WSTR(unicode));
1473 _PyUnicode_WSTR(unicode) = NULL;
1474 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1475#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001476 }
1477 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1478 else {
1479#if SIZEOF_WCHAR_T == 2
1480 /* in case the native representation is 2-bytes, we need to allocate a
1481 new normalized 4-byte version. */
1482 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001483 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1484 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001485 PyErr_NoMemory();
1486 return -1;
1487 }
1488 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1489 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001490 _PyUnicode_UTF8(unicode) = NULL;
1491 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001492 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1493 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001494 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495 PyObject_FREE(_PyUnicode_WSTR(unicode));
1496 _PyUnicode_WSTR(unicode) = NULL;
1497 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1498#else
1499 assert(num_surrogates == 0);
1500
Victor Stinnerc3c74152011-10-02 20:39:55 +02001501 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001502 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001503 _PyUnicode_UTF8(unicode) = NULL;
1504 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1506#endif
1507 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1508 }
1509 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001510 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001511 return 0;
1512}
1513
Alexander Belopolsky40018472011-02-26 01:02:56 +00001514static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001515unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001516{
Walter Dörwald16807132007-05-25 13:52:07 +00001517 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001518 case SSTATE_NOT_INTERNED:
1519 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001520
Benjamin Peterson29060642009-01-31 22:14:21 +00001521 case SSTATE_INTERNED_MORTAL:
1522 /* revive dead object temporarily for DelItem */
1523 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001524 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 Py_FatalError(
1526 "deletion of interned string failed");
1527 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001528
Benjamin Peterson29060642009-01-31 22:14:21 +00001529 case SSTATE_INTERNED_IMMORTAL:
1530 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001531
Benjamin Peterson29060642009-01-31 22:14:21 +00001532 default:
1533 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001534 }
1535
Victor Stinner03490912011-10-03 23:45:12 +02001536 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001537 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001538 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001539 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001540 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1541 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001542
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001543 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001544}
1545
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001546#ifdef Py_DEBUG
1547static int
1548unicode_is_singleton(PyObject *unicode)
1549{
1550 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1551 if (unicode == unicode_empty)
1552 return 1;
1553 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1554 {
1555 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1556 if (ch < 256 && unicode_latin1[ch] == unicode)
1557 return 1;
1558 }
1559 return 0;
1560}
1561#endif
1562
Alexander Belopolsky40018472011-02-26 01:02:56 +00001563static int
Victor Stinner488fa492011-12-12 00:01:39 +01001564unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001565{
Victor Stinner488fa492011-12-12 00:01:39 +01001566 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001567 if (Py_REFCNT(unicode) != 1)
1568 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001569 if (_PyUnicode_HASH(unicode) != -1)
1570 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001571 if (PyUnicode_CHECK_INTERNED(unicode))
1572 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001573 if (!PyUnicode_CheckExact(unicode))
1574 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001575#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 /* singleton refcount is greater than 1 */
1577 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001578#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001579 return 1;
1580}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001581
Victor Stinnerfe226c02011-10-03 03:52:20 +02001582static int
1583unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1584{
1585 PyObject *unicode;
1586 Py_ssize_t old_length;
1587
1588 assert(p_unicode != NULL);
1589 unicode = *p_unicode;
1590
1591 assert(unicode != NULL);
1592 assert(PyUnicode_Check(unicode));
1593 assert(0 <= length);
1594
Victor Stinner910337b2011-10-03 03:20:16 +02001595 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001596 old_length = PyUnicode_WSTR_LENGTH(unicode);
1597 else
1598 old_length = PyUnicode_GET_LENGTH(unicode);
1599 if (old_length == length)
1600 return 0;
1601
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001602 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001603 _Py_INCREF_UNICODE_EMPTY();
1604 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001605 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001606 Py_DECREF(*p_unicode);
1607 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001608 return 0;
1609 }
1610
Victor Stinner488fa492011-12-12 00:01:39 +01001611 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001612 PyObject *copy = resize_copy(unicode, length);
1613 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001614 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001615 Py_DECREF(*p_unicode);
1616 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001617 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001618 }
1619
Victor Stinnerfe226c02011-10-03 03:52:20 +02001620 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001621 PyObject *new_unicode = resize_compact(unicode, length);
1622 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001623 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001624 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001625 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001626 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001627 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001628}
1629
Alexander Belopolsky40018472011-02-26 01:02:56 +00001630int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001631PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001632{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001633 PyObject *unicode;
1634 if (p_unicode == NULL) {
1635 PyErr_BadInternalCall();
1636 return -1;
1637 }
1638 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001639 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001640 {
1641 PyErr_BadInternalCall();
1642 return -1;
1643 }
1644 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001645}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001646
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001647static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001648unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1649 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001650{
1651 PyObject *result;
1652 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001653 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001654 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1655 return 0;
1656 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1657 maxchar);
1658 if (result == NULL)
1659 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001660 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 Py_DECREF(*p_unicode);
1662 *p_unicode = result;
1663 return 0;
1664}
1665
1666static int
1667unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1668 Py_UCS4 ch)
1669{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001670 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001671 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001672 return -1;
1673 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1674 PyUnicode_DATA(*p_unicode),
1675 (*pos)++, ch);
1676 return 0;
1677}
1678
Victor Stinnerc5166102012-02-22 13:55:02 +01001679/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001680
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001681 WARNING: The function doesn't copy the terminating null character and
1682 doesn't check the maximum character (may write a latin1 character in an
1683 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001684static void
1685unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1686 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001687{
1688 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1689 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001690 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001691
1692 switch (kind) {
1693 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001694 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001695 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001696 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001697 }
1698 case PyUnicode_2BYTE_KIND: {
1699 Py_UCS2 *start = (Py_UCS2 *)data + index;
1700 Py_UCS2 *ucs2 = start;
1701 assert(index <= PyUnicode_GET_LENGTH(unicode));
1702
Victor Stinner184252a2012-06-16 02:57:41 +02001703 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001704 *ucs2 = (Py_UCS2)*str;
1705
1706 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001707 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001708 }
1709 default: {
1710 Py_UCS4 *start = (Py_UCS4 *)data + index;
1711 Py_UCS4 *ucs4 = start;
1712 assert(kind == PyUnicode_4BYTE_KIND);
1713 assert(index <= PyUnicode_GET_LENGTH(unicode));
1714
Victor Stinner184252a2012-06-16 02:57:41 +02001715 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001716 *ucs4 = (Py_UCS4)*str;
1717
1718 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001719 }
1720 }
1721}
1722
1723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724static PyObject*
1725get_latin1_char(unsigned char ch)
1726{
Victor Stinnera464fc12011-10-02 20:39:30 +02001727 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001728 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001729 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001730 if (!unicode)
1731 return NULL;
1732 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001733 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 unicode_latin1[ch] = unicode;
1735 }
1736 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001737 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001738}
1739
Alexander Belopolsky40018472011-02-26 01:02:56 +00001740PyObject *
1741PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001742{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001743 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001744 Py_UCS4 maxchar = 0;
1745 Py_ssize_t num_surrogates;
1746
1747 if (u == NULL)
1748 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001749
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001750 /* If the Unicode data is known at construction time, we can apply
1751 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001754 if (size == 0)
1755 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 /* Single character Unicode objects in the Latin-1 range are
1758 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001759 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 return get_latin1_char((unsigned char)*u);
1761
1762 /* If not empty and not single character, copy the Unicode data
1763 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001764 if (find_maxchar_surrogates(u, u + size,
1765 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766 return NULL;
1767
Victor Stinner8faf8212011-12-08 22:14:11 +01001768 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001769 if (!unicode)
1770 return NULL;
1771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772 switch (PyUnicode_KIND(unicode)) {
1773 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001774 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1776 break;
1777 case PyUnicode_2BYTE_KIND:
1778#if Py_UNICODE_SIZE == 2
1779 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1780#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001781 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1783#endif
1784 break;
1785 case PyUnicode_4BYTE_KIND:
1786#if SIZEOF_WCHAR_T == 2
1787 /* This is the only case which has to process surrogates, thus
1788 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001789 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001790#else
1791 assert(num_surrogates == 0);
1792 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1793#endif
1794 break;
1795 default:
1796 assert(0 && "Impossible state");
1797 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001798
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001799 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001800}
1801
Alexander Belopolsky40018472011-02-26 01:02:56 +00001802PyObject *
1803PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001804{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001805 if (size < 0) {
1806 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001807 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001808 return NULL;
1809 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001810 if (u != NULL)
1811 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1812 else
1813 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001814}
1815
Alexander Belopolsky40018472011-02-26 01:02:56 +00001816PyObject *
1817PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001818{
1819 size_t size = strlen(u);
1820 if (size > PY_SSIZE_T_MAX) {
1821 PyErr_SetString(PyExc_OverflowError, "input too long");
1822 return NULL;
1823 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001824 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001825}
1826
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001827PyObject *
1828_PyUnicode_FromId(_Py_Identifier *id)
1829{
1830 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001831 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1832 strlen(id->string),
1833 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001834 if (!id->object)
1835 return NULL;
1836 PyUnicode_InternInPlace(&id->object);
1837 assert(!id->next);
1838 id->next = static_strings;
1839 static_strings = id;
1840 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001841 return id->object;
1842}
1843
1844void
1845_PyUnicode_ClearStaticStrings()
1846{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001847 _Py_Identifier *tmp, *s = static_strings;
1848 while (s) {
1849 Py_DECREF(s->object);
1850 s->object = NULL;
1851 tmp = s->next;
1852 s->next = NULL;
1853 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001854 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001855 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001856}
1857
Benjamin Peterson0df54292012-03-26 14:50:32 -04001858/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001859
Victor Stinnerd3f08822012-05-29 12:57:52 +02001860PyObject*
1861_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001862{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001863 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001864 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001865 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001866#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001867 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001868#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001869 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001870 }
Victor Stinner785938e2011-12-11 20:09:03 +01001871 unicode = PyUnicode_New(size, 127);
1872 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001873 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001874 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1875 assert(_PyUnicode_CheckConsistency(unicode, 1));
1876 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001877}
1878
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001879static Py_UCS4
1880kind_maxchar_limit(unsigned int kind)
1881{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001882 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001883 case PyUnicode_1BYTE_KIND:
1884 return 0x80;
1885 case PyUnicode_2BYTE_KIND:
1886 return 0x100;
1887 case PyUnicode_4BYTE_KIND:
1888 return 0x10000;
1889 default:
1890 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001891 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001892 }
1893}
1894
Victor Stinnere6abb482012-05-02 01:15:40 +02001895Py_LOCAL_INLINE(Py_UCS4)
1896align_maxchar(Py_UCS4 maxchar)
1897{
1898 if (maxchar <= 127)
1899 return 127;
1900 else if (maxchar <= 255)
1901 return 255;
1902 else if (maxchar <= 65535)
1903 return 65535;
1904 else
1905 return MAX_UNICODE;
1906}
1907
Victor Stinner702c7342011-10-05 13:50:52 +02001908static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001909_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001910{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001911 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001912 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001913
Serhiy Storchaka678db842013-01-26 12:16:36 +02001914 if (size == 0)
1915 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001917 if (size == 1)
1918 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001919
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001920 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001921 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922 if (!res)
1923 return NULL;
1924 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001925 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001927}
1928
Victor Stinnere57b1c02011-09-28 22:20:48 +02001929static PyObject*
1930_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001931{
1932 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001933 Py_UCS2 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);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001938 if (size == 1) {
1939 Py_UCS4 ch = u[0];
1940 if (ch < 256)
1941 return get_latin1_char((unsigned char)ch);
1942
1943 res = PyUnicode_New(1, ch);
1944 if (res == NULL)
1945 return NULL;
1946 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1947 assert(_PyUnicode_CheckConsistency(res, 1));
1948 return res;
1949 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001950
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001951 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001952 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 if (!res)
1954 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001955 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001956 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001957 else {
1958 _PyUnicode_CONVERT_BYTES(
1959 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1960 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001961 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962 return res;
1963}
1964
Victor Stinnere57b1c02011-09-28 22:20:48 +02001965static PyObject*
1966_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967{
1968 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001970
Serhiy Storchaka678db842013-01-26 12:16:36 +02001971 if (size == 0)
1972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001974 if (size == 1) {
1975 Py_UCS4 ch = u[0];
1976 if (ch < 256)
1977 return get_latin1_char((unsigned char)ch);
1978
1979 res = PyUnicode_New(1, ch);
1980 if (res == NULL)
1981 return NULL;
1982 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1983 assert(_PyUnicode_CheckConsistency(res, 1));
1984 return res;
1985 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001986
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001987 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001988 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989 if (!res)
1990 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001991 if (max_char < 256)
1992 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1993 PyUnicode_1BYTE_DATA(res));
1994 else if (max_char < 0x10000)
1995 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1996 PyUnicode_2BYTE_DATA(res));
1997 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001999 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 return res;
2001}
2002
2003PyObject*
2004PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2005{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002006 if (size < 0) {
2007 PyErr_SetString(PyExc_ValueError, "size must be positive");
2008 return NULL;
2009 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002010 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002011 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002012 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002014 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002015 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002016 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002018 PyErr_SetString(PyExc_SystemError, "invalid kind");
2019 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021}
2022
Victor Stinnerece58de2012-04-23 23:36:38 +02002023Py_UCS4
2024_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2025{
2026 enum PyUnicode_Kind kind;
2027 void *startptr, *endptr;
2028
2029 assert(PyUnicode_IS_READY(unicode));
2030 assert(0 <= start);
2031 assert(end <= PyUnicode_GET_LENGTH(unicode));
2032 assert(start <= end);
2033
2034 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2035 return PyUnicode_MAX_CHAR_VALUE(unicode);
2036
2037 if (start == end)
2038 return 127;
2039
Victor Stinner94d558b2012-04-27 22:26:58 +02002040 if (PyUnicode_IS_ASCII(unicode))
2041 return 127;
2042
Victor Stinnerece58de2012-04-23 23:36:38 +02002043 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002044 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002045 endptr = (char *)startptr + end * kind;
2046 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002047 switch(kind) {
2048 case PyUnicode_1BYTE_KIND:
2049 return ucs1lib_find_max_char(startptr, endptr);
2050 case PyUnicode_2BYTE_KIND:
2051 return ucs2lib_find_max_char(startptr, endptr);
2052 case PyUnicode_4BYTE_KIND:
2053 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002054 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002055 assert(0);
2056 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002057 }
2058}
2059
Victor Stinner25a4b292011-10-06 12:31:55 +02002060/* Ensure that a string uses the most efficient storage, if it is not the
2061 case: create a new string with of the right kind. Write NULL into *p_unicode
2062 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002063static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002064unicode_adjust_maxchar(PyObject **p_unicode)
2065{
2066 PyObject *unicode, *copy;
2067 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002068 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002069 unsigned int kind;
2070
2071 assert(p_unicode != NULL);
2072 unicode = *p_unicode;
2073 assert(PyUnicode_IS_READY(unicode));
2074 if (PyUnicode_IS_ASCII(unicode))
2075 return;
2076
2077 len = PyUnicode_GET_LENGTH(unicode);
2078 kind = PyUnicode_KIND(unicode);
2079 if (kind == PyUnicode_1BYTE_KIND) {
2080 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002081 max_char = ucs1lib_find_max_char(u, u + len);
2082 if (max_char >= 128)
2083 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002084 }
2085 else if (kind == PyUnicode_2BYTE_KIND) {
2086 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002087 max_char = ucs2lib_find_max_char(u, u + len);
2088 if (max_char >= 256)
2089 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002090 }
2091 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002092 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002093 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002094 max_char = ucs4lib_find_max_char(u, u + len);
2095 if (max_char >= 0x10000)
2096 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002097 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002098 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002099 if (copy != NULL)
2100 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002101 Py_DECREF(unicode);
2102 *p_unicode = copy;
2103}
2104
Victor Stinner034f6cf2011-09-30 02:26:44 +02002105PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002106_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002107{
Victor Stinner87af4f22011-11-21 23:03:47 +01002108 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002109 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002110
Victor Stinner034f6cf2011-09-30 02:26:44 +02002111 if (!PyUnicode_Check(unicode)) {
2112 PyErr_BadInternalCall();
2113 return NULL;
2114 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002115 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002116 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002117
Victor Stinner87af4f22011-11-21 23:03:47 +01002118 length = PyUnicode_GET_LENGTH(unicode);
2119 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002120 if (!copy)
2121 return NULL;
2122 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2123
Victor Stinner87af4f22011-11-21 23:03:47 +01002124 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2125 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002126 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002127 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002128}
2129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002130
Victor Stinnerbc603d12011-10-02 01:00:40 +02002131/* Widen Unicode objects to larger buffers. Don't write terminating null
2132 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002133
2134void*
2135_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2136{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002137 Py_ssize_t len;
2138 void *result;
2139 unsigned int skind;
2140
Benjamin Petersonbac79492012-01-14 13:34:47 -05002141 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002142 return NULL;
2143
2144 len = PyUnicode_GET_LENGTH(s);
2145 skind = PyUnicode_KIND(s);
2146 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002147 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002148 return NULL;
2149 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002150 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002151 case PyUnicode_2BYTE_KIND:
2152 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2153 if (!result)
2154 return PyErr_NoMemory();
2155 assert(skind == PyUnicode_1BYTE_KIND);
2156 _PyUnicode_CONVERT_BYTES(
2157 Py_UCS1, Py_UCS2,
2158 PyUnicode_1BYTE_DATA(s),
2159 PyUnicode_1BYTE_DATA(s) + len,
2160 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002161 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002162 case PyUnicode_4BYTE_KIND:
2163 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2164 if (!result)
2165 return PyErr_NoMemory();
2166 if (skind == PyUnicode_2BYTE_KIND) {
2167 _PyUnicode_CONVERT_BYTES(
2168 Py_UCS2, Py_UCS4,
2169 PyUnicode_2BYTE_DATA(s),
2170 PyUnicode_2BYTE_DATA(s) + len,
2171 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002172 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002173 else {
2174 assert(skind == PyUnicode_1BYTE_KIND);
2175 _PyUnicode_CONVERT_BYTES(
2176 Py_UCS1, Py_UCS4,
2177 PyUnicode_1BYTE_DATA(s),
2178 PyUnicode_1BYTE_DATA(s) + len,
2179 result);
2180 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002181 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002182 default:
2183 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184 }
Victor Stinner01698042011-10-04 00:04:26 +02002185 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002186 return NULL;
2187}
2188
2189static Py_UCS4*
2190as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2191 int copy_null)
2192{
2193 int kind;
2194 void *data;
2195 Py_ssize_t len, targetlen;
2196 if (PyUnicode_READY(string) == -1)
2197 return NULL;
2198 kind = PyUnicode_KIND(string);
2199 data = PyUnicode_DATA(string);
2200 len = PyUnicode_GET_LENGTH(string);
2201 targetlen = len;
2202 if (copy_null)
2203 targetlen++;
2204 if (!target) {
2205 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2206 PyErr_NoMemory();
2207 return NULL;
2208 }
2209 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2210 if (!target) {
2211 PyErr_NoMemory();
2212 return NULL;
2213 }
2214 }
2215 else {
2216 if (targetsize < targetlen) {
2217 PyErr_Format(PyExc_SystemError,
2218 "string is longer than the buffer");
2219 if (copy_null && 0 < targetsize)
2220 target[0] = 0;
2221 return NULL;
2222 }
2223 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002224 if (kind == PyUnicode_1BYTE_KIND) {
2225 Py_UCS1 *start = (Py_UCS1 *) data;
2226 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002228 else if (kind == PyUnicode_2BYTE_KIND) {
2229 Py_UCS2 *start = (Py_UCS2 *) data;
2230 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2231 }
2232 else {
2233 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002235 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 if (copy_null)
2237 target[len] = 0;
2238 return target;
2239}
2240
2241Py_UCS4*
2242PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2243 int copy_null)
2244{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002245 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 PyErr_BadInternalCall();
2247 return NULL;
2248 }
2249 return as_ucs4(string, target, targetsize, copy_null);
2250}
2251
2252Py_UCS4*
2253PyUnicode_AsUCS4Copy(PyObject *string)
2254{
2255 return as_ucs4(string, NULL, 0, 1);
2256}
2257
2258#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002259
Alexander Belopolsky40018472011-02-26 01:02:56 +00002260PyObject *
2261PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002262{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002263 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002264 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002265 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002266 PyErr_BadInternalCall();
2267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002268 }
2269
Martin v. Löwis790465f2008-04-05 20:41:37 +00002270 if (size == -1) {
2271 size = wcslen(w);
2272 }
2273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002275}
2276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002278
Walter Dörwald346737f2007-05-31 10:44:43 +00002279static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002280makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2281 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002282{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002283 *fmt++ = '%';
2284 if (width) {
2285 if (zeropad)
2286 *fmt++ = '0';
2287 fmt += sprintf(fmt, "%d", width);
2288 }
2289 if (precision)
2290 fmt += sprintf(fmt, ".%d", precision);
2291 if (longflag)
2292 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002293 else if (longlongflag) {
2294 /* longlongflag should only ever be nonzero on machines with
2295 HAVE_LONG_LONG defined */
2296#ifdef HAVE_LONG_LONG
2297 char *f = PY_FORMAT_LONG_LONG;
2298 while (*f)
2299 *fmt++ = *f++;
2300#else
2301 /* we shouldn't ever get here */
2302 assert(0);
2303 *fmt++ = 'l';
2304#endif
2305 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002306 else if (size_tflag) {
2307 char *f = PY_FORMAT_SIZE_T;
2308 while (*f)
2309 *fmt++ = *f++;
2310 }
2311 *fmt++ = c;
2312 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002313}
2314
Victor Stinner96865452011-03-01 23:44:09 +00002315/* helper for PyUnicode_FromFormatV() */
2316
2317static const char*
2318parse_format_flags(const char *f,
2319 int *p_width, int *p_precision,
2320 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2321{
2322 int width, precision, longflag, longlongflag, size_tflag;
2323
2324 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2325 f++;
2326 width = 0;
2327 while (Py_ISDIGIT((unsigned)*f))
2328 width = (width*10) + *f++ - '0';
2329 precision = 0;
2330 if (*f == '.') {
2331 f++;
2332 while (Py_ISDIGIT((unsigned)*f))
2333 precision = (precision*10) + *f++ - '0';
2334 if (*f == '%') {
2335 /* "%.3%s" => f points to "3" */
2336 f--;
2337 }
2338 }
2339 if (*f == '\0') {
2340 /* bogus format "%.1" => go backward, f points to "1" */
2341 f--;
2342 }
2343 if (p_width != NULL)
2344 *p_width = width;
2345 if (p_precision != NULL)
2346 *p_precision = precision;
2347
2348 /* Handle %ld, %lu, %lld and %llu. */
2349 longflag = 0;
2350 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002351 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002352
2353 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002354 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002355 longflag = 1;
2356 ++f;
2357 }
2358#ifdef HAVE_LONG_LONG
2359 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002360 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002361 longlongflag = 1;
2362 f += 2;
2363 }
2364#endif
2365 }
2366 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002367 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002368 size_tflag = 1;
2369 ++f;
2370 }
2371 if (p_longflag != NULL)
2372 *p_longflag = longflag;
2373 if (p_longlongflag != NULL)
2374 *p_longlongflag = longlongflag;
2375 if (p_size_tflag != NULL)
2376 *p_size_tflag = size_tflag;
2377 return f;
2378}
2379
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002380/* maximum number of characters required for output of %ld. 21 characters
2381 allows for 64-bit integers (in decimal) and an optional sign. */
2382#define MAX_LONG_CHARS 21
2383/* maximum number of characters required for output of %lld.
2384 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2385 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2386#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2387
Walter Dörwaldd2034312007-05-18 16:29:38 +00002388PyObject *
2389PyUnicode_FromFormatV(const char *format, va_list vargs)
2390{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 va_list count;
2392 Py_ssize_t callcount = 0;
2393 PyObject **callresults = NULL;
2394 PyObject **callresult = NULL;
2395 Py_ssize_t n = 0;
2396 int width = 0;
2397 int precision = 0;
2398 int zeropad;
2399 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002400 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002401 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002402 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2404 Py_UCS4 argmaxchar;
2405 Py_ssize_t numbersize = 0;
2406 char *numberresults = NULL;
2407 char *numberresult = NULL;
2408 Py_ssize_t i;
2409 int kind;
2410 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002411
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002412 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002413 /* step 1: count the number of %S/%R/%A/%s format specifications
2414 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2415 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002417 * also estimate a upper bound for all the number formats in the string,
2418 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002419 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002420 for (f = format; *f; f++) {
2421 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002422 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002423 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2424 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2425 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2426 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002429#ifdef HAVE_LONG_LONG
2430 if (longlongflag) {
2431 if (width < MAX_LONG_LONG_CHARS)
2432 width = MAX_LONG_LONG_CHARS;
2433 }
2434 else
2435#endif
2436 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2437 including sign. Decimal takes the most space. This
2438 isn't enough for octal. If a width is specified we
2439 need more (which we allocate later). */
2440 if (width < MAX_LONG_CHARS)
2441 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442
2443 /* account for the size + '\0' to separate numbers
2444 inside of the numberresults buffer */
2445 numbersize += (width + 1);
2446 }
2447 }
2448 else if ((unsigned char)*f > 127) {
2449 PyErr_Format(PyExc_ValueError,
2450 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2451 "string, got a non-ASCII byte: 0x%02x",
2452 (unsigned char)*f);
2453 return NULL;
2454 }
2455 }
2456 /* step 2: allocate memory for the results of
2457 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2458 if (callcount) {
2459 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2460 if (!callresults) {
2461 PyErr_NoMemory();
2462 return NULL;
2463 }
2464 callresult = callresults;
2465 }
2466 /* step 2.5: allocate memory for the results of formating numbers */
2467 if (numbersize) {
2468 numberresults = PyObject_Malloc(numbersize);
2469 if (!numberresults) {
2470 PyErr_NoMemory();
2471 goto fail;
2472 }
2473 numberresult = numberresults;
2474 }
2475
2476 /* step 3: format numbers and figure out how large a buffer we need */
2477 for (f = format; *f; f++) {
2478 if (*f == '%') {
2479 const char* p;
2480 int longflag;
2481 int longlongflag;
2482 int size_tflag;
2483 int numprinted;
2484
2485 p = f;
2486 zeropad = (f[1] == '0');
2487 f = parse_format_flags(f, &width, &precision,
2488 &longflag, &longlongflag, &size_tflag);
2489 switch (*f) {
2490 case 'c':
2491 {
Serhiy Storchaka8eeae212013-06-23 20:12:14 +03002492 int ordinal = va_arg(count, int);
2493 if (ordinal < 0 || ordinal > MAX_UNICODE) {
2494 PyErr_SetString(PyExc_OverflowError,
2495 "%c arg not in range(0x110000)");
2496 goto fail;
2497 }
2498 maxchar = Py_MAX(maxchar, (Py_UCS4)ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002499 n++;
2500 break;
2501 }
2502 case '%':
2503 n++;
2504 break;
2505 case 'i':
2506 case 'd':
2507 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2508 width, precision, *f);
2509 if (longflag)
2510 numprinted = sprintf(numberresult, fmt,
2511 va_arg(count, long));
2512#ifdef HAVE_LONG_LONG
2513 else if (longlongflag)
2514 numprinted = sprintf(numberresult, fmt,
2515 va_arg(count, PY_LONG_LONG));
2516#endif
2517 else if (size_tflag)
2518 numprinted = sprintf(numberresult, fmt,
2519 va_arg(count, Py_ssize_t));
2520 else
2521 numprinted = sprintf(numberresult, fmt,
2522 va_arg(count, int));
2523 n += numprinted;
2524 /* advance by +1 to skip over the '\0' */
2525 numberresult += (numprinted + 1);
2526 assert(*(numberresult - 1) == '\0');
2527 assert(*(numberresult - 2) != '\0');
2528 assert(numprinted >= 0);
2529 assert(numberresult <= numberresults + numbersize);
2530 break;
2531 case 'u':
2532 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2533 width, precision, 'u');
2534 if (longflag)
2535 numprinted = sprintf(numberresult, fmt,
2536 va_arg(count, unsigned long));
2537#ifdef HAVE_LONG_LONG
2538 else if (longlongflag)
2539 numprinted = sprintf(numberresult, fmt,
2540 va_arg(count, unsigned PY_LONG_LONG));
2541#endif
2542 else if (size_tflag)
2543 numprinted = sprintf(numberresult, fmt,
2544 va_arg(count, size_t));
2545 else
2546 numprinted = sprintf(numberresult, fmt,
2547 va_arg(count, unsigned int));
2548 n += numprinted;
2549 numberresult += (numprinted + 1);
2550 assert(*(numberresult - 1) == '\0');
2551 assert(*(numberresult - 2) != '\0');
2552 assert(numprinted >= 0);
2553 assert(numberresult <= numberresults + numbersize);
2554 break;
2555 case 'x':
2556 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2557 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2558 n += numprinted;
2559 numberresult += (numprinted + 1);
2560 assert(*(numberresult - 1) == '\0');
2561 assert(*(numberresult - 2) != '\0');
2562 assert(numprinted >= 0);
2563 assert(numberresult <= numberresults + numbersize);
2564 break;
2565 case 'p':
2566 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2567 /* %p is ill-defined: ensure leading 0x. */
2568 if (numberresult[1] == 'X')
2569 numberresult[1] = 'x';
2570 else if (numberresult[1] != 'x') {
2571 memmove(numberresult + 2, numberresult,
2572 strlen(numberresult) + 1);
2573 numberresult[0] = '0';
2574 numberresult[1] = 'x';
2575 numprinted += 2;
2576 }
2577 n += numprinted;
2578 numberresult += (numprinted + 1);
2579 assert(*(numberresult - 1) == '\0');
2580 assert(*(numberresult - 2) != '\0');
2581 assert(numprinted >= 0);
2582 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002583 break;
2584 case 's':
2585 {
2586 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002587 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002588 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002589 if (!str)
2590 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 /* since PyUnicode_DecodeUTF8 returns already flexible
2592 unicode objects, there is no need to call ready on them */
2593 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002594 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002596 /* Remember the str and switch to the next slot */
2597 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 break;
2599 }
2600 case 'U':
2601 {
2602 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002603 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 if (PyUnicode_READY(obj) == -1)
2605 goto fail;
2606 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002607 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002608 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 break;
2610 }
2611 case 'V':
2612 {
2613 PyObject *obj = va_arg(count, PyObject *);
2614 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002615 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002616 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002617 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002618 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 if (PyUnicode_READY(obj) == -1)
2620 goto fail;
2621 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002622 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002624 *callresult++ = NULL;
2625 }
2626 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002627 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002628 if (!str_obj)
2629 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002630 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002631 Py_DECREF(str_obj);
2632 goto fail;
2633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002634 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002635 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002636 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002637 *callresult++ = str_obj;
2638 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002639 break;
2640 }
2641 case 'S':
2642 {
2643 PyObject *obj = va_arg(count, PyObject *);
2644 PyObject *str;
2645 assert(obj);
2646 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002647 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002649 if (PyUnicode_READY(str) == -1) {
2650 Py_DECREF(str);
2651 goto fail;
2652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002653 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002654 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 /* Remember the str and switch to the next slot */
2657 *callresult++ = str;
2658 break;
2659 }
2660 case 'R':
2661 {
2662 PyObject *obj = va_arg(count, PyObject *);
2663 PyObject *repr;
2664 assert(obj);
2665 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002666 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002668 if (PyUnicode_READY(repr) == -1) {
2669 Py_DECREF(repr);
2670 goto fail;
2671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002673 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002675 /* Remember the repr and switch to the next slot */
2676 *callresult++ = repr;
2677 break;
2678 }
2679 case 'A':
2680 {
2681 PyObject *obj = va_arg(count, PyObject *);
2682 PyObject *ascii;
2683 assert(obj);
2684 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002685 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002686 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002687 if (PyUnicode_READY(ascii) == -1) {
2688 Py_DECREF(ascii);
2689 goto fail;
2690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002691 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Benjamin Peterson7e303732013-06-10 09:19:46 -07002692 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002693 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 /* Remember the repr and switch to the next slot */
2695 *callresult++ = ascii;
2696 break;
2697 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 default:
2699 /* if we stumble upon an unknown
2700 formatting code, copy the rest of
2701 the format string to the output
2702 string. (we cannot just skip the
2703 code, since there's no way to know
2704 what's in the argument list) */
2705 n += strlen(p);
2706 goto expand;
2707 }
2708 } else
2709 n++;
2710 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002711 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002712 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002714 we don't have to resize the string.
2715 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002716 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002717 if (!string)
2718 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002719 kind = PyUnicode_KIND(string);
2720 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002721 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002722 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002724 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002725 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002726 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002727
2728 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002729 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2730 /* checking for == because the last argument could be a empty
2731 string, which causes i to point to end, the assert at the end of
2732 the loop */
2733 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002734
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 switch (*f) {
2736 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002737 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002738 const int ordinal = va_arg(vargs, int);
2739 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002740 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002741 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002742 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002743 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002744 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002746 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002747 {
Victor Stinner184252a2012-06-16 02:57:41 +02002748 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 /* unused, since we already have the result */
2750 if (*f == 'p')
2751 (void) va_arg(vargs, void *);
2752 else
2753 (void) va_arg(vargs, int);
2754 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002755 len = strlen(numberresult);
2756 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002758 i += len;
2759 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002760 assert(*numberresult == '\0');
2761 numberresult++;
2762 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002764 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 case 's':
2766 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002767 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002769 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770 size = PyUnicode_GET_LENGTH(*callresult);
2771 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002772 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002773 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002774 /* We're done with the unicode()/repr() => forget it */
2775 Py_DECREF(*callresult);
2776 /* switch to next unicode()/repr() result */
2777 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002778 break;
2779 }
2780 case 'U':
2781 {
2782 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 Py_ssize_t size;
2784 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2785 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002786 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002788 break;
2789 }
2790 case 'V':
2791 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002793 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002794 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002795 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002796 size = PyUnicode_GET_LENGTH(obj);
2797 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002798 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002799 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002800 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002801 size = PyUnicode_GET_LENGTH(*callresult);
2802 assert(PyUnicode_KIND(*callresult) <=
2803 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002804 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002806 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002807 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002808 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002809 break;
2810 }
2811 case 'S':
2812 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002813 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002814 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002815 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002816 /* unused, since we already have the result */
2817 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002818 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002819 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002820 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002821 /* We're done with the unicode()/repr() => forget it */
2822 Py_DECREF(*callresult);
2823 /* switch to next unicode()/repr() result */
2824 ++callresult;
2825 break;
2826 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002827 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002828 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002829 break;
2830 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002831 {
2832 Py_ssize_t len = strlen(p);
2833 unicode_write_cstr(string, i, p, len);
2834 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002836 goto end;
2837 }
Victor Stinner184252a2012-06-16 02:57:41 +02002838 }
Victor Stinner1205f272010-09-11 00:54:47 +00002839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002840 else {
2841 assert(i < PyUnicode_GET_LENGTH(string));
2842 PyUnicode_WRITE(kind, data, i++, *f);
2843 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002844 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002846
Benjamin Peterson29060642009-01-31 22:14:21 +00002847 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002848 if (callresults)
2849 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850 if (numberresults)
2851 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002852 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002853 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002854 if (callresults) {
2855 PyObject **callresult2 = callresults;
2856 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002857 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002858 ++callresult2;
2859 }
2860 PyObject_Free(callresults);
2861 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002862 if (numberresults)
2863 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002864 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002865}
2866
Walter Dörwaldd2034312007-05-18 16:29:38 +00002867PyObject *
2868PyUnicode_FromFormat(const char *format, ...)
2869{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002870 PyObject* ret;
2871 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002872
2873#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002874 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002875#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002876 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002877#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002878 ret = PyUnicode_FromFormatV(format, vargs);
2879 va_end(vargs);
2880 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002881}
2882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883#ifdef HAVE_WCHAR_H
2884
Victor Stinner5593d8a2010-10-02 11:11:27 +00002885/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2886 convert a Unicode object to a wide character string.
2887
Victor Stinnerd88d9832011-09-06 02:00:05 +02002888 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002889 character) required to convert the unicode object. Ignore size argument.
2890
Victor Stinnerd88d9832011-09-06 02:00:05 +02002891 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002892 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002893 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002894static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002895unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002896 wchar_t *w,
2897 Py_ssize_t size)
2898{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002899 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002900 const wchar_t *wstr;
2901
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002902 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002903 if (wstr == NULL)
2904 return -1;
2905
Victor Stinner5593d8a2010-10-02 11:11:27 +00002906 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002907 if (size > res)
2908 size = res + 1;
2909 else
2910 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002911 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002912 return res;
2913 }
2914 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002915 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002916}
2917
2918Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002919PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002920 wchar_t *w,
2921 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922{
2923 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002924 PyErr_BadInternalCall();
2925 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002926 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002927 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002928}
2929
Victor Stinner137c34c2010-09-29 10:25:54 +00002930wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002931PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002932 Py_ssize_t *size)
2933{
2934 wchar_t* buffer;
2935 Py_ssize_t buflen;
2936
2937 if (unicode == NULL) {
2938 PyErr_BadInternalCall();
2939 return NULL;
2940 }
2941
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002942 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002943 if (buflen == -1)
2944 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002946 PyErr_NoMemory();
2947 return NULL;
2948 }
2949
Victor Stinner137c34c2010-09-29 10:25:54 +00002950 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2951 if (buffer == NULL) {
2952 PyErr_NoMemory();
2953 return NULL;
2954 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002955 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002956 if (buflen == -1) {
2957 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002958 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002959 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002960 if (size != NULL)
2961 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002962 return buffer;
2963}
2964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002965#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966
Alexander Belopolsky40018472011-02-26 01:02:56 +00002967PyObject *
2968PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002969{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002970 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002971 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 PyErr_SetString(PyExc_ValueError,
2973 "chr() arg not in range(0x110000)");
2974 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002975 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002976
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002977 if ((Py_UCS4)ordinal < 256)
2978 return get_latin1_char((unsigned char)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002980 v = PyUnicode_New(1, ordinal);
2981 if (v == NULL)
2982 return NULL;
2983 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002984 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002985 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002986}
2987
Alexander Belopolsky40018472011-02-26 01:02:56 +00002988PyObject *
2989PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002990{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002991 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002992 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002993 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002994 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002995 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002996 Py_INCREF(obj);
2997 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002998 }
2999 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003000 /* For a Unicode subtype that's not a Unicode object,
3001 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003002 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003003 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003004 PyErr_Format(PyExc_TypeError,
3005 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003006 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003007 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003008}
3009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003012 const char *encoding,
3013 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003014{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003015 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003016 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003017
Guido van Rossumd57fd912000-03-10 22:53:23 +00003018 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 PyErr_BadInternalCall();
3020 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003022
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003023 /* Decoding bytes objects is the most common case and should be fast */
3024 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003025 if (PyBytes_GET_SIZE(obj) == 0)
3026 _Py_RETURN_UNICODE_EMPTY();
3027 v = PyUnicode_Decode(
3028 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3029 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003030 return v;
3031 }
3032
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003033 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 PyErr_SetString(PyExc_TypeError,
3035 "decoding str is not supported");
3036 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003037 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003038
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003039 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3040 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3041 PyErr_Format(PyExc_TypeError,
3042 "coercing to str: need bytes, bytearray "
3043 "or buffer-like object, %.80s found",
3044 Py_TYPE(obj)->tp_name);
3045 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003046 }
Tim Petersced69f82003-09-16 20:30:58 +00003047
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003048 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003049 PyBuffer_Release(&buffer);
3050 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003051 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003052
Serhiy Storchaka05997252013-01-26 12:14:02 +02003053 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003054 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003055 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003056}
3057
Victor Stinner600d3be2010-06-10 12:00:55 +00003058/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003059 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3060 1 on success. */
Victor Stinner20b654a2013-01-03 01:08:58 +01003061int
3062_Py_normalize_encoding(const char *encoding,
Victor Stinner37296e82010-06-10 13:36:23 +00003063 char *lower,
3064 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003065{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003066 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003067 char *l;
3068 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003069
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003070 if (encoding == NULL) {
3071 strcpy(lower, "utf-8");
3072 return 1;
3073 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003074 e = encoding;
3075 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003076 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003077 while (*e) {
3078 if (l == l_end)
3079 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003080 if (Py_ISUPPER(*e)) {
3081 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003082 }
3083 else if (*e == '_') {
3084 *l++ = '-';
3085 e++;
3086 }
3087 else {
3088 *l++ = *e++;
3089 }
3090 }
3091 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003092 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003093}
3094
Alexander Belopolsky40018472011-02-26 01:02:56 +00003095PyObject *
3096PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003097 Py_ssize_t size,
3098 const char *encoding,
3099 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003100{
3101 PyObject *buffer = NULL, *unicode;
3102 Py_buffer info;
3103 char lower[11]; /* Enough for any encoding shortcut */
3104
Fred Drakee4315f52000-05-09 19:53:39 +00003105 /* Shortcuts for common default encodings */
Victor Stinner20b654a2013-01-03 01:08:58 +01003106 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003107 if ((strcmp(lower, "utf-8") == 0) ||
3108 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003109 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003110 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003111 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003112 (strcmp(lower, "iso-8859-1") == 0))
3113 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003114#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003115 else if (strcmp(lower, "mbcs") == 0)
3116 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003117#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003118 else if (strcmp(lower, "ascii") == 0)
3119 return PyUnicode_DecodeASCII(s, size, errors);
3120 else if (strcmp(lower, "utf-16") == 0)
3121 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3122 else if (strcmp(lower, "utf-32") == 0)
3123 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3124 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003125
3126 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003127 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003128 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003129 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003130 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003131 if (buffer == NULL)
3132 goto onError;
3133 unicode = PyCodec_Decode(buffer, encoding, errors);
3134 if (unicode == NULL)
3135 goto onError;
3136 if (!PyUnicode_Check(unicode)) {
3137 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003138 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003139 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003140 Py_DECREF(unicode);
3141 goto onError;
3142 }
3143 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003144 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003145
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003147 Py_XDECREF(buffer);
3148 return NULL;
3149}
3150
Alexander Belopolsky40018472011-02-26 01:02:56 +00003151PyObject *
3152PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003153 const char *encoding,
3154 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003155{
3156 PyObject *v;
3157
3158 if (!PyUnicode_Check(unicode)) {
3159 PyErr_BadArgument();
3160 goto onError;
3161 }
3162
3163 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003164 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003165
3166 /* Decode via the codec registry */
3167 v = PyCodec_Decode(unicode, encoding, errors);
3168 if (v == NULL)
3169 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003170 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003171
Benjamin Peterson29060642009-01-31 22:14:21 +00003172 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003173 return NULL;
3174}
3175
Alexander Belopolsky40018472011-02-26 01:02:56 +00003176PyObject *
3177PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003178 const char *encoding,
3179 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003180{
3181 PyObject *v;
3182
3183 if (!PyUnicode_Check(unicode)) {
3184 PyErr_BadArgument();
3185 goto onError;
3186 }
3187
3188 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003189 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003190
3191 /* Decode via the codec registry */
3192 v = PyCodec_Decode(unicode, encoding, errors);
3193 if (v == NULL)
3194 goto onError;
3195 if (!PyUnicode_Check(v)) {
3196 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003197 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003198 Py_TYPE(v)->tp_name);
3199 Py_DECREF(v);
3200 goto onError;
3201 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003202 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003203
Benjamin Peterson29060642009-01-31 22:14:21 +00003204 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003205 return NULL;
3206}
3207
Alexander Belopolsky40018472011-02-26 01:02:56 +00003208PyObject *
3209PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003210 Py_ssize_t size,
3211 const char *encoding,
3212 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003213{
3214 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003215
Guido van Rossumd57fd912000-03-10 22:53:23 +00003216 unicode = PyUnicode_FromUnicode(s, size);
3217 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003218 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003219 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3220 Py_DECREF(unicode);
3221 return v;
3222}
3223
Alexander Belopolsky40018472011-02-26 01:02:56 +00003224PyObject *
3225PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003226 const char *encoding,
3227 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003228{
3229 PyObject *v;
3230
3231 if (!PyUnicode_Check(unicode)) {
3232 PyErr_BadArgument();
3233 goto onError;
3234 }
3235
3236 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003237 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003238
3239 /* Encode via the codec registry */
3240 v = PyCodec_Encode(unicode, encoding, errors);
3241 if (v == NULL)
3242 goto onError;
3243 return v;
3244
Benjamin Peterson29060642009-01-31 22:14:21 +00003245 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003246 return NULL;
3247}
3248
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003249static size_t
3250wcstombs_errorpos(const wchar_t *wstr)
3251{
3252 size_t len;
3253#if SIZEOF_WCHAR_T == 2
3254 wchar_t buf[3];
3255#else
3256 wchar_t buf[2];
3257#endif
3258 char outbuf[MB_LEN_MAX];
3259 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003260
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003261#if SIZEOF_WCHAR_T == 2
3262 buf[2] = 0;
3263#else
3264 buf[1] = 0;
3265#endif
3266 start = wstr;
3267 while (*wstr != L'\0')
3268 {
3269 previous = wstr;
3270#if SIZEOF_WCHAR_T == 2
3271 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3272 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3273 {
3274 buf[0] = wstr[0];
3275 buf[1] = wstr[1];
3276 wstr += 2;
3277 }
3278 else {
3279 buf[0] = *wstr;
3280 buf[1] = 0;
3281 wstr++;
3282 }
3283#else
3284 buf[0] = *wstr;
3285 wstr++;
3286#endif
3287 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003288 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003289 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 }
3291
3292 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 return 0;
3294}
3295
Victor Stinner1b579672011-12-17 05:47:23 +01003296static int
3297locale_error_handler(const char *errors, int *surrogateescape)
3298{
3299 if (errors == NULL) {
3300 *surrogateescape = 0;
3301 return 0;
3302 }
3303
3304 if (strcmp(errors, "strict") == 0) {
3305 *surrogateescape = 0;
3306 return 0;
3307 }
3308 if (strcmp(errors, "surrogateescape") == 0) {
3309 *surrogateescape = 1;
3310 return 0;
3311 }
3312 PyErr_Format(PyExc_ValueError,
3313 "only 'strict' and 'surrogateescape' error handlers "
3314 "are supported, not '%s'",
3315 errors);
3316 return -1;
3317}
3318
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003319PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003320PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003321{
3322 Py_ssize_t wlen, wlen2;
3323 wchar_t *wstr;
3324 PyObject *bytes = NULL;
3325 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003326 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003327 PyObject *exc;
3328 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003329 int surrogateescape;
3330
3331 if (locale_error_handler(errors, &surrogateescape) < 0)
3332 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003333
3334 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3335 if (wstr == NULL)
3336 return NULL;
3337
3338 wlen2 = wcslen(wstr);
3339 if (wlen2 != wlen) {
3340 PyMem_Free(wstr);
3341 PyErr_SetString(PyExc_TypeError, "embedded null character");
3342 return NULL;
3343 }
3344
3345 if (surrogateescape) {
3346 /* locale encoding with surrogateescape */
3347 char *str;
3348
3349 str = _Py_wchar2char(wstr, &error_pos);
3350 if (str == NULL) {
3351 if (error_pos == (size_t)-1) {
3352 PyErr_NoMemory();
3353 PyMem_Free(wstr);
3354 return NULL;
3355 }
3356 else {
3357 goto encode_error;
3358 }
3359 }
3360 PyMem_Free(wstr);
3361
3362 bytes = PyBytes_FromString(str);
3363 PyMem_Free(str);
3364 }
3365 else {
3366 size_t len, len2;
3367
3368 len = wcstombs(NULL, wstr, 0);
3369 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003370 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 goto encode_error;
3372 }
3373
3374 bytes = PyBytes_FromStringAndSize(NULL, len);
3375 if (bytes == NULL) {
3376 PyMem_Free(wstr);
3377 return NULL;
3378 }
3379
3380 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3381 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003382 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003383 goto encode_error;
3384 }
3385 PyMem_Free(wstr);
3386 }
3387 return bytes;
3388
3389encode_error:
3390 errmsg = strerror(errno);
3391 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003392
3393 if (error_pos == (size_t)-1)
3394 error_pos = wcstombs_errorpos(wstr);
3395
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396 PyMem_Free(wstr);
3397 Py_XDECREF(bytes);
3398
Victor Stinner2f197072011-12-17 07:08:30 +01003399 if (errmsg != NULL) {
3400 size_t errlen;
3401 wstr = _Py_char2wchar(errmsg, &errlen);
3402 if (wstr != NULL) {
3403 reason = PyUnicode_FromWideChar(wstr, errlen);
3404 PyMem_Free(wstr);
3405 } else
3406 errmsg = NULL;
3407 }
3408 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003409 reason = PyUnicode_FromString(
3410 "wcstombs() encountered an unencodable "
3411 "wide character");
3412 if (reason == NULL)
3413 return NULL;
3414
3415 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3416 "locale", unicode,
3417 (Py_ssize_t)error_pos,
3418 (Py_ssize_t)(error_pos+1),
3419 reason);
3420 Py_DECREF(reason);
3421 if (exc != NULL) {
3422 PyCodec_StrictErrors(exc);
3423 Py_XDECREF(exc);
3424 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003425 return NULL;
3426}
3427
Victor Stinnerad158722010-10-27 00:25:46 +00003428PyObject *
3429PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003430{
Victor Stinner99b95382011-07-04 14:23:54 +02003431#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003432 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003433#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003434 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003435#else
Victor Stinner793b5312011-04-27 00:24:21 +02003436 PyInterpreterState *interp = PyThreadState_GET()->interp;
3437 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3438 cannot use it to encode and decode filenames before it is loaded. Load
3439 the Python codec requires to encode at least its own filename. Use the C
3440 version of the locale codec until the codec registry is initialized and
3441 the Python codec is loaded.
3442
3443 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3444 cannot only rely on it: check also interp->fscodec_initialized for
3445 subinterpreters. */
3446 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003447 return PyUnicode_AsEncodedString(unicode,
3448 Py_FileSystemDefaultEncoding,
3449 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003450 }
3451 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003452 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003453 }
Victor Stinnerad158722010-10-27 00:25:46 +00003454#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003455}
3456
Alexander Belopolsky40018472011-02-26 01:02:56 +00003457PyObject *
3458PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003459 const char *encoding,
3460 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003461{
3462 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003463 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003464
Guido van Rossumd57fd912000-03-10 22:53:23 +00003465 if (!PyUnicode_Check(unicode)) {
3466 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003467 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468 }
Fred Drakee4315f52000-05-09 19:53:39 +00003469
Fred Drakee4315f52000-05-09 19:53:39 +00003470 /* Shortcuts for common default encodings */
Victor Stinner20b654a2013-01-03 01:08:58 +01003471 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003472 if ((strcmp(lower, "utf-8") == 0) ||
3473 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003474 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003475 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003476 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003477 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003478 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003479 }
Victor Stinner37296e82010-06-10 13:36:23 +00003480 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003481 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003482 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003483 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003484#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003485 else if (strcmp(lower, "mbcs") == 0)
3486 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003487#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003488 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003489 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003490 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003491
3492 /* Encode via the codec registry */
3493 v = PyCodec_Encode(unicode, encoding, errors);
3494 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003495 return NULL;
3496
3497 /* The normal path */
3498 if (PyBytes_Check(v))
3499 return v;
3500
3501 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003502 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003503 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003504 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003505
3506 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3507 "encoder %s returned bytearray instead of bytes",
3508 encoding);
3509 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003510 Py_DECREF(v);
3511 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003512 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003513
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003514 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3515 Py_DECREF(v);
3516 return b;
3517 }
3518
3519 PyErr_Format(PyExc_TypeError,
3520 "encoder did not return a bytes object (type=%.400s)",
3521 Py_TYPE(v)->tp_name);
3522 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003523 return NULL;
3524}
3525
Alexander Belopolsky40018472011-02-26 01:02:56 +00003526PyObject *
3527PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003528 const char *encoding,
3529 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003530{
3531 PyObject *v;
3532
3533 if (!PyUnicode_Check(unicode)) {
3534 PyErr_BadArgument();
3535 goto onError;
3536 }
3537
3538 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003539 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003540
3541 /* Encode via the codec registry */
3542 v = PyCodec_Encode(unicode, encoding, errors);
3543 if (v == NULL)
3544 goto onError;
3545 if (!PyUnicode_Check(v)) {
3546 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003547 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003548 Py_TYPE(v)->tp_name);
3549 Py_DECREF(v);
3550 goto onError;
3551 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003552 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003553
Benjamin Peterson29060642009-01-31 22:14:21 +00003554 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003555 return NULL;
3556}
3557
Victor Stinner2f197072011-12-17 07:08:30 +01003558static size_t
3559mbstowcs_errorpos(const char *str, size_t len)
3560{
3561#ifdef HAVE_MBRTOWC
3562 const char *start = str;
3563 mbstate_t mbs;
3564 size_t converted;
3565 wchar_t ch;
3566
3567 memset(&mbs, 0, sizeof mbs);
3568 while (len)
3569 {
3570 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3571 if (converted == 0)
3572 /* Reached end of string */
3573 break;
3574 if (converted == (size_t)-1 || converted == (size_t)-2) {
3575 /* Conversion error or incomplete character */
3576 return str - start;
3577 }
3578 else {
3579 str += converted;
3580 len -= converted;
3581 }
3582 }
3583 /* failed to find the undecodable byte sequence */
3584 return 0;
3585#endif
3586 return 0;
3587}
3588
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003589PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003590PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003591 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003592{
3593 wchar_t smallbuf[256];
3594 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3595 wchar_t *wstr;
3596 size_t wlen, wlen2;
3597 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003598 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003599 size_t error_pos;
3600 char *errmsg;
3601 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003602
3603 if (locale_error_handler(errors, &surrogateescape) < 0)
3604 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003605
3606 if (str[len] != '\0' || len != strlen(str)) {
3607 PyErr_SetString(PyExc_TypeError, "embedded null character");
3608 return NULL;
3609 }
3610
3611 if (surrogateescape)
3612 {
3613 wstr = _Py_char2wchar(str, &wlen);
3614 if (wstr == NULL) {
3615 if (wlen == (size_t)-1)
3616 PyErr_NoMemory();
3617 else
3618 PyErr_SetFromErrno(PyExc_OSError);
3619 return NULL;
3620 }
3621
3622 unicode = PyUnicode_FromWideChar(wstr, wlen);
3623 PyMem_Free(wstr);
3624 }
3625 else {
3626#ifndef HAVE_BROKEN_MBSTOWCS
3627 wlen = mbstowcs(NULL, str, 0);
3628#else
3629 wlen = len;
3630#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003631 if (wlen == (size_t)-1)
3632 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003633 if (wlen+1 <= smallbuf_len) {
3634 wstr = smallbuf;
3635 }
3636 else {
3637 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3638 return PyErr_NoMemory();
3639
3640 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3641 if (!wstr)
3642 return PyErr_NoMemory();
3643 }
3644
3645 /* This shouldn't fail now */
3646 wlen2 = mbstowcs(wstr, str, wlen+1);
3647 if (wlen2 == (size_t)-1) {
3648 if (wstr != smallbuf)
3649 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003650 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003651 }
3652#ifdef HAVE_BROKEN_MBSTOWCS
3653 assert(wlen2 == wlen);
3654#endif
3655 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3656 if (wstr != smallbuf)
3657 PyMem_Free(wstr);
3658 }
3659 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003660
3661decode_error:
3662 errmsg = strerror(errno);
3663 assert(errmsg != NULL);
3664
3665 error_pos = mbstowcs_errorpos(str, len);
3666 if (errmsg != NULL) {
3667 size_t errlen;
3668 wstr = _Py_char2wchar(errmsg, &errlen);
3669 if (wstr != NULL) {
3670 reason = PyUnicode_FromWideChar(wstr, errlen);
3671 PyMem_Free(wstr);
3672 } else
3673 errmsg = NULL;
3674 }
3675 if (errmsg == NULL)
3676 reason = PyUnicode_FromString(
3677 "mbstowcs() encountered an invalid multibyte sequence");
3678 if (reason == NULL)
3679 return NULL;
3680
3681 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3682 "locale", str, len,
3683 (Py_ssize_t)error_pos,
3684 (Py_ssize_t)(error_pos+1),
3685 reason);
3686 Py_DECREF(reason);
3687 if (exc != NULL) {
3688 PyCodec_StrictErrors(exc);
3689 Py_XDECREF(exc);
3690 }
3691 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003692}
3693
3694PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003695PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003696{
3697 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003698 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003699}
3700
3701
3702PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003703PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003704 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003705 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3706}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003707
Christian Heimes5894ba72007-11-04 11:43:14 +00003708PyObject*
3709PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3710{
Victor Stinner99b95382011-07-04 14:23:54 +02003711#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003712 return PyUnicode_DecodeMBCS(s, size, NULL);
3713#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003714 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003715#else
Victor Stinner793b5312011-04-27 00:24:21 +02003716 PyInterpreterState *interp = PyThreadState_GET()->interp;
3717 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3718 cannot use it to encode and decode filenames before it is loaded. Load
3719 the Python codec requires to encode at least its own filename. Use the C
3720 version of the locale codec until the codec registry is initialized and
3721 the Python codec is loaded.
3722
3723 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3724 cannot only rely on it: check also interp->fscodec_initialized for
3725 subinterpreters. */
3726 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003727 return PyUnicode_Decode(s, size,
3728 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003729 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003730 }
3731 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003732 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003733 }
Victor Stinnerad158722010-10-27 00:25:46 +00003734#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003735}
3736
Martin v. Löwis011e8422009-05-05 04:43:17 +00003737
3738int
Antoine Pitrou13348842012-01-29 18:36:34 +01003739_PyUnicode_HasNULChars(PyObject* s)
3740{
3741 static PyObject *nul = NULL;
3742
3743 if (nul == NULL)
3744 nul = PyUnicode_FromStringAndSize("\0", 1);
3745 if (nul == NULL)
3746 return -1;
3747 return PyUnicode_Contains(s, nul);
3748}
3749
3750
3751int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003752PyUnicode_FSConverter(PyObject* arg, void* addr)
3753{
3754 PyObject *output = NULL;
3755 Py_ssize_t size;
3756 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003757 if (arg == NULL) {
3758 Py_DECREF(*(PyObject**)addr);
3759 return 1;
3760 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003761 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003762 output = arg;
3763 Py_INCREF(output);
3764 }
3765 else {
3766 arg = PyUnicode_FromObject(arg);
3767 if (!arg)
3768 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003769 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003770 Py_DECREF(arg);
3771 if (!output)
3772 return 0;
3773 if (!PyBytes_Check(output)) {
3774 Py_DECREF(output);
3775 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3776 return 0;
3777 }
3778 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003779 size = PyBytes_GET_SIZE(output);
3780 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003781 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003782 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003783 Py_DECREF(output);
3784 return 0;
3785 }
3786 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003787 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003788}
3789
3790
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003791int
3792PyUnicode_FSDecoder(PyObject* arg, void* addr)
3793{
3794 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003795 if (arg == NULL) {
3796 Py_DECREF(*(PyObject**)addr);
3797 return 1;
3798 }
3799 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003800 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003802 output = arg;
3803 Py_INCREF(output);
3804 }
3805 else {
3806 arg = PyBytes_FromObject(arg);
3807 if (!arg)
3808 return 0;
3809 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3810 PyBytes_GET_SIZE(arg));
3811 Py_DECREF(arg);
3812 if (!output)
3813 return 0;
3814 if (!PyUnicode_Check(output)) {
3815 Py_DECREF(output);
3816 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3817 return 0;
3818 }
3819 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003820 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003821 Py_DECREF(output);
3822 return 0;
3823 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003824 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003825 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003826 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3827 Py_DECREF(output);
3828 return 0;
3829 }
3830 *(PyObject**)addr = output;
3831 return Py_CLEANUP_SUPPORTED;
3832}
3833
3834
Martin v. Löwis5b222132007-06-10 09:51:05 +00003835char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003837{
Christian Heimesf3863112007-11-22 07:46:41 +00003838 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003840 if (!PyUnicode_Check(unicode)) {
3841 PyErr_BadArgument();
3842 return NULL;
3843 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003844 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003845 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003846
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003847 if (PyUnicode_UTF8(unicode) == NULL) {
3848 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3850 if (bytes == NULL)
3851 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003852 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3853 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854 Py_DECREF(bytes);
3855 return NULL;
3856 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003857 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3858 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3859 PyBytes_AS_STRING(bytes),
3860 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861 Py_DECREF(bytes);
3862 }
3863
3864 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003865 *psize = PyUnicode_UTF8_LENGTH(unicode);
3866 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003867}
3868
3869char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003870PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003871{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3873}
3874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875Py_UNICODE *
3876PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3877{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878 const unsigned char *one_byte;
3879#if SIZEOF_WCHAR_T == 4
3880 const Py_UCS2 *two_bytes;
3881#else
3882 const Py_UCS4 *four_bytes;
3883 const Py_UCS4 *ucs4_end;
3884 Py_ssize_t num_surrogates;
3885#endif
3886 wchar_t *w;
3887 wchar_t *wchar_end;
3888
3889 if (!PyUnicode_Check(unicode)) {
3890 PyErr_BadArgument();
3891 return NULL;
3892 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003893 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003894 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003895 assert(_PyUnicode_KIND(unicode) != 0);
3896 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003897
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003898 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003900 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3901 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 num_surrogates = 0;
3903
3904 for (; four_bytes < ucs4_end; ++four_bytes) {
3905 if (*four_bytes > 0xFFFF)
3906 ++num_surrogates;
3907 }
3908
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003909 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3910 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3911 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912 PyErr_NoMemory();
3913 return NULL;
3914 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003915 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003917 w = _PyUnicode_WSTR(unicode);
3918 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3919 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3921 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003922 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003924 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3925 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 }
3927 else
3928 *w = *four_bytes;
3929
3930 if (w > wchar_end) {
3931 assert(0 && "Miscalculated string end");
3932 }
3933 }
3934 *w = 0;
3935#else
3936 /* sizeof(wchar_t) == 4 */
3937 Py_FatalError("Impossible unicode object state, wstr and str "
3938 "should share memory already.");
3939 return NULL;
3940#endif
3941 }
3942 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003943 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3944 (_PyUnicode_LENGTH(unicode) + 1));
3945 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946 PyErr_NoMemory();
3947 return NULL;
3948 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003949 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3950 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3951 w = _PyUnicode_WSTR(unicode);
3952 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003954 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3955 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003956 for (; w < wchar_end; ++one_byte, ++w)
3957 *w = *one_byte;
3958 /* null-terminate the wstr */
3959 *w = 0;
3960 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003961 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003963 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003964 for (; w < wchar_end; ++two_bytes, ++w)
3965 *w = *two_bytes;
3966 /* null-terminate the wstr */
3967 *w = 0;
3968#else
3969 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003970 PyObject_FREE(_PyUnicode_WSTR(unicode));
3971 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972 Py_FatalError("Impossible unicode object state, wstr "
3973 "and str should share memory already.");
3974 return NULL;
3975#endif
3976 }
3977 else {
3978 assert(0 && "This should never happen.");
3979 }
3980 }
3981 }
3982 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003983 *size = PyUnicode_WSTR_LENGTH(unicode);
3984 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003985}
3986
Alexander Belopolsky40018472011-02-26 01:02:56 +00003987Py_UNICODE *
3988PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003989{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003991}
3992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993
Alexander Belopolsky40018472011-02-26 01:02:56 +00003994Py_ssize_t
3995PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003996{
3997 if (!PyUnicode_Check(unicode)) {
3998 PyErr_BadArgument();
3999 goto onError;
4000 }
4001 return PyUnicode_GET_SIZE(unicode);
4002
Benjamin Peterson29060642009-01-31 22:14:21 +00004003 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004004 return -1;
4005}
4006
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007Py_ssize_t
4008PyUnicode_GetLength(PyObject *unicode)
4009{
Victor Stinner07621332012-06-16 04:53:46 +02004010 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 PyErr_BadArgument();
4012 return -1;
4013 }
Victor Stinner07621332012-06-16 04:53:46 +02004014 if (PyUnicode_READY(unicode) == -1)
4015 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004016 return PyUnicode_GET_LENGTH(unicode);
4017}
4018
4019Py_UCS4
4020PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4021{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004022 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4023 PyErr_BadArgument();
4024 return (Py_UCS4)-1;
4025 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004026 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004027 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004028 return (Py_UCS4)-1;
4029 }
4030 return PyUnicode_READ_CHAR(unicode, index);
4031}
4032
4033int
4034PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4035{
4036 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004037 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 return -1;
4039 }
Victor Stinner488fa492011-12-12 00:01:39 +01004040 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004041 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004042 PyErr_SetString(PyExc_IndexError, "string index out of range");
4043 return -1;
4044 }
Victor Stinner488fa492011-12-12 00:01:39 +01004045 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004046 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004047 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4048 PyErr_SetString(PyExc_ValueError, "character out of range");
4049 return -1;
4050 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004051 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4052 index, ch);
4053 return 0;
4054}
4055
Alexander Belopolsky40018472011-02-26 01:02:56 +00004056const char *
4057PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004058{
Victor Stinner42cb4622010-09-01 19:39:01 +00004059 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004060}
4061
Victor Stinner554f3f02010-06-16 23:33:54 +00004062/* create or adjust a UnicodeDecodeError */
4063static void
4064make_decode_exception(PyObject **exceptionObject,
4065 const char *encoding,
4066 const char *input, Py_ssize_t length,
4067 Py_ssize_t startpos, Py_ssize_t endpos,
4068 const char *reason)
4069{
4070 if (*exceptionObject == NULL) {
4071 *exceptionObject = PyUnicodeDecodeError_Create(
4072 encoding, input, length, startpos, endpos, reason);
4073 }
4074 else {
4075 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4076 goto onError;
4077 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4078 goto onError;
4079 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4080 goto onError;
4081 }
4082 return;
4083
4084onError:
4085 Py_DECREF(*exceptionObject);
4086 *exceptionObject = NULL;
4087}
4088
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004089/* error handling callback helper:
4090 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004091 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092 and adjust various state variables.
4093 return 0 on success, -1 on error
4094*/
4095
Alexander Belopolsky40018472011-02-26 01:02:56 +00004096static int
4097unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004098 const char *encoding, const char *reason,
4099 const char **input, const char **inend, Py_ssize_t *startinpos,
4100 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004101 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004103 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004104
4105 PyObject *restuple = NULL;
4106 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004107 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004108 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004109 Py_ssize_t requiredsize;
4110 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004111 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004112 int res = -1;
4113
Victor Stinner596a6c42011-11-09 00:02:18 +01004114 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4115 outsize = PyUnicode_GET_LENGTH(*output);
4116 else
4117 outsize = _PyUnicode_WSTR_LENGTH(*output);
4118
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004120 *errorHandler = PyCodec_LookupError(errors);
4121 if (*errorHandler == NULL)
4122 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004123 }
4124
Victor Stinner554f3f02010-06-16 23:33:54 +00004125 make_decode_exception(exceptionObject,
4126 encoding,
4127 *input, *inend - *input,
4128 *startinpos, *endinpos,
4129 reason);
4130 if (*exceptionObject == NULL)
4131 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004132
4133 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4134 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004135 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004136 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004137 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004138 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004139 }
4140 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004141 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004142 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004143 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004144
4145 /* Copy back the bytes variables, which might have been modified by the
4146 callback */
4147 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4148 if (!inputobj)
4149 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004150 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004151 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004152 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004153 *input = PyBytes_AS_STRING(inputobj);
4154 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004155 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004156 /* we can DECREF safely, as the exception has another reference,
4157 so the object won't go away. */
4158 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004160 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004161 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004162 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004163 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4164 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004165 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004166
Victor Stinner596a6c42011-11-09 00:02:18 +01004167 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4168 /* need more space? (at least enough for what we
4169 have+the replacement+the rest of the string (starting
4170 at the new input position), so we won't have to check space
4171 when there are no errors in the rest of the string) */
4172 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4173 requiredsize = *outpos + replen + insize-newpos;
4174 if (requiredsize > outsize) {
4175 if (requiredsize<2*outsize)
4176 requiredsize = 2*outsize;
4177 if (unicode_resize(output, requiredsize) < 0)
4178 goto onError;
4179 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004180 if (unicode_widen(output, *outpos,
4181 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004182 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004183 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004184 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004185 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004186 else {
4187 wchar_t *repwstr;
4188 Py_ssize_t repwlen;
4189 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4190 if (repwstr == NULL)
4191 goto onError;
4192 /* need more space? (at least enough for what we
4193 have+the replacement+the rest of the string (starting
4194 at the new input position), so we won't have to check space
4195 when there are no errors in the rest of the string) */
4196 requiredsize = *outpos + repwlen + insize-newpos;
4197 if (requiredsize > outsize) {
4198 if (requiredsize < 2*outsize)
4199 requiredsize = 2*outsize;
4200 if (unicode_resize(output, requiredsize) < 0)
4201 goto onError;
4202 }
4203 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4204 *outpos += repwlen;
4205 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004206 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004207 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004208
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209 /* we made it! */
4210 res = 0;
4211
Benjamin Peterson29060642009-01-31 22:14:21 +00004212 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004213 Py_XDECREF(restuple);
4214 return res;
4215}
4216
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004217/* --- UTF-7 Codec -------------------------------------------------------- */
4218
Antoine Pitrou244651a2009-05-04 18:56:13 +00004219/* See RFC2152 for details. We encode conservatively and decode liberally. */
4220
4221/* Three simple macros defining base-64. */
4222
4223/* Is c a base-64 character? */
4224
4225#define IS_BASE64(c) \
4226 (((c) >= 'A' && (c) <= 'Z') || \
4227 ((c) >= 'a' && (c) <= 'z') || \
4228 ((c) >= '0' && (c) <= '9') || \
4229 (c) == '+' || (c) == '/')
4230
4231/* given that c is a base-64 character, what is its base-64 value? */
4232
4233#define FROM_BASE64(c) \
4234 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4235 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4236 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4237 (c) == '+' ? 62 : 63)
4238
4239/* What is the base-64 character of the bottom 6 bits of n? */
4240
4241#define TO_BASE64(n) \
4242 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4243
4244/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4245 * decoded as itself. We are permissive on decoding; the only ASCII
4246 * byte not decoding to itself is the + which begins a base64
4247 * string. */
4248
4249#define DECODE_DIRECT(c) \
4250 ((c) <= 127 && (c) != '+')
4251
4252/* The UTF-7 encoder treats ASCII characters differently according to
4253 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4254 * the above). See RFC2152. This array identifies these different
4255 * sets:
4256 * 0 : "Set D"
4257 * alphanumeric and '(),-./:?
4258 * 1 : "Set O"
4259 * !"#$%&*;<=>@[]^_`{|}
4260 * 2 : "whitespace"
4261 * ht nl cr sp
4262 * 3 : special (must be base64 encoded)
4263 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4264 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004265
Tim Petersced69f82003-09-16 20:30:58 +00004266static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004267char utf7_category[128] = {
4268/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4269 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4270/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4271 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4272/* sp ! " # $ % & ' ( ) * + , - . / */
4273 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4274/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4276/* @ A B C D E F G H I J K L M N O */
4277 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4278/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4279 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4280/* ` a b c d e f g h i j k l m n o */
4281 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4282/* p q r s t u v w x y z { | } ~ del */
4283 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004284};
4285
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286/* ENCODE_DIRECT: this character should be encoded as itself. The
4287 * answer depends on whether we are encoding set O as itself, and also
4288 * on whether we are encoding whitespace as itself. RFC2152 makes it
4289 * clear that the answers to these questions vary between
4290 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004291
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292#define ENCODE_DIRECT(c, directO, directWS) \
4293 ((c) < 128 && (c) > 0 && \
4294 ((utf7_category[(c)] == 0) || \
4295 (directWS && (utf7_category[(c)] == 2)) || \
4296 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004297
Alexander Belopolsky40018472011-02-26 01:02:56 +00004298PyObject *
4299PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004300 Py_ssize_t size,
4301 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004302{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004303 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4304}
4305
Antoine Pitrou244651a2009-05-04 18:56:13 +00004306/* The decoder. The only state we preserve is our read position,
4307 * i.e. how many characters we have consumed. So if we end in the
4308 * middle of a shift sequence we have to back off the read position
4309 * and the output to the beginning of the sequence, otherwise we lose
4310 * all the shift state (seen bits, number of bits seen, high
4311 * surrogate). */
4312
Alexander Belopolsky40018472011-02-26 01:02:56 +00004313PyObject *
4314PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004315 Py_ssize_t size,
4316 const char *errors,
4317 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004318{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004320 Py_ssize_t startinpos;
4321 Py_ssize_t endinpos;
4322 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004323 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004324 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004325 const char *errmsg = "";
4326 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004327 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004328 unsigned int base64bits = 0;
4329 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004330 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004331 PyObject *errorHandler = NULL;
4332 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004333
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004334 /* Start off assuming it's all ASCII. Widen later as necessary. */
4335 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336 if (!unicode)
4337 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004338 if (size == 0) {
4339 if (consumed)
4340 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004341 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004342 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004343
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004344 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345 e = s + size;
4346
4347 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004348 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004349 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004350 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004351
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 if (inShift) { /* in a base-64 section */
4353 if (IS_BASE64(ch)) { /* consume a base-64 character */
4354 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4355 base64bits += 6;
4356 s++;
4357 if (base64bits >= 16) {
4358 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004359 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 base64bits -= 16;
4361 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004362 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 if (surrogate) {
4364 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004365 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4366 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004367 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4368 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004370 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004373 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4374 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 }
4377 }
Victor Stinner551ac952011-11-29 22:58:13 +01004378 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 /* first surrogate */
4380 surrogate = outCh;
4381 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004383 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4384 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 }
4386 }
4387 }
4388 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389 inShift = 0;
4390 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004392 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4393 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004394 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004396 if (base64bits > 0) { /* left-over bits */
4397 if (base64bits >= 6) {
4398 /* We've seen at least one base-64 character */
4399 errmsg = "partial character in shift sequence";
4400 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004402 else {
4403 /* Some bits remain; they should be zero */
4404 if (base64buffer != 0) {
4405 errmsg = "non-zero padding bits in shift sequence";
4406 goto utf7Error;
4407 }
4408 }
4409 }
4410 if (ch != '-') {
4411 /* '-' is absorbed; other terminating
4412 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004413 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4414 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004415 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
4418 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004419 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 s++; /* consume '+' */
4421 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004423 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4424 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 }
4426 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004427 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004428 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004429 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004430 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004431 }
4432 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004434 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4435 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004436 s++;
4437 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 else {
4439 startinpos = s-starts;
4440 s++;
4441 errmsg = "unexpected special character";
4442 goto utf7Error;
4443 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004446 endinpos = s-starts;
4447 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 errors, &errorHandler,
4449 "utf7", errmsg,
4450 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004451 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004452 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004453 }
4454
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 /* end of string */
4456
4457 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4458 /* if we're in an inconsistent state, that's an error */
4459 if (surrogate ||
4460 (base64bits >= 6) ||
4461 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 endinpos = size;
4463 if (unicode_decode_call_errorhandler(
4464 errors, &errorHandler,
4465 "utf7", "unterminated shift sequence",
4466 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004467 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 goto onError;
4469 if (s < e)
4470 goto restart;
4471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473
4474 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004475 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004477 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004478 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 }
4480 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004481 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004482 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004483 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004484
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004485 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486 goto onError;
4487
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004488 Py_XDECREF(errorHandler);
4489 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004490 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004491
Benjamin Peterson29060642009-01-31 22:14:21 +00004492 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004493 Py_XDECREF(errorHandler);
4494 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495 Py_DECREF(unicode);
4496 return NULL;
4497}
4498
4499
Alexander Belopolsky40018472011-02-26 01:02:56 +00004500PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004501_PyUnicode_EncodeUTF7(PyObject *str,
4502 int base64SetO,
4503 int base64WhiteSpace,
4504 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004506 int kind;
4507 void *data;
4508 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004509 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004510 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004511 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 unsigned int base64bits = 0;
4513 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004514 char * out;
4515 char * start;
4516
Benjamin Petersonbac79492012-01-14 13:34:47 -05004517 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004518 return NULL;
4519 kind = PyUnicode_KIND(str);
4520 data = PyUnicode_DATA(str);
4521 len = PyUnicode_GET_LENGTH(str);
4522
4523 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004524 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004526 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004527 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004528 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004529 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 if (v == NULL)
4531 return NULL;
4532
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004533 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004534 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004535 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536
Antoine Pitrou244651a2009-05-04 18:56:13 +00004537 if (inShift) {
4538 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4539 /* shifting out */
4540 if (base64bits) { /* output remaining bits */
4541 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4542 base64buffer = 0;
4543 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 }
4545 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004546 /* Characters not in the BASE64 set implicitly unshift the sequence
4547 so no '-' is required, except if the character is itself a '-' */
4548 if (IS_BASE64(ch) || ch == '-') {
4549 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004551 *out++ = (char) ch;
4552 }
4553 else {
4554 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004555 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004557 else { /* not in a shift sequence */
4558 if (ch == '+') {
4559 *out++ = '+';
4560 *out++ = '-';
4561 }
4562 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4563 *out++ = (char) ch;
4564 }
4565 else {
4566 *out++ = '+';
4567 inShift = 1;
4568 goto encode_char;
4569 }
4570 }
4571 continue;
4572encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004574 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004575
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 /* code first surrogate */
4577 base64bits += 16;
4578 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4579 while (base64bits >= 6) {
4580 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4581 base64bits -= 6;
4582 }
4583 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004584 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 base64bits += 16;
4587 base64buffer = (base64buffer << 16) | ch;
4588 while (base64bits >= 6) {
4589 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4590 base64bits -= 6;
4591 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004592 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 if (base64bits)
4594 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4595 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004596 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004597 if (_PyBytes_Resize(&v, out - start) < 0)
4598 return NULL;
4599 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004600}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601PyObject *
4602PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4603 Py_ssize_t size,
4604 int base64SetO,
4605 int base64WhiteSpace,
4606 const char *errors)
4607{
4608 PyObject *result;
4609 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4610 if (tmp == NULL)
4611 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004612 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004613 base64WhiteSpace, errors);
4614 Py_DECREF(tmp);
4615 return result;
4616}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004617
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618#undef IS_BASE64
4619#undef FROM_BASE64
4620#undef TO_BASE64
4621#undef DECODE_DIRECT
4622#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004623
Guido van Rossumd57fd912000-03-10 22:53:23 +00004624/* --- UTF-8 Codec -------------------------------------------------------- */
4625
Alexander Belopolsky40018472011-02-26 01:02:56 +00004626PyObject *
4627PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004628 Py_ssize_t size,
4629 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004630{
Walter Dörwald69652032004-09-07 20:24:22 +00004631 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4632}
4633
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004634#include "stringlib/asciilib.h"
4635#include "stringlib/codecs.h"
4636#include "stringlib/undef.h"
4637
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004638#include "stringlib/ucs1lib.h"
4639#include "stringlib/codecs.h"
4640#include "stringlib/undef.h"
4641
4642#include "stringlib/ucs2lib.h"
4643#include "stringlib/codecs.h"
4644#include "stringlib/undef.h"
4645
4646#include "stringlib/ucs4lib.h"
4647#include "stringlib/codecs.h"
4648#include "stringlib/undef.h"
4649
Antoine Pitrouab868312009-01-10 15:40:25 +00004650/* Mask to quickly check whether a C 'long' contains a
4651 non-ASCII, UTF8-encoded char. */
4652#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004653# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004654#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004655# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004656#else
4657# error C 'long' size should be either 4 or 8!
4658#endif
4659
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004660static Py_ssize_t
4661ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004662{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004663 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004664 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004665
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004666 /*
4667 * Issue #17237: m68k is a bit different from most architectures in
4668 * that objects do not use "natural alignment" - for example, int and
4669 * long are only aligned at 2-byte boundaries. Therefore the assert()
4670 * won't work; also, tests have shown that skipping the "optimised
4671 * version" will even speed up m68k.
4672 */
4673#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004674#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004675 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4676 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004677 /* Fast path, see in STRINGLIB(utf8_decode) for
4678 an explanation. */
4679 /* Help register allocation */
4680 register const char *_p = p;
4681 register Py_UCS1 * q = dest;
4682 while (_p < aligned_end) {
4683 unsigned long value = *(const unsigned long *) _p;
4684 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004685 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004686 *((unsigned long *)q) = value;
4687 _p += SIZEOF_LONG;
4688 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004689 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690 p = _p;
4691 while (p < end) {
4692 if ((unsigned char)*p & 0x80)
4693 break;
4694 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004695 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004699#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004700 while (p < end) {
4701 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4702 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004703 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704 /* Help register allocation */
4705 register const char *_p = p;
4706 while (_p < aligned_end) {
4707 unsigned long value = *(unsigned long *) _p;
4708 if (value & ASCII_CHAR_MASK)
4709 break;
4710 _p += SIZEOF_LONG;
4711 }
4712 p = _p;
4713 if (_p == end)
4714 break;
4715 }
4716 if ((unsigned char)*p & 0x80)
4717 break;
4718 ++p;
4719 }
4720 memcpy(dest, start, p - start);
4721 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004722}
Antoine Pitrouab868312009-01-10 15:40:25 +00004723
Victor Stinner785938e2011-12-11 20:09:03 +01004724PyObject *
4725PyUnicode_DecodeUTF8Stateful(const char *s,
4726 Py_ssize_t size,
4727 const char *errors,
4728 Py_ssize_t *consumed)
4729{
Victor Stinner785938e2011-12-11 20:09:03 +01004730 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004731 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004732 const char *end = s + size;
4733 Py_ssize_t outpos;
4734
4735 Py_ssize_t startinpos;
4736 Py_ssize_t endinpos;
4737 const char *errmsg = "";
4738 PyObject *errorHandler = NULL;
4739 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004740
4741 if (size == 0) {
4742 if (consumed)
4743 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004744 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004745 }
4746
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004747 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4748 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004749 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 *consumed = 1;
4751 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004752 }
4753
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004754 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004755 if (!unicode)
4756 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004757
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4759 s += outpos;
4760 while (s < end) {
4761 Py_UCS4 ch;
4762 int kind = PyUnicode_KIND(unicode);
4763 if (kind == PyUnicode_1BYTE_KIND) {
4764 if (PyUnicode_IS_ASCII(unicode))
4765 ch = asciilib_utf8_decode(&s, end,
4766 PyUnicode_1BYTE_DATA(unicode), &outpos);
4767 else
4768 ch = ucs1lib_utf8_decode(&s, end,
4769 PyUnicode_1BYTE_DATA(unicode), &outpos);
4770 } else if (kind == PyUnicode_2BYTE_KIND) {
4771 ch = ucs2lib_utf8_decode(&s, end,
4772 PyUnicode_2BYTE_DATA(unicode), &outpos);
4773 } else {
4774 assert(kind == PyUnicode_4BYTE_KIND);
4775 ch = ucs4lib_utf8_decode(&s, end,
4776 PyUnicode_4BYTE_DATA(unicode), &outpos);
4777 }
4778
4779 switch (ch) {
4780 case 0:
4781 if (s == end || consumed)
4782 goto End;
4783 errmsg = "unexpected end of data";
4784 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004785 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004786 break;
4787 case 1:
4788 errmsg = "invalid start byte";
4789 startinpos = s - starts;
4790 endinpos = startinpos + 1;
4791 break;
4792 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004793 case 3:
4794 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795 errmsg = "invalid continuation byte";
4796 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004797 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798 break;
4799 default:
4800 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4801 goto onError;
4802 continue;
4803 }
4804
4805 if (unicode_decode_call_errorhandler(
4806 errors, &errorHandler,
4807 "utf-8", errmsg,
4808 &starts, &end, &startinpos, &endinpos, &exc, &s,
4809 &unicode, &outpos))
4810 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004811 }
4812
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813End:
4814 if (unicode_resize(&unicode, outpos) < 0)
4815 goto onError;
4816
4817 if (consumed)
4818 *consumed = s - starts;
4819
4820 Py_XDECREF(errorHandler);
4821 Py_XDECREF(exc);
4822 assert(_PyUnicode_CheckConsistency(unicode, 1));
4823 return unicode;
4824
4825onError:
4826 Py_XDECREF(errorHandler);
4827 Py_XDECREF(exc);
4828 Py_XDECREF(unicode);
4829 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004830}
4831
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832#ifdef __APPLE__
4833
4834/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner27b1ca22012-12-03 12:47:59 +01004835 used to decode the command line arguments on Mac OS X.
4836
4837 Return a pointer to a newly allocated wide character string (use
4838 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004839
4840wchar_t*
4841_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4842{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004843 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004844 wchar_t *unicode;
4845 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846
4847 /* Note: size will always be longer than the resulting Unicode
4848 character count */
Victor Stinner27b1ca22012-12-03 12:47:59 +01004849 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004851 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4852 if (!unicode)
4853 return NULL;
4854
4855 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004856 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004857 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004858 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004859 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004860#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004861 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004862#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 if (ch > 0xFF) {
4866#if SIZEOF_WCHAR_T == 4
4867 assert(0);
4868#else
4869 assert(Py_UNICODE_IS_SURROGATE(ch));
4870 /* compute and append the two surrogates: */
4871 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4872 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4873#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004874 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004875 else {
4876 if (!ch && s == e)
4877 break;
4878 /* surrogateescape */
4879 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4880 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004881 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004882 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004883 return unicode;
4884}
4885
4886#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004888/* Primary internal function which creates utf8 encoded bytes objects.
4889
4890 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004891 and allocate exactly as much space needed at the end. Else allocate the
4892 maximum possible needed (4 result bytes per Unicode character), and return
4893 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004894*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004895PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004896_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004897{
Victor Stinner6099a032011-12-18 14:22:26 +01004898 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004899 void *data;
4900 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004901
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004902 if (!PyUnicode_Check(unicode)) {
4903 PyErr_BadArgument();
4904 return NULL;
4905 }
4906
4907 if (PyUnicode_READY(unicode) == -1)
4908 return NULL;
4909
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004910 if (PyUnicode_UTF8(unicode))
4911 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4912 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004913
4914 kind = PyUnicode_KIND(unicode);
4915 data = PyUnicode_DATA(unicode);
4916 size = PyUnicode_GET_LENGTH(unicode);
4917
Benjamin Petersonead6b532011-12-20 17:23:42 -06004918 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004919 default:
4920 assert(0);
4921 case PyUnicode_1BYTE_KIND:
4922 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4923 assert(!PyUnicode_IS_ASCII(unicode));
4924 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4925 case PyUnicode_2BYTE_KIND:
4926 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4927 case PyUnicode_4BYTE_KIND:
4928 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004929 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004930}
4931
Alexander Belopolsky40018472011-02-26 01:02:56 +00004932PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004933PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4934 Py_ssize_t size,
4935 const char *errors)
4936{
4937 PyObject *v, *unicode;
4938
4939 unicode = PyUnicode_FromUnicode(s, size);
4940 if (unicode == NULL)
4941 return NULL;
4942 v = _PyUnicode_AsUTF8String(unicode, errors);
4943 Py_DECREF(unicode);
4944 return v;
4945}
4946
4947PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004948PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004949{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004950 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004951}
4952
Walter Dörwald41980ca2007-08-16 21:55:45 +00004953/* --- UTF-32 Codec ------------------------------------------------------- */
4954
4955PyObject *
4956PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004957 Py_ssize_t size,
4958 const char *errors,
4959 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960{
4961 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4962}
4963
4964PyObject *
4965PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004966 Py_ssize_t size,
4967 const char *errors,
4968 int *byteorder,
4969 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004970{
4971 const char *starts = s;
4972 Py_ssize_t startinpos;
4973 Py_ssize_t endinpos;
4974 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004975 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004976 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 int bo = 0; /* assume native ordering by default */
4978 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004979 /* Offsets from q for retrieving bytes in the right order. */
4980#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4981 int iorder[] = {0, 1, 2, 3};
4982#else
4983 int iorder[] = {3, 2, 1, 0};
4984#endif
4985 PyObject *errorHandler = NULL;
4986 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004987
Walter Dörwald41980ca2007-08-16 21:55:45 +00004988 q = (unsigned char *)s;
4989 e = q + size;
4990
4991 if (byteorder)
4992 bo = *byteorder;
4993
4994 /* Check for BOM marks (U+FEFF) in the input and adjust current
4995 byte order setting accordingly. In native mode, the leading BOM
4996 mark is skipped, in all other modes, it is copied to the output
4997 stream as-is (giving a ZWNBSP character). */
4998 if (bo == 0) {
4999 if (size >= 4) {
5000 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005002#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005003 if (bom == 0x0000FEFF) {
5004 q += 4;
5005 bo = -1;
5006 }
5007 else if (bom == 0xFFFE0000) {
5008 q += 4;
5009 bo = 1;
5010 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005011#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005012 if (bom == 0x0000FEFF) {
5013 q += 4;
5014 bo = 1;
5015 }
5016 else if (bom == 0xFFFE0000) {
5017 q += 4;
5018 bo = -1;
5019 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005020#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005022 }
5023
5024 if (bo == -1) {
5025 /* force LE */
5026 iorder[0] = 0;
5027 iorder[1] = 1;
5028 iorder[2] = 2;
5029 iorder[3] = 3;
5030 }
5031 else if (bo == 1) {
5032 /* force BE */
5033 iorder[0] = 3;
5034 iorder[1] = 2;
5035 iorder[2] = 1;
5036 iorder[3] = 0;
5037 }
5038
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005039 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005040 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005041 if (!unicode)
5042 return NULL;
5043 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005044 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005045 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005046
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 Py_UCS4 ch;
5049 /* remaining bytes at the end? (size should be divisible by 4) */
5050 if (e-q<4) {
5051 if (consumed)
5052 break;
5053 errmsg = "truncated data";
5054 startinpos = ((const char *)q)-starts;
5055 endinpos = ((const char *)e)-starts;
5056 goto utf32Error;
5057 /* The remaining input chars are ignored if the callback
5058 chooses to skip the input */
5059 }
5060 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5061 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 if (ch >= 0x110000)
5064 {
5065 errmsg = "codepoint not in range(0x110000)";
5066 startinpos = ((const char *)q)-starts;
5067 endinpos = startinpos+4;
5068 goto utf32Error;
5069 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005070 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5071 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 q += 4;
5073 continue;
5074 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 if (unicode_decode_call_errorhandler(
5076 errors, &errorHandler,
5077 "utf32", errmsg,
5078 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005079 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081 }
5082
5083 if (byteorder)
5084 *byteorder = bo;
5085
5086 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005087 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088
5089 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005090 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 goto onError;
5092
5093 Py_XDECREF(errorHandler);
5094 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005095 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096
Benjamin Peterson29060642009-01-31 22:14:21 +00005097 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 Py_DECREF(unicode);
5099 Py_XDECREF(errorHandler);
5100 Py_XDECREF(exc);
5101 return NULL;
5102}
5103
5104PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005105_PyUnicode_EncodeUTF32(PyObject *str,
5106 const char *errors,
5107 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005108{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005109 int kind;
5110 void *data;
5111 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005112 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005114 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115 /* Offsets from p for storing byte pairs in the right order. */
5116#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5117 int iorder[] = {0, 1, 2, 3};
5118#else
5119 int iorder[] = {3, 2, 1, 0};
5120#endif
5121
Benjamin Peterson29060642009-01-31 22:14:21 +00005122#define STORECHAR(CH) \
5123 do { \
5124 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5125 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5126 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5127 p[iorder[0]] = (CH) & 0xff; \
5128 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129 } while(0)
5130
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005131 if (!PyUnicode_Check(str)) {
5132 PyErr_BadArgument();
5133 return NULL;
5134 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005135 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005136 return NULL;
5137 kind = PyUnicode_KIND(str);
5138 data = PyUnicode_DATA(str);
5139 len = PyUnicode_GET_LENGTH(str);
5140
5141 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005142 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005143 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005144 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145 if (v == NULL)
5146 return NULL;
5147
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005148 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005149 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005150 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005151 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005152 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153
5154 if (byteorder == -1) {
5155 /* force LE */
5156 iorder[0] = 0;
5157 iorder[1] = 1;
5158 iorder[2] = 2;
5159 iorder[3] = 3;
5160 }
5161 else if (byteorder == 1) {
5162 /* force BE */
5163 iorder[0] = 3;
5164 iorder[1] = 2;
5165 iorder[2] = 1;
5166 iorder[3] = 0;
5167 }
5168
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005169 for (i = 0; i < len; i++)
5170 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005171
5172 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005173 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005174#undef STORECHAR
5175}
5176
Alexander Belopolsky40018472011-02-26 01:02:56 +00005177PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005178PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5179 Py_ssize_t size,
5180 const char *errors,
5181 int byteorder)
5182{
5183 PyObject *result;
5184 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5185 if (tmp == NULL)
5186 return NULL;
5187 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5188 Py_DECREF(tmp);
5189 return result;
5190}
5191
5192PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005193PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005194{
Victor Stinnerb960b342011-11-20 19:12:52 +01005195 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005196}
5197
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198/* --- UTF-16 Codec ------------------------------------------------------- */
5199
Tim Peters772747b2001-08-09 22:21:55 +00005200PyObject *
5201PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005202 Py_ssize_t size,
5203 const char *errors,
5204 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005205{
Walter Dörwald69652032004-09-07 20:24:22 +00005206 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5207}
5208
5209PyObject *
5210PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005211 Py_ssize_t size,
5212 const char *errors,
5213 int *byteorder,
5214 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005215{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005216 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005217 Py_ssize_t startinpos;
5218 Py_ssize_t endinpos;
5219 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005220 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005221 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005222 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005223 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005224 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005225 PyObject *errorHandler = NULL;
5226 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005227
Tim Peters772747b2001-08-09 22:21:55 +00005228 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005229 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005230
5231 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005232 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005233
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005234 /* Check for BOM marks (U+FEFF) in the input and adjust current
5235 byte order setting accordingly. In native mode, the leading BOM
5236 mark is skipped, in all other modes, it is copied to the output
5237 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005238 if (bo == 0 && size >= 2) {
5239 const Py_UCS4 bom = (q[1] << 8) | q[0];
5240 if (bom == 0xFEFF) {
5241 q += 2;
5242 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005244 else if (bom == 0xFFFE) {
5245 q += 2;
5246 bo = 1;
5247 }
5248 if (byteorder)
5249 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005250 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005251
Antoine Pitrou63065d72012-05-15 23:48:04 +02005252 if (q == e) {
5253 if (consumed)
5254 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005255 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005256 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005257
Antoine Pitrouab868312009-01-10 15:40:25 +00005258#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005259 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005260#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005261 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005262#endif
Tim Peters772747b2001-08-09 22:21:55 +00005263
Antoine Pitrou63065d72012-05-15 23:48:04 +02005264 /* Note: size will always be longer than the resulting Unicode
5265 character count */
5266 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5267 if (!unicode)
5268 return NULL;
5269
5270 outpos = 0;
5271 while (1) {
5272 Py_UCS4 ch = 0;
5273 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005274 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005275 if (kind == PyUnicode_1BYTE_KIND) {
5276 if (PyUnicode_IS_ASCII(unicode))
5277 ch = asciilib_utf16_decode(&q, e,
5278 PyUnicode_1BYTE_DATA(unicode), &outpos,
5279 native_ordering);
5280 else
5281 ch = ucs1lib_utf16_decode(&q, e,
5282 PyUnicode_1BYTE_DATA(unicode), &outpos,
5283 native_ordering);
5284 } else if (kind == PyUnicode_2BYTE_KIND) {
5285 ch = ucs2lib_utf16_decode(&q, e,
5286 PyUnicode_2BYTE_DATA(unicode), &outpos,
5287 native_ordering);
5288 } else {
5289 assert(kind == PyUnicode_4BYTE_KIND);
5290 ch = ucs4lib_utf16_decode(&q, e,
5291 PyUnicode_4BYTE_DATA(unicode), &outpos,
5292 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005293 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005294 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005295
Antoine Pitrou63065d72012-05-15 23:48:04 +02005296 switch (ch)
5297 {
5298 case 0:
5299 /* remaining byte at the end? (size should be even) */
5300 if (q == e || consumed)
5301 goto End;
5302 errmsg = "truncated data";
5303 startinpos = ((const char *)q) - starts;
5304 endinpos = ((const char *)e) - starts;
5305 break;
5306 /* The remaining input chars are ignored if the callback
5307 chooses to skip the input */
5308 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005309 q -= 2;
5310 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005311 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005312 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005313 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005314 endinpos = ((const char *)e) - starts;
5315 break;
5316 case 2:
5317 errmsg = "illegal encoding";
5318 startinpos = ((const char *)q) - 2 - starts;
5319 endinpos = startinpos + 2;
5320 break;
5321 case 3:
5322 errmsg = "illegal UTF-16 surrogate";
5323 startinpos = ((const char *)q) - 4 - starts;
5324 endinpos = startinpos + 2;
5325 break;
5326 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005327 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5328 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 continue;
5330 }
5331
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 errors,
5334 &errorHandler,
5335 "utf16", errmsg,
5336 &starts,
5337 (const char **)&e,
5338 &startinpos,
5339 &endinpos,
5340 &exc,
5341 (const char **)&q,
5342 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005343 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005345 }
5346
Antoine Pitrou63065d72012-05-15 23:48:04 +02005347End:
Walter Dörwald69652032004-09-07 20:24:22 +00005348 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005350
Guido van Rossumd57fd912000-03-10 22:53:23 +00005351 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005352 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005353 goto onError;
5354
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005355 Py_XDECREF(errorHandler);
5356 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005357 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005358
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005360 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005361 Py_XDECREF(errorHandler);
5362 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005363 return NULL;
5364}
5365
Tim Peters772747b2001-08-09 22:21:55 +00005366PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005367_PyUnicode_EncodeUTF16(PyObject *str,
5368 const char *errors,
5369 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005370{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005371 enum PyUnicode_Kind kind;
5372 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005373 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005374 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005375 unsigned short *out;
5376 Py_ssize_t bytesize;
5377 Py_ssize_t pairs;
5378#ifdef WORDS_BIGENDIAN
5379 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005380#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005381 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005382#endif
5383
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005384 if (!PyUnicode_Check(str)) {
5385 PyErr_BadArgument();
5386 return NULL;
5387 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005388 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005389 return NULL;
5390 kind = PyUnicode_KIND(str);
5391 data = PyUnicode_DATA(str);
5392 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005393
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005394 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005395 if (kind == PyUnicode_4BYTE_KIND) {
5396 const Py_UCS4 *in = (const Py_UCS4 *)data;
5397 const Py_UCS4 *end = in + len;
5398 while (in < end)
5399 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005400 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005401 }
5402 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005403 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005404 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005405 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005406 if (v == NULL)
5407 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005409 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005410 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005411 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005412 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005413 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005414 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005415 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005416
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005417 switch (kind) {
5418 case PyUnicode_1BYTE_KIND: {
5419 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5420 break;
Tim Peters772747b2001-08-09 22:21:55 +00005421 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005422 case PyUnicode_2BYTE_KIND: {
5423 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5424 break;
Tim Peters772747b2001-08-09 22:21:55 +00005425 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005426 case PyUnicode_4BYTE_KIND: {
5427 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5428 break;
5429 }
5430 default:
5431 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005432 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005433
5434 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005435 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436}
5437
Alexander Belopolsky40018472011-02-26 01:02:56 +00005438PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005439PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5440 Py_ssize_t size,
5441 const char *errors,
5442 int byteorder)
5443{
5444 PyObject *result;
5445 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5446 if (tmp == NULL)
5447 return NULL;
5448 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5449 Py_DECREF(tmp);
5450 return result;
5451}
5452
5453PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005454PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005455{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005456 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005457}
5458
5459/* --- Unicode Escape Codec ----------------------------------------------- */
5460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005461/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5462 if all the escapes in the string make it still a valid ASCII string.
5463 Returns -1 if any escapes were found which cause the string to
5464 pop out of ASCII range. Otherwise returns the length of the
5465 required buffer to hold the string.
5466 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005467static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005468length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5469{
5470 const unsigned char *p = (const unsigned char *)s;
5471 const unsigned char *end = p + size;
5472 Py_ssize_t length = 0;
5473
5474 if (size < 0)
5475 return -1;
5476
5477 for (; p < end; ++p) {
5478 if (*p > 127) {
5479 /* Non-ASCII */
5480 return -1;
5481 }
5482 else if (*p != '\\') {
5483 /* Normal character */
5484 ++length;
5485 }
5486 else {
5487 /* Backslash-escape, check next char */
5488 ++p;
5489 /* Escape sequence reaches till end of string or
5490 non-ASCII follow-up. */
5491 if (p >= end || *p > 127)
5492 return -1;
5493 switch (*p) {
5494 case '\n':
5495 /* backslash + \n result in zero characters */
5496 break;
5497 case '\\': case '\'': case '\"':
5498 case 'b': case 'f': case 't':
5499 case 'n': case 'r': case 'v': case 'a':
5500 ++length;
5501 break;
5502 case '0': case '1': case '2': case '3':
5503 case '4': case '5': case '6': case '7':
5504 case 'x': case 'u': case 'U': case 'N':
5505 /* these do not guarantee ASCII characters */
5506 return -1;
5507 default:
5508 /* count the backslash + the other character */
5509 length += 2;
5510 }
5511 }
5512 }
5513 return length;
5514}
5515
Fredrik Lundh06d12682001-01-24 07:59:11 +00005516static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005517
Alexander Belopolsky40018472011-02-26 01:02:56 +00005518PyObject *
5519PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005520 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005521 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005522{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005523 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005524 Py_ssize_t startinpos;
5525 Py_ssize_t endinpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005526 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005527 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005528 char* message;
5529 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005530 PyObject *errorHandler = NULL;
5531 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005532 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005533 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005534
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005535 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005536
5537 /* After length_of_escaped_ascii_string() there are two alternatives,
5538 either the string is pure ASCII with named escapes like \n, etc.
5539 and we determined it's exact size (common case)
5540 or it contains \x, \u, ... escape sequences. then we create a
5541 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005542 if (len >= 0) {
5543 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544 if (!v)
5545 goto onError;
5546 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005547 }
5548 else {
5549 /* Escaped strings will always be longer than the resulting
5550 Unicode string, so we start with size here and then reduce the
5551 length after conversion to the true value.
5552 (but if the error callback returns a long replacement string
5553 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005554 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005555 if (!v)
5556 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005557 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005558 }
5559
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005561 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005562 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005563 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005564
Guido van Rossumd57fd912000-03-10 22:53:23 +00005565 while (s < end) {
5566 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005567 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005568 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005570 /* The only case in which i == ascii_length is a backslash
5571 followed by a newline. */
5572 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005573
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574 /* Non-escape characters are interpreted as Unicode ordinals */
5575 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005576 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5577 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578 continue;
5579 }
5580
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005581 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005582 /* \ - Escapes */
5583 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005584 c = *s++;
5585 if (s > end)
5586 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005587
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588 /* The only case in which i == ascii_length is a backslash
5589 followed by a newline. */
5590 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005591
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005592 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593
Benjamin Peterson29060642009-01-31 22:14:21 +00005594 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005595#define WRITECHAR(ch) \
5596 do { \
5597 if (unicode_putchar(&v, &i, ch) < 0) \
5598 goto onError; \
5599 }while(0)
5600
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005602 case '\\': WRITECHAR('\\'); break;
5603 case '\'': WRITECHAR('\''); break;
5604 case '\"': WRITECHAR('\"'); break;
5605 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005606 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005607 case 'f': WRITECHAR('\014'); break;
5608 case 't': WRITECHAR('\t'); break;
5609 case 'n': WRITECHAR('\n'); break;
5610 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005611 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005612 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005613 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005614 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005617 case '0': case '1': case '2': case '3':
5618 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005619 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005620 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005621 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005622 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005623 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005625 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626 break;
5627
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 /* hex escapes */
5629 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005631 digits = 2;
5632 message = "truncated \\xXX escape";
5633 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634
Benjamin Peterson29060642009-01-31 22:14:21 +00005635 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005637 digits = 4;
5638 message = "truncated \\uXXXX escape";
5639 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005640
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005642 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005643 digits = 8;
5644 message = "truncated \\UXXXXXXXX escape";
5645 hexescape:
5646 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005647 if (end - s < digits) {
5648 /* count only hex digits */
5649 for (; s < end; ++s) {
5650 c = (unsigned char)*s;
5651 if (!Py_ISXDIGIT(c))
5652 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005653 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005654 goto error;
5655 }
5656 for (; digits--; ++s) {
5657 c = (unsigned char)*s;
5658 if (!Py_ISXDIGIT(c))
5659 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005660 chr = (chr<<4) & ~0xF;
5661 if (c >= '0' && c <= '9')
5662 chr += c - '0';
5663 else if (c >= 'a' && c <= 'f')
5664 chr += 10 + c - 'a';
5665 else
5666 chr += 10 + c - 'A';
5667 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005668 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005669 /* _decoding_error will have already written into the
5670 target buffer. */
5671 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005672 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005673 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005674 message = "illegal Unicode character";
5675 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005676 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005677 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005678 break;
5679
Benjamin Peterson29060642009-01-31 22:14:21 +00005680 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005681 case 'N':
5682 message = "malformed \\N character escape";
5683 if (ucnhash_CAPI == NULL) {
5684 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005685 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5686 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005687 if (ucnhash_CAPI == NULL)
5688 goto ucnhashError;
5689 }
5690 if (*s == '{') {
5691 const char *start = s+1;
5692 /* look for the closing brace */
5693 while (*s != '}' && s < end)
5694 s++;
5695 if (s > start && s < end && *s == '}') {
5696 /* found a name. look it up in the unicode database */
5697 message = "unknown Unicode character name";
5698 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005699 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005700 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005701 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005702 goto store;
5703 }
5704 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005705 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005706
5707 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005708 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005709 message = "\\ at end of string";
5710 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005711 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005712 }
5713 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005714 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005715 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005716 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005717 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005719 continue;
5720
5721 error:
5722 endinpos = s-starts;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005723 if (unicode_decode_call_errorhandler(
5724 errors, &errorHandler,
5725 "unicodeescape", message,
5726 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005727 &v, &i))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005728 goto onError;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005729 len = PyUnicode_GET_LENGTH(v);
Serhiy Storchakad6793772013-01-29 10:20:44 +02005730 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005732#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005733
Victor Stinner16e6a802011-12-12 13:24:15 +01005734 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005735 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005736 Py_XDECREF(errorHandler);
5737 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005738 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005739
Benjamin Peterson29060642009-01-31 22:14:21 +00005740 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005741 PyErr_SetString(
5742 PyExc_UnicodeError,
5743 "\\N escapes not supported (can't load unicodedata module)"
5744 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005745 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005746 Py_XDECREF(errorHandler);
5747 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005748 return NULL;
5749
Benjamin Peterson29060642009-01-31 22:14:21 +00005750 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005752 Py_XDECREF(errorHandler);
5753 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005754 return NULL;
5755}
5756
5757/* Return a Unicode-Escape string version of the Unicode object.
5758
5759 If quotes is true, the string is enclosed in u"" or u'' quotes as
5760 appropriate.
5761
5762*/
5763
Alexander Belopolsky40018472011-02-26 01:02:56 +00005764PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005765PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005766{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005767 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005768 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005769 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005770 int kind;
5771 void *data;
5772 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773
Ezio Melottie7f90372012-10-05 03:33:31 +03005774 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005775 escape.
5776
Ezio Melottie7f90372012-10-05 03:33:31 +03005777 For UCS1 strings it's '\xxx', 4 bytes per source character.
5778 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5779 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005780 */
5781
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005782 if (!PyUnicode_Check(unicode)) {
5783 PyErr_BadArgument();
5784 return NULL;
5785 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005786 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005787 return NULL;
5788 len = PyUnicode_GET_LENGTH(unicode);
5789 kind = PyUnicode_KIND(unicode);
5790 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005791 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005792 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5793 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5794 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5795 }
5796
5797 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005798 return PyBytes_FromStringAndSize(NULL, 0);
5799
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005800 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005801 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005802
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005803 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005804 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005805 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005807 if (repr == NULL)
5808 return NULL;
5809
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005810 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005811
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005812 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005813 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005814
Walter Dörwald79e913e2007-05-12 11:08:06 +00005815 /* Escape backslashes */
5816 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817 *p++ = '\\';
5818 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005819 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005820 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005821
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005822 /* Map 21-bit characters to '\U00xxxxxx' */
5823 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005824 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005825 *p++ = '\\';
5826 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005827 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5828 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5829 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5830 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5831 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5832 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5833 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5834 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005835 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005836 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005837
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005839 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005840 *p++ = '\\';
5841 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005842 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5843 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5844 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5845 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005847
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005848 /* Map special whitespace to '\t', \n', '\r' */
5849 else if (ch == '\t') {
5850 *p++ = '\\';
5851 *p++ = 't';
5852 }
5853 else if (ch == '\n') {
5854 *p++ = '\\';
5855 *p++ = 'n';
5856 }
5857 else if (ch == '\r') {
5858 *p++ = '\\';
5859 *p++ = 'r';
5860 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005861
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005862 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005863 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005865 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005866 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5867 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005868 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005869
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 /* Copy everything else as-is */
5871 else
5872 *p++ = (char) ch;
5873 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005875 assert(p - PyBytes_AS_STRING(repr) > 0);
5876 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5877 return NULL;
5878 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879}
5880
Alexander Belopolsky40018472011-02-26 01:02:56 +00005881PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005882PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5883 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005885 PyObject *result;
5886 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5887 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889 result = PyUnicode_AsUnicodeEscapeString(tmp);
5890 Py_DECREF(tmp);
5891 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892}
5893
5894/* --- Raw Unicode Escape Codec ------------------------------------------- */
5895
Alexander Belopolsky40018472011-02-26 01:02:56 +00005896PyObject *
5897PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005898 Py_ssize_t size,
5899 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005901 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005902 Py_ssize_t startinpos;
5903 Py_ssize_t endinpos;
5904 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005905 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 const char *end;
5907 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 PyObject *errorHandler = NULL;
5909 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005910
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911 /* Escaped strings will always be longer than the resulting
5912 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005913 length after conversion to the true value. (But decoding error
5914 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005915 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005917 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005919 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005920 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921 end = s + size;
5922 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 unsigned char c;
5924 Py_UCS4 x;
5925 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005926 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 /* Non-escape characters are interpreted as Unicode ordinals */
5929 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005930 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5931 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005933 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 startinpos = s-starts;
5935
5936 /* \u-escapes are only interpreted iff the number of leading
5937 backslashes if odd */
5938 bs = s;
5939 for (;s < end;) {
5940 if (*s != '\\')
5941 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005942 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5943 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005944 }
5945 if (((s - bs) & 1) == 0 ||
5946 s >= end ||
5947 (*s != 'u' && *s != 'U')) {
5948 continue;
5949 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005950 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 count = *s=='u' ? 4 : 8;
5952 s++;
5953
5954 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 for (x = 0, i = 0; i < count; ++i, ++s) {
5956 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005957 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 endinpos = s-starts;
5959 if (unicode_decode_call_errorhandler(
5960 errors, &errorHandler,
5961 "rawunicodeescape", "truncated \\uXXXX",
5962 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005963 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 goto onError;
5965 goto nextByte;
5966 }
5967 x = (x<<4) & ~0xF;
5968 if (c >= '0' && c <= '9')
5969 x += c - '0';
5970 else if (c >= 'a' && c <= 'f')
5971 x += 10 + c - 'a';
5972 else
5973 x += 10 + c - 'A';
5974 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005975 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005976 if (unicode_putchar(&v, &outpos, x) < 0)
5977 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005978 } else {
5979 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005980 if (unicode_decode_call_errorhandler(
5981 errors, &errorHandler,
5982 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005983 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005984 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005986 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 nextByte:
5988 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005990 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005992 Py_XDECREF(errorHandler);
5993 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005994 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00005995
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005998 Py_XDECREF(errorHandler);
5999 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 return NULL;
6001}
6002
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006003
Alexander Belopolsky40018472011-02-26 01:02:56 +00006004PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006005PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006007 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 char *p;
6009 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006010 Py_ssize_t expandsize, pos;
6011 int kind;
6012 void *data;
6013 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006015 if (!PyUnicode_Check(unicode)) {
6016 PyErr_BadArgument();
6017 return NULL;
6018 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006019 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006020 return NULL;
6021 kind = PyUnicode_KIND(unicode);
6022 data = PyUnicode_DATA(unicode);
6023 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006024 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6025 bytes, and 1 byte characters 4. */
6026 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006027
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006028 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006029 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006030
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006031 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032 if (repr == NULL)
6033 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006034 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006035 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006037 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038 for (pos = 0; pos < len; pos++) {
6039 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 /* Map 32-bit characters to '\Uxxxxxxxx' */
6041 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006042 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006043 *p++ = '\\';
6044 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006045 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6046 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6047 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6048 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6049 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6050 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6051 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6052 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006053 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006055 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056 *p++ = '\\';
6057 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006058 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6059 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6060 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6061 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006063 /* Copy everything else as-is */
6064 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065 *p++ = (char) ch;
6066 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006067
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006068 assert(p > q);
6069 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006070 return NULL;
6071 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072}
6073
Alexander Belopolsky40018472011-02-26 01:02:56 +00006074PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006075PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6076 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 PyObject *result;
6079 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6080 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006081 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006082 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6083 Py_DECREF(tmp);
6084 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085}
6086
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006087/* --- Unicode Internal Codec ------------------------------------------- */
6088
Alexander Belopolsky40018472011-02-26 01:02:56 +00006089PyObject *
6090_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006091 Py_ssize_t size,
6092 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006093{
6094 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006095 Py_ssize_t startinpos;
6096 Py_ssize_t endinpos;
6097 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006098 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006099 const char *end;
6100 const char *reason;
6101 PyObject *errorHandler = NULL;
6102 PyObject *exc = NULL;
6103
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006104 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006105 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006106 1))
6107 return NULL;
6108
Thomas Wouters89f507f2006-12-13 04:49:30 +00006109 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006110 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006111 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006113 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006114 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006115 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006116 end = s + size;
6117
6118 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006119 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006120 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006121 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006122 endinpos = end-starts;
6123 reason = "truncated input";
6124 goto error;
6125 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006126 /* We copy the raw representation one byte at a time because the
6127 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006128 ((char *) &uch)[0] = s[0];
6129 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006130#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006131 ((char *) &uch)[2] = s[2];
6132 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006133#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006134 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006135#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006136 /* We have to sanity check the raw data, otherwise doom looms for
6137 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006138 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006139 endinpos = s - starts + Py_UNICODE_SIZE;
6140 reason = "illegal code point (> 0x10FFFF)";
6141 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006142 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006143#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006144 s += Py_UNICODE_SIZE;
6145#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006146 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006147 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006148 Py_UNICODE uch2;
6149 ((char *) &uch2)[0] = s[0];
6150 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006151 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006152 {
Victor Stinner551ac952011-11-29 22:58:13 +01006153 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006154 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006155 }
6156 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006157#endif
6158
6159 if (unicode_putchar(&v, &outpos, ch) < 0)
6160 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006161 continue;
6162
6163 error:
6164 startinpos = s - starts;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006165 if (unicode_decode_call_errorhandler(
6166 errors, &errorHandler,
6167 "unicode_internal", reason,
6168 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006169 &v, &outpos))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006170 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006171 }
6172
Victor Stinner16e6a802011-12-12 13:24:15 +01006173 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006174 goto onError;
6175 Py_XDECREF(errorHandler);
6176 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006177 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006178
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006180 Py_XDECREF(v);
6181 Py_XDECREF(errorHandler);
6182 Py_XDECREF(exc);
6183 return NULL;
6184}
6185
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186/* --- Latin-1 Codec ------------------------------------------------------ */
6187
Alexander Belopolsky40018472011-02-26 01:02:56 +00006188PyObject *
6189PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006190 Py_ssize_t size,
6191 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006194 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195}
6196
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006197/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006198static void
6199make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006200 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006201 PyObject *unicode,
6202 Py_ssize_t startpos, Py_ssize_t endpos,
6203 const char *reason)
6204{
6205 if (*exceptionObject == NULL) {
6206 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006207 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006208 encoding, unicode, startpos, endpos, reason);
6209 }
6210 else {
6211 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6212 goto onError;
6213 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6214 goto onError;
6215 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6216 goto onError;
6217 return;
6218 onError:
6219 Py_DECREF(*exceptionObject);
6220 *exceptionObject = NULL;
6221 }
6222}
6223
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006224/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006225static void
6226raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006227 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006228 PyObject *unicode,
6229 Py_ssize_t startpos, Py_ssize_t endpos,
6230 const char *reason)
6231{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006232 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006233 encoding, unicode, startpos, endpos, reason);
6234 if (*exceptionObject != NULL)
6235 PyCodec_StrictErrors(*exceptionObject);
6236}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006237
6238/* error handling callback helper:
6239 build arguments, call the callback and check the arguments,
6240 put the result into newpos and return the replacement string, which
6241 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006242static PyObject *
6243unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006244 PyObject **errorHandler,
6245 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006246 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006247 Py_ssize_t startpos, Py_ssize_t endpos,
6248 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006249{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006250 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006251 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006252 PyObject *restuple;
6253 PyObject *resunicode;
6254
6255 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006257 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006259 }
6260
Benjamin Petersonbac79492012-01-14 13:34:47 -05006261 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006262 return NULL;
6263 len = PyUnicode_GET_LENGTH(unicode);
6264
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006265 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006266 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006268 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006269
6270 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006271 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006272 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006274 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006275 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 Py_DECREF(restuple);
6277 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006278 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006279 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 &resunicode, newpos)) {
6281 Py_DECREF(restuple);
6282 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006283 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006284 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6285 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6286 Py_DECREF(restuple);
6287 return NULL;
6288 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006289 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006290 *newpos = len + *newpos;
6291 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6293 Py_DECREF(restuple);
6294 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006295 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006296 Py_INCREF(resunicode);
6297 Py_DECREF(restuple);
6298 return resunicode;
6299}
6300
Alexander Belopolsky40018472011-02-26 01:02:56 +00006301static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006302unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006303 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006304 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006305{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006306 /* input state */
6307 Py_ssize_t pos=0, size;
6308 int kind;
6309 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006310 /* output object */
6311 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312 /* pointer into the output */
6313 char *str;
6314 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006315 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006316 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6317 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006318 PyObject *errorHandler = NULL;
6319 PyObject *exc = NULL;
6320 /* the following variable is used for caching string comparisons
6321 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6322 int known_errorHandler = -1;
6323
Benjamin Petersonbac79492012-01-14 13:34:47 -05006324 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006325 return NULL;
6326 size = PyUnicode_GET_LENGTH(unicode);
6327 kind = PyUnicode_KIND(unicode);
6328 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006329 /* allocate enough for a simple encoding without
6330 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006331 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006332 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006333 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006334 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006335 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006336 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337 ressize = size;
6338
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006339 while (pos < size) {
6340 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006341
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 /* can we encode this? */
6343 if (c<limit) {
6344 /* no overflow check, because we know that the space is enough */
6345 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006346 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006347 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006348 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006349 Py_ssize_t requiredsize;
6350 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006351 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006352 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006353 Py_ssize_t collstart = pos;
6354 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006356 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 ++collend;
6358 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6359 if (known_errorHandler==-1) {
6360 if ((errors==NULL) || (!strcmp(errors, "strict")))
6361 known_errorHandler = 1;
6362 else if (!strcmp(errors, "replace"))
6363 known_errorHandler = 2;
6364 else if (!strcmp(errors, "ignore"))
6365 known_errorHandler = 3;
6366 else if (!strcmp(errors, "xmlcharrefreplace"))
6367 known_errorHandler = 4;
6368 else
6369 known_errorHandler = 0;
6370 }
6371 switch (known_errorHandler) {
6372 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006373 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 goto onError;
6375 case 2: /* replace */
6376 while (collstart++<collend)
6377 *str++ = '?'; /* fall through */
6378 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006379 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 break;
6381 case 4: /* xmlcharrefreplace */
6382 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006383 /* determine replacement size */
6384 for (i = collstart, repsize = 0; i < collend; ++i) {
6385 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6386 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006388 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006389 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006390 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006392 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006394 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006397 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006398 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006399 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006401 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006404 if (requiredsize > ressize) {
6405 if (requiredsize<2*ressize)
6406 requiredsize = 2*ressize;
6407 if (_PyBytes_Resize(&res, requiredsize))
6408 goto onError;
6409 str = PyBytes_AS_STRING(res) + respos;
6410 ressize = requiredsize;
6411 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006412 /* generate replacement */
6413 for (i = collstart; i < collend; ++i) {
6414 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006416 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 break;
6418 default:
6419 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 encoding, reason, unicode, &exc,
6421 collstart, collend, &newpos);
6422 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006423 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006425 if (PyBytes_Check(repunicode)) {
6426 /* Directly copy bytes result to output. */
6427 repsize = PyBytes_Size(repunicode);
6428 if (repsize > 1) {
6429 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006430 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006431 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6432 Py_DECREF(repunicode);
6433 goto onError;
6434 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006435 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006436 ressize += repsize-1;
6437 }
6438 memcpy(str, PyBytes_AsString(repunicode), repsize);
6439 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006440 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006441 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006442 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006443 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006444 /* need more space? (at least enough for what we
6445 have+the replacement+the rest of the string, so
6446 we won't have to check space for encodable characters) */
6447 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 repsize = PyUnicode_GET_LENGTH(repunicode);
6449 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 if (requiredsize > ressize) {
6451 if (requiredsize<2*ressize)
6452 requiredsize = 2*ressize;
6453 if (_PyBytes_Resize(&res, requiredsize)) {
6454 Py_DECREF(repunicode);
6455 goto onError;
6456 }
6457 str = PyBytes_AS_STRING(res) + respos;
6458 ressize = requiredsize;
6459 }
6460 /* check if there is anything unencodable in the replacement
6461 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006462 for (i = 0; repsize-->0; ++i, ++str) {
6463 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006465 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006466 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 Py_DECREF(repunicode);
6468 goto onError;
6469 }
6470 *str = (char)c;
6471 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006473 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006474 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006475 }
6476 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006477 /* Resize if we allocated to much */
6478 size = str - PyBytes_AS_STRING(res);
6479 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006480 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006481 if (_PyBytes_Resize(&res, size) < 0)
6482 goto onError;
6483 }
6484
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006485 Py_XDECREF(errorHandler);
6486 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006487 return res;
6488
6489 onError:
6490 Py_XDECREF(res);
6491 Py_XDECREF(errorHandler);
6492 Py_XDECREF(exc);
6493 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494}
6495
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006497PyObject *
6498PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006499 Py_ssize_t size,
6500 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006501{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 PyObject *result;
6503 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6504 if (unicode == NULL)
6505 return NULL;
6506 result = unicode_encode_ucs1(unicode, errors, 256);
6507 Py_DECREF(unicode);
6508 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509}
6510
Alexander Belopolsky40018472011-02-26 01:02:56 +00006511PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006512_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006513{
6514 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 PyErr_BadArgument();
6516 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006517 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006518 if (PyUnicode_READY(unicode) == -1)
6519 return NULL;
6520 /* Fast path: if it is a one-byte string, construct
6521 bytes object directly. */
6522 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6523 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6524 PyUnicode_GET_LENGTH(unicode));
6525 /* Non-Latin-1 characters present. Defer to above function to
6526 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006528}
6529
6530PyObject*
6531PyUnicode_AsLatin1String(PyObject *unicode)
6532{
6533 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006534}
6535
6536/* --- 7-bit ASCII Codec -------------------------------------------------- */
6537
Alexander Belopolsky40018472011-02-26 01:02:56 +00006538PyObject *
6539PyUnicode_DecodeASCII(const char *s,
6540 Py_ssize_t size,
6541 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006543 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006544 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006545 int kind;
6546 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006547 Py_ssize_t startinpos;
6548 Py_ssize_t endinpos;
6549 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006550 const char *e;
6551 PyObject *errorHandler = NULL;
6552 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006553
Guido van Rossumd57fd912000-03-10 22:53:23 +00006554 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006555 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006556
Guido van Rossumd57fd912000-03-10 22:53:23 +00006557 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006558 if (size == 1 && (unsigned char)s[0] < 128)
6559 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006560
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006561 unicode = PyUnicode_New(size, 127);
6562 if (unicode == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006563 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006564
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006565 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006566 data = PyUnicode_1BYTE_DATA(unicode);
6567 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6568 if (outpos == size)
6569 return unicode;
6570
6571 s += outpos;
6572 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006573 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 register unsigned char c = (unsigned char)*s;
6575 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006576 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006577 ++s;
6578 }
6579 else {
6580 startinpos = s-starts;
6581 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 if (unicode_decode_call_errorhandler(
6583 errors, &errorHandler,
6584 "ascii", "ordinal not in range(128)",
6585 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006586 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006587 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006588 kind = PyUnicode_KIND(unicode);
6589 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006591 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006592 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006593 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006594 Py_XDECREF(errorHandler);
6595 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006596 assert(_PyUnicode_CheckConsistency(unicode, 1));
6597 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006598
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006600 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 Py_XDECREF(errorHandler);
6602 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006603 return NULL;
6604}
6605
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006606/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006607PyObject *
6608PyUnicode_EncodeASCII(const Py_UNICODE *p,
6609 Py_ssize_t size,
6610 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006611{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006612 PyObject *result;
6613 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6614 if (unicode == NULL)
6615 return NULL;
6616 result = unicode_encode_ucs1(unicode, errors, 128);
6617 Py_DECREF(unicode);
6618 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619}
6620
Alexander Belopolsky40018472011-02-26 01:02:56 +00006621PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006622_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006623{
6624 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006625 PyErr_BadArgument();
6626 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006628 if (PyUnicode_READY(unicode) == -1)
6629 return NULL;
6630 /* Fast path: if it is an ASCII-only string, construct bytes object
6631 directly. Else defer to above function to raise the exception. */
6632 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6633 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6634 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006636}
6637
6638PyObject *
6639PyUnicode_AsASCIIString(PyObject *unicode)
6640{
6641 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642}
6643
Victor Stinner99b95382011-07-04 14:23:54 +02006644#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006645
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006646/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006647
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006648#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006649#define NEED_RETRY
6650#endif
6651
Victor Stinner3a50e702011-10-18 21:21:00 +02006652#ifndef WC_ERR_INVALID_CHARS
6653# define WC_ERR_INVALID_CHARS 0x0080
6654#endif
6655
6656static char*
6657code_page_name(UINT code_page, PyObject **obj)
6658{
6659 *obj = NULL;
6660 if (code_page == CP_ACP)
6661 return "mbcs";
6662 if (code_page == CP_UTF7)
6663 return "CP_UTF7";
6664 if (code_page == CP_UTF8)
6665 return "CP_UTF8";
6666
6667 *obj = PyBytes_FromFormat("cp%u", code_page);
6668 if (*obj == NULL)
6669 return NULL;
6670 return PyBytes_AS_STRING(*obj);
6671}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006672
Alexander Belopolsky40018472011-02-26 01:02:56 +00006673static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006674is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006675{
6676 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006677 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006678
Victor Stinner3a50e702011-10-18 21:21:00 +02006679 if (!IsDBCSLeadByteEx(code_page, *curr))
6680 return 0;
6681
6682 prev = CharPrevExA(code_page, s, curr, 0);
6683 if (prev == curr)
6684 return 1;
6685 /* FIXME: This code is limited to "true" double-byte encodings,
6686 as it assumes an incomplete character consists of a single
6687 byte. */
6688 if (curr - prev == 2)
6689 return 1;
6690 if (!IsDBCSLeadByteEx(code_page, *prev))
6691 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006692 return 0;
6693}
6694
Victor Stinner3a50e702011-10-18 21:21:00 +02006695static DWORD
6696decode_code_page_flags(UINT code_page)
6697{
6698 if (code_page == CP_UTF7) {
6699 /* The CP_UTF7 decoder only supports flags=0 */
6700 return 0;
6701 }
6702 else
6703 return MB_ERR_INVALID_CHARS;
6704}
6705
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006706/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006707 * Decode a byte string from a Windows code page into unicode object in strict
6708 * mode.
6709 *
6710 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6711 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006712 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006713static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006714decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006715 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006716 const char *in,
6717 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006718{
Victor Stinner3a50e702011-10-18 21:21:00 +02006719 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006720 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006721 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006722
6723 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006724 assert(insize > 0);
6725 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6726 if (outsize <= 0)
6727 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006728
6729 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006731 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006732 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 if (*v == NULL)
6734 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006735 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006736 }
6737 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006739 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006740 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006742 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006743 }
6744
6745 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006746 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6747 if (outsize <= 0)
6748 goto error;
6749 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006750
Victor Stinner3a50e702011-10-18 21:21:00 +02006751error:
6752 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6753 return -2;
6754 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006755 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006756}
6757
Victor Stinner3a50e702011-10-18 21:21:00 +02006758/*
6759 * Decode a byte string from a code page into unicode object with an error
6760 * handler.
6761 *
6762 * Returns consumed size if succeed, or raise a WindowsError or
6763 * UnicodeDecodeError exception and returns -1 on error.
6764 */
6765static int
6766decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006767 PyObject **v,
6768 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006769 const char *errors)
6770{
6771 const char *startin = in;
6772 const char *endin = in + size;
6773 const DWORD flags = decode_code_page_flags(code_page);
6774 /* Ideally, we should get reason from FormatMessage. This is the Windows
6775 2000 English version of the message. */
6776 const char *reason = "No mapping for the Unicode character exists "
6777 "in the target code page.";
6778 /* each step cannot decode more than 1 character, but a character can be
6779 represented as a surrogate pair */
6780 wchar_t buffer[2], *startout, *out;
6781 int insize, outsize;
6782 PyObject *errorHandler = NULL;
6783 PyObject *exc = NULL;
6784 PyObject *encoding_obj = NULL;
6785 char *encoding;
6786 DWORD err;
6787 int ret = -1;
6788
6789 assert(size > 0);
6790
6791 encoding = code_page_name(code_page, &encoding_obj);
6792 if (encoding == NULL)
6793 return -1;
6794
6795 if (errors == NULL || strcmp(errors, "strict") == 0) {
6796 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6797 UnicodeDecodeError. */
6798 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6799 if (exc != NULL) {
6800 PyCodec_StrictErrors(exc);
6801 Py_CLEAR(exc);
6802 }
6803 goto error;
6804 }
6805
6806 if (*v == NULL) {
6807 /* Create unicode object */
6808 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6809 PyErr_NoMemory();
6810 goto error;
6811 }
Victor Stinnerab595942011-12-17 04:59:06 +01006812 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006813 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006814 if (*v == NULL)
6815 goto error;
6816 startout = PyUnicode_AS_UNICODE(*v);
6817 }
6818 else {
6819 /* Extend unicode object */
6820 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6821 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6822 PyErr_NoMemory();
6823 goto error;
6824 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006825 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006826 goto error;
6827 startout = PyUnicode_AS_UNICODE(*v) + n;
6828 }
6829
6830 /* Decode the byte string character per character */
6831 out = startout;
6832 while (in < endin)
6833 {
6834 /* Decode a character */
6835 insize = 1;
6836 do
6837 {
6838 outsize = MultiByteToWideChar(code_page, flags,
6839 in, insize,
6840 buffer, Py_ARRAY_LENGTH(buffer));
6841 if (outsize > 0)
6842 break;
6843 err = GetLastError();
6844 if (err != ERROR_NO_UNICODE_TRANSLATION
6845 && err != ERROR_INSUFFICIENT_BUFFER)
6846 {
6847 PyErr_SetFromWindowsErr(0);
6848 goto error;
6849 }
6850 insize++;
6851 }
6852 /* 4=maximum length of a UTF-8 sequence */
6853 while (insize <= 4 && (in + insize) <= endin);
6854
6855 if (outsize <= 0) {
6856 Py_ssize_t startinpos, endinpos, outpos;
6857
6858 startinpos = in - startin;
6859 endinpos = startinpos + 1;
6860 outpos = out - PyUnicode_AS_UNICODE(*v);
6861 if (unicode_decode_call_errorhandler(
6862 errors, &errorHandler,
6863 encoding, reason,
6864 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006865 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006866 {
6867 goto error;
6868 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006869 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006870 }
6871 else {
6872 in += insize;
6873 memcpy(out, buffer, outsize * sizeof(wchar_t));
6874 out += outsize;
6875 }
6876 }
6877
6878 /* write a NUL character at the end */
6879 *out = 0;
6880
6881 /* Extend unicode object */
6882 outsize = out - startout;
6883 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006884 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006886 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006887
6888error:
6889 Py_XDECREF(encoding_obj);
6890 Py_XDECREF(errorHandler);
6891 Py_XDECREF(exc);
6892 return ret;
6893}
6894
Victor Stinner3a50e702011-10-18 21:21:00 +02006895static PyObject *
6896decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006897 const char *s, Py_ssize_t size,
6898 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899{
Victor Stinner76a31a62011-11-04 00:05:13 +01006900 PyObject *v = NULL;
6901 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006902
Victor Stinner3a50e702011-10-18 21:21:00 +02006903 if (code_page < 0) {
6904 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6905 return NULL;
6906 }
6907
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006908 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006909 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910
Victor Stinner76a31a62011-11-04 00:05:13 +01006911 do
6912 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006913#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006914 if (size > INT_MAX) {
6915 chunk_size = INT_MAX;
6916 final = 0;
6917 done = 0;
6918 }
6919 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006920#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006921 {
6922 chunk_size = (int)size;
6923 final = (consumed == NULL);
6924 done = 1;
6925 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006926
Victor Stinner76a31a62011-11-04 00:05:13 +01006927 /* Skip trailing lead-byte unless 'final' is set */
6928 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6929 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006930
Victor Stinner76a31a62011-11-04 00:05:13 +01006931 if (chunk_size == 0 && done) {
6932 if (v != NULL)
6933 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006934 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006935 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006936
Victor Stinner76a31a62011-11-04 00:05:13 +01006937
6938 converted = decode_code_page_strict(code_page, &v,
6939 s, chunk_size);
6940 if (converted == -2)
6941 converted = decode_code_page_errors(code_page, &v,
6942 s, chunk_size,
6943 errors);
6944 assert(converted != 0);
6945
6946 if (converted < 0) {
6947 Py_XDECREF(v);
6948 return NULL;
6949 }
6950
6951 if (consumed)
6952 *consumed += converted;
6953
6954 s += converted;
6955 size -= converted;
6956 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006957
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006958 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006959}
6960
Alexander Belopolsky40018472011-02-26 01:02:56 +00006961PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006962PyUnicode_DecodeCodePageStateful(int code_page,
6963 const char *s,
6964 Py_ssize_t size,
6965 const char *errors,
6966 Py_ssize_t *consumed)
6967{
6968 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6969}
6970
6971PyObject *
6972PyUnicode_DecodeMBCSStateful(const char *s,
6973 Py_ssize_t size,
6974 const char *errors,
6975 Py_ssize_t *consumed)
6976{
6977 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6978}
6979
6980PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006981PyUnicode_DecodeMBCS(const char *s,
6982 Py_ssize_t size,
6983 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006984{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006985 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6986}
6987
Victor Stinner3a50e702011-10-18 21:21:00 +02006988static DWORD
6989encode_code_page_flags(UINT code_page, const char *errors)
6990{
6991 if (code_page == CP_UTF8) {
6992 if (winver.dwMajorVersion >= 6)
6993 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6994 and later */
6995 return WC_ERR_INVALID_CHARS;
6996 else
6997 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
6998 return 0;
6999 }
7000 else if (code_page == CP_UTF7) {
7001 /* CP_UTF7 only supports flags=0 */
7002 return 0;
7003 }
7004 else {
7005 if (errors != NULL && strcmp(errors, "replace") == 0)
7006 return 0;
7007 else
7008 return WC_NO_BEST_FIT_CHARS;
7009 }
7010}
7011
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007012/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 * Encode a Unicode string to a Windows code page into a byte string in strict
7014 * mode.
7015 *
7016 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7017 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007018 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007019static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007020encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007021 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007022 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007023{
Victor Stinner554f3f02010-06-16 23:33:54 +00007024 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007025 BOOL *pusedDefaultChar = &usedDefaultChar;
7026 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007027 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007028 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007029 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const DWORD flags = encode_code_page_flags(code_page, NULL);
7031 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007032 /* Create a substring so that we can get the UTF-16 representation
7033 of just the slice under consideration. */
7034 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035
Martin v. Löwis3d325192011-11-04 18:23:06 +01007036 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007037
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007039 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007040 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007041 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007042
Victor Stinner2fc507f2011-11-04 20:06:39 +01007043 substring = PyUnicode_Substring(unicode, offset, offset+len);
7044 if (substring == NULL)
7045 return -1;
7046 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7047 if (p == NULL) {
7048 Py_DECREF(substring);
7049 return -1;
7050 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007051
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007052 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007053 outsize = WideCharToMultiByte(code_page, flags,
7054 p, size,
7055 NULL, 0,
7056 NULL, pusedDefaultChar);
7057 if (outsize <= 0)
7058 goto error;
7059 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007060 if (pusedDefaultChar && *pusedDefaultChar) {
7061 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007062 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007063 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007064
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007066 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007067 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007068 if (*outbytes == NULL) {
7069 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007070 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007071 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007072 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073 }
7074 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007075 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 const Py_ssize_t n = PyBytes_Size(*outbytes);
7077 if (outsize > PY_SSIZE_T_MAX - n) {
7078 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007079 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007080 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007082 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7083 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007085 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087 }
7088
7089 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 outsize = WideCharToMultiByte(code_page, flags,
7091 p, size,
7092 out, outsize,
7093 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007094 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 if (outsize <= 0)
7096 goto error;
7097 if (pusedDefaultChar && *pusedDefaultChar)
7098 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007099 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007100
Victor Stinner3a50e702011-10-18 21:21:00 +02007101error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007102 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7104 return -2;
7105 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007106 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007107}
7108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109/*
7110 * Encode a Unicode string to a Windows code page into a byte string using a
7111 * error handler.
7112 *
7113 * Returns consumed characters if succeed, or raise a WindowsError and returns
7114 * -1 on other error.
7115 */
7116static int
7117encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007118 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007119 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007120{
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007122 Py_ssize_t pos = unicode_offset;
7123 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007124 /* Ideally, we should get reason from FormatMessage. This is the Windows
7125 2000 English version of the message. */
7126 const char *reason = "invalid character";
7127 /* 4=maximum length of a UTF-8 sequence */
7128 char buffer[4];
7129 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7130 Py_ssize_t outsize;
7131 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 PyObject *errorHandler = NULL;
7133 PyObject *exc = NULL;
7134 PyObject *encoding_obj = NULL;
7135 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007136 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007137 PyObject *rep;
7138 int ret = -1;
7139
7140 assert(insize > 0);
7141
7142 encoding = code_page_name(code_page, &encoding_obj);
7143 if (encoding == NULL)
7144 return -1;
7145
7146 if (errors == NULL || strcmp(errors, "strict") == 0) {
7147 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7148 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007149 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 if (exc != NULL) {
7151 PyCodec_StrictErrors(exc);
7152 Py_DECREF(exc);
7153 }
7154 Py_XDECREF(encoding_obj);
7155 return -1;
7156 }
7157
7158 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7159 pusedDefaultChar = &usedDefaultChar;
7160 else
7161 pusedDefaultChar = NULL;
7162
7163 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7164 PyErr_NoMemory();
7165 goto error;
7166 }
7167 outsize = insize * Py_ARRAY_LENGTH(buffer);
7168
7169 if (*outbytes == NULL) {
7170 /* Create string object */
7171 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7172 if (*outbytes == NULL)
7173 goto error;
7174 out = PyBytes_AS_STRING(*outbytes);
7175 }
7176 else {
7177 /* Extend string object */
7178 Py_ssize_t n = PyBytes_Size(*outbytes);
7179 if (n > PY_SSIZE_T_MAX - outsize) {
7180 PyErr_NoMemory();
7181 goto error;
7182 }
7183 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7184 goto error;
7185 out = PyBytes_AS_STRING(*outbytes) + n;
7186 }
7187
7188 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007189 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007191 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7192 wchar_t chars[2];
7193 int charsize;
7194 if (ch < 0x10000) {
7195 chars[0] = (wchar_t)ch;
7196 charsize = 1;
7197 }
7198 else {
7199 ch -= 0x10000;
7200 chars[0] = 0xd800 + (ch >> 10);
7201 chars[1] = 0xdc00 + (ch & 0x3ff);
7202 charsize = 2;
7203 }
7204
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007206 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 buffer, Py_ARRAY_LENGTH(buffer),
7208 NULL, pusedDefaultChar);
7209 if (outsize > 0) {
7210 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7211 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007212 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 memcpy(out, buffer, outsize);
7214 out += outsize;
7215 continue;
7216 }
7217 }
7218 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7219 PyErr_SetFromWindowsErr(0);
7220 goto error;
7221 }
7222
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 rep = unicode_encode_call_errorhandler(
7224 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007225 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007226 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 if (rep == NULL)
7228 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007229 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007230
7231 if (PyBytes_Check(rep)) {
7232 outsize = PyBytes_GET_SIZE(rep);
7233 if (outsize != 1) {
7234 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7235 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7236 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7237 Py_DECREF(rep);
7238 goto error;
7239 }
7240 out = PyBytes_AS_STRING(*outbytes) + offset;
7241 }
7242 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7243 out += outsize;
7244 }
7245 else {
7246 Py_ssize_t i;
7247 enum PyUnicode_Kind kind;
7248 void *data;
7249
Benjamin Petersonbac79492012-01-14 13:34:47 -05007250 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007251 Py_DECREF(rep);
7252 goto error;
7253 }
7254
7255 outsize = PyUnicode_GET_LENGTH(rep);
7256 if (outsize != 1) {
7257 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7258 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7259 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7260 Py_DECREF(rep);
7261 goto error;
7262 }
7263 out = PyBytes_AS_STRING(*outbytes) + offset;
7264 }
7265 kind = PyUnicode_KIND(rep);
7266 data = PyUnicode_DATA(rep);
7267 for (i=0; i < outsize; i++) {
7268 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7269 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007270 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007271 encoding, unicode,
7272 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 "unable to encode error handler result to ASCII");
7274 Py_DECREF(rep);
7275 goto error;
7276 }
7277 *out = (unsigned char)ch;
7278 out++;
7279 }
7280 }
7281 Py_DECREF(rep);
7282 }
7283 /* write a NUL byte */
7284 *out = 0;
7285 outsize = out - PyBytes_AS_STRING(*outbytes);
7286 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7287 if (_PyBytes_Resize(outbytes, outsize) < 0)
7288 goto error;
7289 ret = 0;
7290
7291error:
7292 Py_XDECREF(encoding_obj);
7293 Py_XDECREF(errorHandler);
7294 Py_XDECREF(exc);
7295 return ret;
7296}
7297
Victor Stinner3a50e702011-10-18 21:21:00 +02007298static PyObject *
7299encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007300 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 const char *errors)
7302{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007303 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007305 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007306 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007307
Benjamin Petersonbac79492012-01-14 13:34:47 -05007308 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007309 return NULL;
7310 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007311
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 if (code_page < 0) {
7313 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7314 return NULL;
7315 }
7316
Martin v. Löwis3d325192011-11-04 18:23:06 +01007317 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007318 return PyBytes_FromStringAndSize(NULL, 0);
7319
Victor Stinner7581cef2011-11-03 22:32:33 +01007320 offset = 0;
7321 do
7322 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007323#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007324 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007325 chunks. */
7326 if (len > INT_MAX/2) {
7327 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007328 done = 0;
7329 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007330 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007332 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007333 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007334 done = 1;
7335 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007336
Victor Stinner76a31a62011-11-04 00:05:13 +01007337 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007338 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 errors);
7340 if (ret == -2)
7341 ret = encode_code_page_errors(code_page, &outbytes,
7342 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007344 if (ret < 0) {
7345 Py_XDECREF(outbytes);
7346 return NULL;
7347 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007348
Victor Stinner7581cef2011-11-03 22:32:33 +01007349 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007350 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007351 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 return outbytes;
7354}
7355
7356PyObject *
7357PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7358 Py_ssize_t size,
7359 const char *errors)
7360{
Victor Stinner7581cef2011-11-03 22:32:33 +01007361 PyObject *unicode, *res;
7362 unicode = PyUnicode_FromUnicode(p, size);
7363 if (unicode == NULL)
7364 return NULL;
7365 res = encode_code_page(CP_ACP, unicode, errors);
7366 Py_DECREF(unicode);
7367 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007368}
7369
7370PyObject *
7371PyUnicode_EncodeCodePage(int code_page,
7372 PyObject *unicode,
7373 const char *errors)
7374{
Victor Stinner7581cef2011-11-03 22:32:33 +01007375 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007376}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007377
Alexander Belopolsky40018472011-02-26 01:02:56 +00007378PyObject *
7379PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007380{
7381 if (!PyUnicode_Check(unicode)) {
7382 PyErr_BadArgument();
7383 return NULL;
7384 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007385 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007386}
7387
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007388#undef NEED_RETRY
7389
Victor Stinner99b95382011-07-04 14:23:54 +02007390#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007391
Guido van Rossumd57fd912000-03-10 22:53:23 +00007392/* --- Character Mapping Codec -------------------------------------------- */
7393
Alexander Belopolsky40018472011-02-26 01:02:56 +00007394PyObject *
7395PyUnicode_DecodeCharmap(const char *s,
7396 Py_ssize_t size,
7397 PyObject *mapping,
7398 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007399{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007400 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007401 Py_ssize_t startinpos;
7402 Py_ssize_t endinpos;
7403 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007404 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007405 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007406 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007407 PyObject *errorHandler = NULL;
7408 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007409
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410 /* Default to Latin-1 */
7411 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007412 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007413
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007414 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007415 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007416 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007417 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007418 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007419 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007420 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007421 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007422 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007423 enum PyUnicode_Kind mapkind;
7424 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007425 Py_UCS4 x;
7426
Benjamin Petersonbac79492012-01-14 13:34:47 -05007427 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007428 return NULL;
7429
7430 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007431 mapdata = PyUnicode_DATA(mapping);
7432 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007433 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007434 unsigned char ch;
7435 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7436 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7437 if (outkind == PyUnicode_1BYTE_KIND) {
7438 void *outdata = PyUnicode_DATA(v);
7439 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7440 while (s < e) {
7441 unsigned char ch = *s;
7442 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7443 if (x > maxchar)
7444 goto Error;
7445 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7446 ++s;
7447 }
7448 break;
7449 }
7450 else if (outkind == PyUnicode_2BYTE_KIND) {
7451 void *outdata = PyUnicode_DATA(v);
7452 while (s < e) {
7453 unsigned char ch = *s;
7454 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7455 if (x == 0xFFFE)
7456 goto Error;
7457 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7458 ++s;
7459 }
7460 break;
7461 }
7462 }
7463 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007464
Benjamin Peterson29060642009-01-31 22:14:21 +00007465 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007466 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007467 else
7468 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007469Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007470 if (x == 0xfffe)
7471 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007472 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007473 startinpos = s-starts;
7474 endinpos = startinpos+1;
7475 if (unicode_decode_call_errorhandler(
7476 errors, &errorHandler,
7477 "charmap", "character maps to <undefined>",
7478 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007479 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007480 goto onError;
7481 }
7482 continue;
7483 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007484
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007485 if (unicode_putchar(&v, &outpos, x) < 0)
7486 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007487 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007488 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007489 }
7490 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007491 while (s < e) {
7492 unsigned char ch = *s;
7493 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007494
Benjamin Peterson29060642009-01-31 22:14:21 +00007495 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7496 w = PyLong_FromLong((long)ch);
7497 if (w == NULL)
7498 goto onError;
7499 x = PyObject_GetItem(mapping, w);
7500 Py_DECREF(w);
7501 if (x == NULL) {
7502 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7503 /* No mapping found means: mapping is undefined. */
7504 PyErr_Clear();
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007505 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007506 } else
7507 goto onError;
7508 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007509
Benjamin Peterson29060642009-01-31 22:14:21 +00007510 /* Apply mapping */
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007511 if (x == Py_None)
7512 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 if (PyLong_Check(x)) {
7514 long value = PyLong_AS_LONG(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007515 if (value == 0xFFFE)
7516 goto Undefined;
Antoine Pitroua1f76552012-09-23 20:00:04 +02007517 if (value < 0 || value > MAX_UNICODE) {
7518 PyErr_Format(PyExc_TypeError,
7519 "character mapping must be in range(0x%lx)",
7520 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 Py_DECREF(x);
7522 goto onError;
7523 }
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007524 if (unicode_putchar(&v, &outpos, value) < 0) {
7525 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007526 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007527 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007528 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007530 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007531
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007532 if (PyUnicode_READY(x) == -1) {
7533 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007534 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007535 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007536 targetsize = PyUnicode_GET_LENGTH(x);
7537
7538 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007539 /* 1-1 mapping */
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007540 Py_UCS4 value = PyUnicode_READ_CHAR(x, 0);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007541 if (value == 0xFFFE)
7542 goto Undefined;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007543 if (unicode_putchar(&v, &outpos, value) < 0) {
7544 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007545 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007546 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007547 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007548 else if (targetsize > 1) {
7549 /* 1-n mapping */
7550 if (targetsize > extrachars) {
7551 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007552 Py_ssize_t needed = (targetsize - extrachars) + \
7553 (targetsize << 2);
7554 extrachars += needed;
7555 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007556 if (unicode_resize(&v,
7557 PyUnicode_GET_LENGTH(v) + needed) < 0)
7558 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007559 Py_DECREF(x);
7560 goto onError;
7561 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007562 }
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007563 if (unicode_widen(&v, outpos,
7564 PyUnicode_MAX_CHAR_VALUE(x)) < 0) {
7565 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007566 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007567 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007568 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7569 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007570 extrachars -= targetsize;
7571 }
7572 /* 1-0 mapping: skip the character */
7573 }
7574 else {
7575 /* wrong return value */
7576 PyErr_SetString(PyExc_TypeError,
7577 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007578 Py_DECREF(x);
7579 goto onError;
7580 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007581 Py_DECREF(x);
7582 ++s;
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007583 continue;
7584Undefined:
7585 /* undefined mapping */
7586 Py_XDECREF(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007587 startinpos = s-starts;
7588 endinpos = startinpos+1;
7589 if (unicode_decode_call_errorhandler(
7590 errors, &errorHandler,
7591 "charmap", "character maps to <undefined>",
7592 &starts, &e, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007593 &v, &outpos)) {
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007594 goto onError;
7595 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007596 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007597 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007598 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007599 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007600 Py_XDECREF(errorHandler);
7601 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007602 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007603
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007605 Py_XDECREF(errorHandler);
7606 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007607 Py_XDECREF(v);
7608 return NULL;
7609}
7610
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007611/* Charmap encoding: the lookup table */
7612
Alexander Belopolsky40018472011-02-26 01:02:56 +00007613struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 PyObject_HEAD
7615 unsigned char level1[32];
7616 int count2, count3;
7617 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007618};
7619
7620static PyObject*
7621encoding_map_size(PyObject *obj, PyObject* args)
7622{
7623 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007624 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007625 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007626}
7627
7628static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007629 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007630 PyDoc_STR("Return the size (in bytes) of this object") },
7631 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007632};
7633
7634static void
7635encoding_map_dealloc(PyObject* o)
7636{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007637 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007638}
7639
7640static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007641 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007642 "EncodingMap", /*tp_name*/
7643 sizeof(struct encoding_map), /*tp_basicsize*/
7644 0, /*tp_itemsize*/
7645 /* methods */
7646 encoding_map_dealloc, /*tp_dealloc*/
7647 0, /*tp_print*/
7648 0, /*tp_getattr*/
7649 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007650 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007651 0, /*tp_repr*/
7652 0, /*tp_as_number*/
7653 0, /*tp_as_sequence*/
7654 0, /*tp_as_mapping*/
7655 0, /*tp_hash*/
7656 0, /*tp_call*/
7657 0, /*tp_str*/
7658 0, /*tp_getattro*/
7659 0, /*tp_setattro*/
7660 0, /*tp_as_buffer*/
7661 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7662 0, /*tp_doc*/
7663 0, /*tp_traverse*/
7664 0, /*tp_clear*/
7665 0, /*tp_richcompare*/
7666 0, /*tp_weaklistoffset*/
7667 0, /*tp_iter*/
7668 0, /*tp_iternext*/
7669 encoding_map_methods, /*tp_methods*/
7670 0, /*tp_members*/
7671 0, /*tp_getset*/
7672 0, /*tp_base*/
7673 0, /*tp_dict*/
7674 0, /*tp_descr_get*/
7675 0, /*tp_descr_set*/
7676 0, /*tp_dictoffset*/
7677 0, /*tp_init*/
7678 0, /*tp_alloc*/
7679 0, /*tp_new*/
7680 0, /*tp_free*/
7681 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007682};
7683
7684PyObject*
7685PyUnicode_BuildEncodingMap(PyObject* string)
7686{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007687 PyObject *result;
7688 struct encoding_map *mresult;
7689 int i;
7690 int need_dict = 0;
7691 unsigned char level1[32];
7692 unsigned char level2[512];
7693 unsigned char *mlevel1, *mlevel2, *mlevel3;
7694 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007695 int kind;
7696 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007697 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007698 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007699
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007700 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701 PyErr_BadArgument();
7702 return NULL;
7703 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007704 kind = PyUnicode_KIND(string);
7705 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007706 length = PyUnicode_GET_LENGTH(string);
7707 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007708 memset(level1, 0xFF, sizeof level1);
7709 memset(level2, 0xFF, sizeof level2);
7710
7711 /* If there isn't a one-to-one mapping of NULL to \0,
7712 or if there are non-BMP characters, we need to use
7713 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007714 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007715 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007716 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007717 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007718 ch = PyUnicode_READ(kind, data, i);
7719 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007720 need_dict = 1;
7721 break;
7722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007723 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007724 /* unmapped character */
7725 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007726 l1 = ch >> 11;
7727 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007728 if (level1[l1] == 0xFF)
7729 level1[l1] = count2++;
7730 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007731 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007732 }
7733
7734 if (count2 >= 0xFF || count3 >= 0xFF)
7735 need_dict = 1;
7736
7737 if (need_dict) {
7738 PyObject *result = PyDict_New();
7739 PyObject *key, *value;
7740 if (!result)
7741 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007742 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007743 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007744 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007745 if (!key || !value)
7746 goto failed1;
7747 if (PyDict_SetItem(result, key, value) == -1)
7748 goto failed1;
7749 Py_DECREF(key);
7750 Py_DECREF(value);
7751 }
7752 return result;
7753 failed1:
7754 Py_XDECREF(key);
7755 Py_XDECREF(value);
7756 Py_DECREF(result);
7757 return NULL;
7758 }
7759
7760 /* Create a three-level trie */
7761 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7762 16*count2 + 128*count3 - 1);
7763 if (!result)
7764 return PyErr_NoMemory();
7765 PyObject_Init(result, &EncodingMapType);
7766 mresult = (struct encoding_map*)result;
7767 mresult->count2 = count2;
7768 mresult->count3 = count3;
7769 mlevel1 = mresult->level1;
7770 mlevel2 = mresult->level23;
7771 mlevel3 = mresult->level23 + 16*count2;
7772 memcpy(mlevel1, level1, 32);
7773 memset(mlevel2, 0xFF, 16*count2);
7774 memset(mlevel3, 0, 128*count3);
7775 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007776 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007777 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007778 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7779 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780 /* unmapped character */
7781 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007782 o1 = ch>>11;
7783 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007784 i2 = 16*mlevel1[o1] + o2;
7785 if (mlevel2[i2] == 0xFF)
7786 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007787 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007788 i3 = 128*mlevel2[i2] + o3;
7789 mlevel3[i3] = i;
7790 }
7791 return result;
7792}
7793
7794static int
Victor Stinner22168992011-11-20 17:09:18 +01007795encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007796{
7797 struct encoding_map *map = (struct encoding_map*)mapping;
7798 int l1 = c>>11;
7799 int l2 = (c>>7) & 0xF;
7800 int l3 = c & 0x7F;
7801 int i;
7802
Victor Stinner22168992011-11-20 17:09:18 +01007803 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007805 if (c == 0)
7806 return 0;
7807 /* level 1*/
7808 i = map->level1[l1];
7809 if (i == 0xFF) {
7810 return -1;
7811 }
7812 /* level 2*/
7813 i = map->level23[16*i+l2];
7814 if (i == 0xFF) {
7815 return -1;
7816 }
7817 /* level 3 */
7818 i = map->level23[16*map->count2 + 128*i + l3];
7819 if (i == 0) {
7820 return -1;
7821 }
7822 return i;
7823}
7824
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007825/* Lookup the character ch in the mapping. If the character
7826 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007827 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007828static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007829charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007830{
Christian Heimes217cfd12007-12-02 14:31:20 +00007831 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007832 PyObject *x;
7833
7834 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007835 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007836 x = PyObject_GetItem(mapping, w);
7837 Py_DECREF(w);
7838 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7840 /* No mapping found means: mapping is undefined. */
7841 PyErr_Clear();
7842 x = Py_None;
7843 Py_INCREF(x);
7844 return x;
7845 } else
7846 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007847 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007848 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007850 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 long value = PyLong_AS_LONG(x);
7852 if (value < 0 || value > 255) {
7853 PyErr_SetString(PyExc_TypeError,
7854 "character mapping must be in range(256)");
7855 Py_DECREF(x);
7856 return NULL;
7857 }
7858 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007859 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007860 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007861 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007862 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007863 /* wrong return value */
7864 PyErr_Format(PyExc_TypeError,
7865 "character mapping must return integer, bytes or None, not %.400s",
7866 x->ob_type->tp_name);
7867 Py_DECREF(x);
7868 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007869 }
7870}
7871
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007872static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007873charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007875 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7876 /* exponentially overallocate to minimize reallocations */
7877 if (requiredsize < 2*outsize)
7878 requiredsize = 2*outsize;
7879 if (_PyBytes_Resize(outobj, requiredsize))
7880 return -1;
7881 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882}
7883
Benjamin Peterson14339b62009-01-31 16:36:08 +00007884typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007885 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007886} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007887/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007888 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007889 space is available. Return a new reference to the object that
7890 was put in the output buffer, or Py_None, if the mapping was undefined
7891 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007892 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007893static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007894charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007895 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007896{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 PyObject *rep;
7898 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007899 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007900
Christian Heimes90aa7642007-12-19 02:45:37 +00007901 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007902 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 if (res == -1)
7905 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 if (outsize<requiredsize)
7907 if (charmapencode_resize(outobj, outpos, requiredsize))
7908 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007909 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007910 outstart[(*outpos)++] = (char)res;
7911 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 }
7913
7914 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007915 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 Py_DECREF(rep);
7919 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007920 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007921 if (PyLong_Check(rep)) {
7922 Py_ssize_t requiredsize = *outpos+1;
7923 if (outsize<requiredsize)
7924 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7925 Py_DECREF(rep);
7926 return enc_EXCEPTION;
7927 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007928 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007929 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007930 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007931 else {
7932 const char *repchars = PyBytes_AS_STRING(rep);
7933 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7934 Py_ssize_t requiredsize = *outpos+repsize;
7935 if (outsize<requiredsize)
7936 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7937 Py_DECREF(rep);
7938 return enc_EXCEPTION;
7939 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007940 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007941 memcpy(outstart + *outpos, repchars, repsize);
7942 *outpos += repsize;
7943 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007945 Py_DECREF(rep);
7946 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947}
7948
7949/* handle an error in PyUnicode_EncodeCharmap
7950 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007951static int
7952charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007953 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007955 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007956 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007957{
7958 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007959 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007960 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007961 enum PyUnicode_Kind kind;
7962 void *data;
7963 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007965 Py_ssize_t collstartpos = *inpos;
7966 Py_ssize_t collendpos = *inpos+1;
7967 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007968 char *encoding = "charmap";
7969 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007970 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007971 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007972 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007973
Benjamin Petersonbac79492012-01-14 13:34:47 -05007974 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007975 return -1;
7976 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007977 /* find all unencodable characters */
7978 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007979 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007980 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007981 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007982 val = encoding_map_lookup(ch, mapping);
7983 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007984 break;
7985 ++collendpos;
7986 continue;
7987 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007988
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007989 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7990 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 if (rep==NULL)
7992 return -1;
7993 else if (rep!=Py_None) {
7994 Py_DECREF(rep);
7995 break;
7996 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007999 }
8000 /* cache callback name lookup
8001 * (if not done yet, i.e. it's the first error) */
8002 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008003 if ((errors==NULL) || (!strcmp(errors, "strict")))
8004 *known_errorHandler = 1;
8005 else if (!strcmp(errors, "replace"))
8006 *known_errorHandler = 2;
8007 else if (!strcmp(errors, "ignore"))
8008 *known_errorHandler = 3;
8009 else if (!strcmp(errors, "xmlcharrefreplace"))
8010 *known_errorHandler = 4;
8011 else
8012 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008013 }
8014 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008015 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008016 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008017 return -1;
8018 case 2: /* replace */
8019 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 x = charmapencode_output('?', mapping, res, respos);
8021 if (x==enc_EXCEPTION) {
8022 return -1;
8023 }
8024 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008025 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 return -1;
8027 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008028 }
8029 /* fall through */
8030 case 3: /* ignore */
8031 *inpos = collendpos;
8032 break;
8033 case 4: /* xmlcharrefreplace */
8034 /* generate replacement (temporarily (mis)uses p) */
8035 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 char buffer[2+29+1+1];
8037 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008038 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 for (cp = buffer; *cp; ++cp) {
8040 x = charmapencode_output(*cp, mapping, res, respos);
8041 if (x==enc_EXCEPTION)
8042 return -1;
8043 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008044 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008045 return -1;
8046 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008047 }
8048 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008049 *inpos = collendpos;
8050 break;
8051 default:
8052 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008053 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008055 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008057 if (PyBytes_Check(repunicode)) {
8058 /* Directly copy bytes result to output. */
8059 Py_ssize_t outsize = PyBytes_Size(*res);
8060 Py_ssize_t requiredsize;
8061 repsize = PyBytes_Size(repunicode);
8062 requiredsize = *respos + repsize;
8063 if (requiredsize > outsize)
8064 /* Make room for all additional bytes. */
8065 if (charmapencode_resize(res, respos, requiredsize)) {
8066 Py_DECREF(repunicode);
8067 return -1;
8068 }
8069 memcpy(PyBytes_AsString(*res) + *respos,
8070 PyBytes_AsString(repunicode), repsize);
8071 *respos += repsize;
8072 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008073 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008074 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008075 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008076 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008077 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008078 Py_DECREF(repunicode);
8079 return -1;
8080 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008081 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008082 data = PyUnicode_DATA(repunicode);
8083 kind = PyUnicode_KIND(repunicode);
8084 for (index = 0; index < repsize; index++) {
8085 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8086 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008088 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 return -1;
8090 }
8091 else if (x==enc_FAILED) {
8092 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008093 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 return -1;
8095 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008096 }
8097 *inpos = newpos;
8098 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008099 }
8100 return 0;
8101}
8102
Alexander Belopolsky40018472011-02-26 01:02:56 +00008103PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008104_PyUnicode_EncodeCharmap(PyObject *unicode,
8105 PyObject *mapping,
8106 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008107{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008108 /* output object */
8109 PyObject *res = NULL;
8110 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008111 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008114 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008115 PyObject *errorHandler = NULL;
8116 PyObject *exc = NULL;
8117 /* the following variable is used for caching string comparisons
8118 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8119 * 3=ignore, 4=xmlcharrefreplace */
8120 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121
Benjamin Petersonbac79492012-01-14 13:34:47 -05008122 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008123 return NULL;
8124 size = PyUnicode_GET_LENGTH(unicode);
8125
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 /* Default to Latin-1 */
8127 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008128 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008129
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130 /* allocate enough for a simple encoding without
8131 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008132 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133 if (res == NULL)
8134 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008135 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008137
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008139 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008140 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008141 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 if (x==enc_EXCEPTION) /* error */
8143 goto onError;
8144 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008145 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 &exc,
8147 &known_errorHandler, &errorHandler, errors,
8148 &res, &respos)) {
8149 goto onError;
8150 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008151 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 else
8153 /* done with this character => adjust input position */
8154 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008155 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008156
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008157 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008158 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008159 if (_PyBytes_Resize(&res, respos) < 0)
8160 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008161
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008162 Py_XDECREF(exc);
8163 Py_XDECREF(errorHandler);
8164 return res;
8165
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008167 Py_XDECREF(res);
8168 Py_XDECREF(exc);
8169 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008170 return NULL;
8171}
8172
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008173/* Deprecated */
8174PyObject *
8175PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8176 Py_ssize_t size,
8177 PyObject *mapping,
8178 const char *errors)
8179{
8180 PyObject *result;
8181 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8182 if (unicode == NULL)
8183 return NULL;
8184 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8185 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008186 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008187}
8188
Alexander Belopolsky40018472011-02-26 01:02:56 +00008189PyObject *
8190PyUnicode_AsCharmapString(PyObject *unicode,
8191 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008192{
8193 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008194 PyErr_BadArgument();
8195 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008196 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008197 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008198}
8199
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008200/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201static void
8202make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008203 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008204 Py_ssize_t startpos, Py_ssize_t endpos,
8205 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008206{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008207 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008208 *exceptionObject = _PyUnicodeTranslateError_Create(
8209 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210 }
8211 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8213 goto onError;
8214 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8215 goto onError;
8216 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8217 goto onError;
8218 return;
8219 onError:
8220 Py_DECREF(*exceptionObject);
8221 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008222 }
8223}
8224
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008225/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008226static void
8227raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008228 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008229 Py_ssize_t startpos, Py_ssize_t endpos,
8230 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231{
8232 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008233 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008234 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236}
8237
8238/* error handling callback helper:
8239 build arguments, call the callback and check the arguments,
8240 put the result into newpos and return the replacement string, which
8241 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008242static PyObject *
8243unicode_translate_call_errorhandler(const char *errors,
8244 PyObject **errorHandler,
8245 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008246 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008247 Py_ssize_t startpos, Py_ssize_t endpos,
8248 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008250 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008251
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008252 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253 PyObject *restuple;
8254 PyObject *resunicode;
8255
8256 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008258 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 }
8261
8262 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008263 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008264 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266
8267 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008269 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008272 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 Py_DECREF(restuple);
8274 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275 }
8276 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 &resunicode, &i_newpos)) {
8278 Py_DECREF(restuple);
8279 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008281 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008282 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008283 else
8284 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008285 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8287 Py_DECREF(restuple);
8288 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008289 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 Py_INCREF(resunicode);
8291 Py_DECREF(restuple);
8292 return resunicode;
8293}
8294
8295/* Lookup the character ch in the mapping and put the result in result,
8296 which must be decrefed by the caller.
8297 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008298static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008299charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300{
Christian Heimes217cfd12007-12-02 14:31:20 +00008301 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302 PyObject *x;
8303
8304 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 x = PyObject_GetItem(mapping, w);
8307 Py_DECREF(w);
8308 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8310 /* No mapping found means: use 1:1 mapping. */
8311 PyErr_Clear();
8312 *result = NULL;
8313 return 0;
8314 } else
8315 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 }
8317 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 *result = x;
8319 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008321 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 long value = PyLong_AS_LONG(x);
8323 long max = PyUnicode_GetMax();
8324 if (value < 0 || value > max) {
8325 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008326 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008327 Py_DECREF(x);
8328 return -1;
8329 }
8330 *result = x;
8331 return 0;
8332 }
8333 else if (PyUnicode_Check(x)) {
8334 *result = x;
8335 return 0;
8336 }
8337 else {
8338 /* wrong return value */
8339 PyErr_SetString(PyExc_TypeError,
8340 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008341 Py_DECREF(x);
8342 return -1;
8343 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344}
8345/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 if not reallocate and adjust various state variables.
8347 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008348static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008349charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008352 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008353 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008354 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 /* exponentially overallocate to minimize reallocations */
8356 if (requiredsize < 2 * oldsize)
8357 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008358 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8359 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008361 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008362 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 }
8364 return 0;
8365}
8366/* lookup the character, put the result in the output string and adjust
8367 various state variables. Return a new reference to the object that
8368 was put in the output buffer in *result, or Py_None, if the mapping was
8369 undefined (in which case no character was written).
8370 The called must decref result.
8371 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008372static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8374 PyObject *mapping, Py_UCS4 **output,
8375 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008376 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8379 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 }
8385 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008387 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008389 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008390 }
8391 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 Py_ssize_t repsize;
8393 if (PyUnicode_READY(*res) == -1)
8394 return -1;
8395 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 if (repsize==1) {
8397 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008398 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 }
8400 else if (repsize!=0) {
8401 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008402 Py_ssize_t requiredsize = *opos +
8403 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008405 Py_ssize_t i;
8406 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408 for(i = 0; i < repsize; i++)
8409 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008411 }
8412 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 return 0;
8415}
8416
Alexander Belopolsky40018472011-02-26 01:02:56 +00008417PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008418_PyUnicode_TranslateCharmap(PyObject *input,
8419 PyObject *mapping,
8420 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008422 /* input object */
8423 char *idata;
8424 Py_ssize_t size, i;
8425 int kind;
8426 /* output buffer */
8427 Py_UCS4 *output = NULL;
8428 Py_ssize_t osize;
8429 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008431 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432 char *reason = "character maps to <undefined>";
8433 PyObject *errorHandler = NULL;
8434 PyObject *exc = NULL;
8435 /* the following variable is used for caching string comparisons
8436 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8437 * 3=ignore, 4=xmlcharrefreplace */
8438 int known_errorHandler = -1;
8439
Guido van Rossumd57fd912000-03-10 22:53:23 +00008440 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 PyErr_BadArgument();
8442 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008443 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 if (PyUnicode_READY(input) == -1)
8446 return NULL;
8447 idata = (char*)PyUnicode_DATA(input);
8448 kind = PyUnicode_KIND(input);
8449 size = PyUnicode_GET_LENGTH(input);
8450 i = 0;
8451
8452 if (size == 0) {
8453 Py_INCREF(input);
8454 return input;
8455 }
8456
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457 /* allocate enough for a simple 1:1 translation without
8458 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008459 osize = size;
8460 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8461 opos = 0;
8462 if (output == NULL) {
8463 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008465 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 /* try to encode it */
8469 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470 if (charmaptranslate_output(input, i, mapping,
8471 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 Py_XDECREF(x);
8473 goto onError;
8474 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008475 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 else { /* untranslatable character */
8479 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8480 Py_ssize_t repsize;
8481 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008482 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 Py_ssize_t collstart = i;
8485 Py_ssize_t collend = i+1;
8486 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008487
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 while (collend < size) {
8490 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 goto onError;
8492 Py_XDECREF(x);
8493 if (x!=Py_None)
8494 break;
8495 ++collend;
8496 }
8497 /* cache callback name lookup
8498 * (if not done yet, i.e. it's the first error) */
8499 if (known_errorHandler==-1) {
8500 if ((errors==NULL) || (!strcmp(errors, "strict")))
8501 known_errorHandler = 1;
8502 else if (!strcmp(errors, "replace"))
8503 known_errorHandler = 2;
8504 else if (!strcmp(errors, "ignore"))
8505 known_errorHandler = 3;
8506 else if (!strcmp(errors, "xmlcharrefreplace"))
8507 known_errorHandler = 4;
8508 else
8509 known_errorHandler = 0;
8510 }
8511 switch (known_errorHandler) {
8512 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 raise_translate_exception(&exc, input, collstart,
8514 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008515 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 case 2: /* replace */
8517 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008518 for (coll = collstart; coll<collend; coll++)
8519 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 /* fall through */
8521 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 break;
8524 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 /* generate replacement (temporarily (mis)uses i) */
8526 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 char buffer[2+29+1+1];
8528 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008529 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8530 if (charmaptranslate_makespace(&output, &osize,
8531 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 goto onError;
8533 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 break;
8538 default:
8539 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008540 reason, input, &exc,
8541 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008542 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008544 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008545 Py_DECREF(repunicode);
8546 goto onError;
8547 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 repsize = PyUnicode_GET_LENGTH(repunicode);
8550 if (charmaptranslate_makespace(&output, &osize,
8551 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 Py_DECREF(repunicode);
8553 goto onError;
8554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008555 for (uni2 = 0; repsize-->0; ++uni2)
8556 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8557 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008559 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008560 }
8561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8563 if (!res)
8564 goto onError;
8565 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 Py_XDECREF(exc);
8567 Py_XDECREF(errorHandler);
8568 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 Py_XDECREF(exc);
8573 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008574 return NULL;
8575}
8576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008577/* Deprecated. Use PyUnicode_Translate instead. */
8578PyObject *
8579PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8580 Py_ssize_t size,
8581 PyObject *mapping,
8582 const char *errors)
8583{
Christian Heimes5f520f42012-09-11 14:03:25 +02008584 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8586 if (!unicode)
8587 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008588 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8589 Py_DECREF(unicode);
8590 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591}
8592
Alexander Belopolsky40018472011-02-26 01:02:56 +00008593PyObject *
8594PyUnicode_Translate(PyObject *str,
8595 PyObject *mapping,
8596 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597{
8598 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008599
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600 str = PyUnicode_FromObject(str);
8601 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008602 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008604 Py_DECREF(str);
8605 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606}
Tim Petersced69f82003-09-16 20:30:58 +00008607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008609fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610{
8611 /* No need to call PyUnicode_READY(self) because this function is only
8612 called as a callback from fixup() which does it already. */
8613 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8614 const int kind = PyUnicode_KIND(self);
8615 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008616 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008617 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 Py_ssize_t i;
8619
8620 for (i = 0; i < len; ++i) {
8621 ch = PyUnicode_READ(kind, data, i);
8622 fixed = 0;
8623 if (ch > 127) {
8624 if (Py_UNICODE_ISSPACE(ch))
8625 fixed = ' ';
8626 else {
8627 const int decimal = Py_UNICODE_TODECIMAL(ch);
8628 if (decimal >= 0)
8629 fixed = '0' + decimal;
8630 }
8631 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008632 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008633 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 PyUnicode_WRITE(kind, data, i, fixed);
8635 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008636 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008637 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 }
8640
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008641 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642}
8643
8644PyObject *
8645_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8646{
8647 if (!PyUnicode_Check(unicode)) {
8648 PyErr_BadInternalCall();
8649 return NULL;
8650 }
8651 if (PyUnicode_READY(unicode) == -1)
8652 return NULL;
8653 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8654 /* If the string is already ASCII, just return the same string */
8655 Py_INCREF(unicode);
8656 return unicode;
8657 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008658 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659}
8660
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008661PyObject *
8662PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8663 Py_ssize_t length)
8664{
Victor Stinnerf0124502011-11-21 23:12:56 +01008665 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008666 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008667 Py_UCS4 maxchar;
8668 enum PyUnicode_Kind kind;
8669 void *data;
8670
Victor Stinner99d7ad02012-02-22 13:37:39 +01008671 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008672 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008673 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008674 if (ch > 127) {
8675 int decimal = Py_UNICODE_TODECIMAL(ch);
8676 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008677 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008678 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008679 }
8680 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008681
8682 /* Copy to a new string */
8683 decimal = PyUnicode_New(length, maxchar);
8684 if (decimal == NULL)
8685 return decimal;
8686 kind = PyUnicode_KIND(decimal);
8687 data = PyUnicode_DATA(decimal);
8688 /* Iterate over code points */
8689 for (i = 0; i < length; i++) {
8690 Py_UNICODE ch = s[i];
8691 if (ch > 127) {
8692 int decimal = Py_UNICODE_TODECIMAL(ch);
8693 if (decimal >= 0)
8694 ch = '0' + decimal;
8695 }
8696 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008698 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008699}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008700/* --- Decimal Encoder ---------------------------------------------------- */
8701
Alexander Belopolsky40018472011-02-26 01:02:56 +00008702int
8703PyUnicode_EncodeDecimal(Py_UNICODE *s,
8704 Py_ssize_t length,
8705 char *output,
8706 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008707{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008708 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008709 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008710 enum PyUnicode_Kind kind;
8711 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008712
8713 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 PyErr_BadArgument();
8715 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008716 }
8717
Victor Stinner42bf7752011-11-21 22:52:58 +01008718 unicode = PyUnicode_FromUnicode(s, length);
8719 if (unicode == NULL)
8720 return -1;
8721
Benjamin Petersonbac79492012-01-14 13:34:47 -05008722 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008723 Py_DECREF(unicode);
8724 return -1;
8725 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008726 kind = PyUnicode_KIND(unicode);
8727 data = PyUnicode_DATA(unicode);
8728
Victor Stinnerb84d7232011-11-22 01:50:07 +01008729 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008730 PyObject *exc;
8731 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008733 Py_ssize_t startpos;
8734
8735 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008736
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008738 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008739 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008741 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 decimal = Py_UNICODE_TODECIMAL(ch);
8743 if (decimal >= 0) {
8744 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008745 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 continue;
8747 }
8748 if (0 < ch && ch < 256) {
8749 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008750 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008751 continue;
8752 }
Victor Stinner6345be92011-11-25 20:09:01 +01008753
Victor Stinner42bf7752011-11-21 22:52:58 +01008754 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008755 exc = NULL;
8756 raise_encode_exception(&exc, "decimal", unicode,
8757 startpos, startpos+1,
8758 "invalid decimal Unicode string");
8759 Py_XDECREF(exc);
8760 Py_DECREF(unicode);
8761 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008762 }
8763 /* 0-terminate the output string */
8764 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008765 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008766 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008767}
8768
Guido van Rossumd57fd912000-03-10 22:53:23 +00008769/* --- Helpers ------------------------------------------------------------ */
8770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008772any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 Py_ssize_t start,
8774 Py_ssize_t end)
8775{
8776 int kind1, kind2, kind;
8777 void *buf1, *buf2;
8778 Py_ssize_t len1, len2, result;
8779
8780 kind1 = PyUnicode_KIND(s1);
8781 kind2 = PyUnicode_KIND(s2);
8782 kind = kind1 > kind2 ? kind1 : kind2;
8783 buf1 = PyUnicode_DATA(s1);
8784 buf2 = PyUnicode_DATA(s2);
8785 if (kind1 != kind)
8786 buf1 = _PyUnicode_AsKind(s1, kind);
8787 if (!buf1)
8788 return -2;
8789 if (kind2 != kind)
8790 buf2 = _PyUnicode_AsKind(s2, kind);
8791 if (!buf2) {
8792 if (kind1 != kind) PyMem_Free(buf1);
8793 return -2;
8794 }
8795 len1 = PyUnicode_GET_LENGTH(s1);
8796 len2 = PyUnicode_GET_LENGTH(s2);
8797
Victor Stinner794d5672011-10-10 03:21:36 +02008798 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008799 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008800 case PyUnicode_1BYTE_KIND:
8801 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8802 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8803 else
8804 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8805 break;
8806 case PyUnicode_2BYTE_KIND:
8807 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8808 break;
8809 case PyUnicode_4BYTE_KIND:
8810 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8811 break;
8812 default:
8813 assert(0); result = -2;
8814 }
8815 }
8816 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008817 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008818 case PyUnicode_1BYTE_KIND:
8819 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8820 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8821 else
8822 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8823 break;
8824 case PyUnicode_2BYTE_KIND:
8825 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8826 break;
8827 case PyUnicode_4BYTE_KIND:
8828 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8829 break;
8830 default:
8831 assert(0); result = -2;
8832 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833 }
8834
8835 if (kind1 != kind)
8836 PyMem_Free(buf1);
8837 if (kind2 != kind)
8838 PyMem_Free(buf2);
8839
8840 return result;
8841}
8842
8843Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008844_PyUnicode_InsertThousandsGrouping(
8845 PyObject *unicode, Py_ssize_t index,
8846 Py_ssize_t n_buffer,
8847 void *digits, Py_ssize_t n_digits,
8848 Py_ssize_t min_width,
8849 const char *grouping, PyObject *thousands_sep,
8850 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851{
Victor Stinner41a863c2012-02-24 00:37:51 +01008852 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008853 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008854 Py_ssize_t thousands_sep_len;
8855 Py_ssize_t len;
8856
8857 if (unicode != NULL) {
8858 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008859 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008860 }
8861 else {
8862 kind = PyUnicode_1BYTE_KIND;
8863 data = NULL;
8864 }
8865 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8866 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8867 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8868 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008869 if (thousands_sep_kind < kind) {
8870 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8871 if (!thousands_sep_data)
8872 return -1;
8873 }
8874 else {
8875 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8876 if (!data)
8877 return -1;
8878 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008879 }
8880
Benjamin Petersonead6b532011-12-20 17:23:42 -06008881 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008883 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008884 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008885 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008886 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008887 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008888 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008889 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008890 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008891 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008892 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008893 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008894 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008895 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008896 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008897 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008898 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008899 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008900 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008901 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008902 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008903 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008904 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008905 break;
8906 default:
8907 assert(0);
8908 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008909 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008910 if (unicode != NULL && thousands_sep_kind != kind) {
8911 if (thousands_sep_kind < kind)
8912 PyMem_Free(thousands_sep_data);
8913 else
8914 PyMem_Free(data);
8915 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008916 if (unicode == NULL) {
8917 *maxchar = 127;
8918 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07008919 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02008920 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008921 }
8922 }
8923 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924}
8925
8926
Thomas Wouters477c8d52006-05-27 19:21:47 +00008927/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008928#define ADJUST_INDICES(start, end, len) \
8929 if (end > len) \
8930 end = len; \
8931 else if (end < 0) { \
8932 end += len; \
8933 if (end < 0) \
8934 end = 0; \
8935 } \
8936 if (start < 0) { \
8937 start += len; \
8938 if (start < 0) \
8939 start = 0; \
8940 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008941
Alexander Belopolsky40018472011-02-26 01:02:56 +00008942Py_ssize_t
8943PyUnicode_Count(PyObject *str,
8944 PyObject *substr,
8945 Py_ssize_t start,
8946 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008948 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008949 PyObject* str_obj;
8950 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 int kind1, kind2, kind;
8952 void *buf1 = NULL, *buf2 = NULL;
8953 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008954
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008955 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008956 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008957 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008958 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008959 if (!sub_obj) {
8960 Py_DECREF(str_obj);
8961 return -1;
8962 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008963 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008964 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008965 Py_DECREF(str_obj);
8966 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967 }
Tim Petersced69f82003-09-16 20:30:58 +00008968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969 kind1 = PyUnicode_KIND(str_obj);
8970 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008971 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008974 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008975 if (kind2 > kind) {
8976 Py_DECREF(sub_obj);
8977 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008978 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008979 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008980 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008981 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 if (!buf2)
8983 goto onError;
8984 len1 = PyUnicode_GET_LENGTH(str_obj);
8985 len2 = PyUnicode_GET_LENGTH(sub_obj);
8986
8987 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008988 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008990 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8991 result = asciilib_count(
8992 ((Py_UCS1*)buf1) + start, end - start,
8993 buf2, len2, PY_SSIZE_T_MAX
8994 );
8995 else
8996 result = ucs1lib_count(
8997 ((Py_UCS1*)buf1) + start, end - start,
8998 buf2, len2, PY_SSIZE_T_MAX
8999 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000 break;
9001 case PyUnicode_2BYTE_KIND:
9002 result = ucs2lib_count(
9003 ((Py_UCS2*)buf1) + start, end - start,
9004 buf2, len2, PY_SSIZE_T_MAX
9005 );
9006 break;
9007 case PyUnicode_4BYTE_KIND:
9008 result = ucs4lib_count(
9009 ((Py_UCS4*)buf1) + start, end - start,
9010 buf2, len2, PY_SSIZE_T_MAX
9011 );
9012 break;
9013 default:
9014 assert(0); result = 0;
9015 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009016
9017 Py_DECREF(sub_obj);
9018 Py_DECREF(str_obj);
9019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009020 if (kind2 != kind)
9021 PyMem_Free(buf2);
9022
Guido van Rossumd57fd912000-03-10 22:53:23 +00009023 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 onError:
9025 Py_DECREF(sub_obj);
9026 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027 if (kind2 != kind && buf2)
9028 PyMem_Free(buf2);
9029 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030}
9031
Alexander Belopolsky40018472011-02-26 01:02:56 +00009032Py_ssize_t
9033PyUnicode_Find(PyObject *str,
9034 PyObject *sub,
9035 Py_ssize_t start,
9036 Py_ssize_t end,
9037 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009039 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009040
Guido van Rossumd57fd912000-03-10 22:53:23 +00009041 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009042 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009043 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009044 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009045 if (!sub) {
9046 Py_DECREF(str);
9047 return -2;
9048 }
9049 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9050 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009051 Py_DECREF(str);
9052 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009053 }
Tim Petersced69f82003-09-16 20:30:58 +00009054
Victor Stinner794d5672011-10-10 03:21:36 +02009055 result = any_find_slice(direction,
9056 str, sub, start, end
9057 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009058
Guido van Rossumd57fd912000-03-10 22:53:23 +00009059 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009060 Py_DECREF(sub);
9061
Guido van Rossumd57fd912000-03-10 22:53:23 +00009062 return result;
9063}
9064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009065Py_ssize_t
9066PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9067 Py_ssize_t start, Py_ssize_t end,
9068 int direction)
9069{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009071 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 if (PyUnicode_READY(str) == -1)
9073 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009074 if (start < 0 || end < 0) {
9075 PyErr_SetString(PyExc_IndexError, "string index out of range");
9076 return -2;
9077 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078 if (end > PyUnicode_GET_LENGTH(str))
9079 end = PyUnicode_GET_LENGTH(str);
9080 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009081 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9082 kind, end-start, ch, direction);
9083 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009085 else
9086 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009087}
9088
Alexander Belopolsky40018472011-02-26 01:02:56 +00009089static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009090tailmatch(PyObject *self,
9091 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009092 Py_ssize_t start,
9093 Py_ssize_t end,
9094 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 int kind_self;
9097 int kind_sub;
9098 void *data_self;
9099 void *data_sub;
9100 Py_ssize_t offset;
9101 Py_ssize_t i;
9102 Py_ssize_t end_sub;
9103
9104 if (PyUnicode_READY(self) == -1 ||
9105 PyUnicode_READY(substring) == -1)
9106 return 0;
9107
9108 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009109 return 1;
9110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9112 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009113 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009114 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009115
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009116 kind_self = PyUnicode_KIND(self);
9117 data_self = PyUnicode_DATA(self);
9118 kind_sub = PyUnicode_KIND(substring);
9119 data_sub = PyUnicode_DATA(substring);
9120 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9121
9122 if (direction > 0)
9123 offset = end;
9124 else
9125 offset = start;
9126
9127 if (PyUnicode_READ(kind_self, data_self, offset) ==
9128 PyUnicode_READ(kind_sub, data_sub, 0) &&
9129 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9130 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9131 /* If both are of the same kind, memcmp is sufficient */
9132 if (kind_self == kind_sub) {
9133 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009134 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 data_sub,
9136 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009137 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009138 }
9139 /* otherwise we have to compare each character by first accesing it */
9140 else {
9141 /* We do not need to compare 0 and len(substring)-1 because
9142 the if statement above ensured already that they are equal
9143 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009144 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009145 for (i = 1; i < end_sub; ++i) {
9146 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9147 PyUnicode_READ(kind_sub, data_sub, i))
9148 return 0;
9149 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009150 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009151 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009152 }
9153
9154 return 0;
9155}
9156
Alexander Belopolsky40018472011-02-26 01:02:56 +00009157Py_ssize_t
9158PyUnicode_Tailmatch(PyObject *str,
9159 PyObject *substr,
9160 Py_ssize_t start,
9161 Py_ssize_t end,
9162 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009164 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009165
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166 str = PyUnicode_FromObject(str);
9167 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009169 substr = PyUnicode_FromObject(substr);
9170 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 Py_DECREF(str);
9172 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173 }
Tim Petersced69f82003-09-16 20:30:58 +00009174
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009175 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177 Py_DECREF(str);
9178 Py_DECREF(substr);
9179 return result;
9180}
9181
Guido van Rossumd57fd912000-03-10 22:53:23 +00009182/* Apply fixfct filter to the Unicode object self and return a
9183 reference to the modified object */
9184
Alexander Belopolsky40018472011-02-26 01:02:56 +00009185static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009186fixup(PyObject *self,
9187 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189 PyObject *u;
9190 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009191 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009192
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009193 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009194 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009195 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009196 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 /* fix functions return the new maximum character in a string,
9199 if the kind of the resulting unicode object does not change,
9200 everything is fine. Otherwise we need to change the string kind
9201 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009202 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009203
9204 if (maxchar_new == 0) {
9205 /* no changes */;
9206 if (PyUnicode_CheckExact(self)) {
9207 Py_DECREF(u);
9208 Py_INCREF(self);
9209 return self;
9210 }
9211 else
9212 return u;
9213 }
9214
Victor Stinnere6abb482012-05-02 01:15:40 +02009215 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009216
Victor Stinnereaab6042011-12-11 22:22:39 +01009217 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009219
9220 /* In case the maximum character changed, we need to
9221 convert the string to the new category. */
9222 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9223 if (v == NULL) {
9224 Py_DECREF(u);
9225 return NULL;
9226 }
9227 if (maxchar_new > maxchar_old) {
9228 /* If the maxchar increased so that the kind changed, not all
9229 characters are representable anymore and we need to fix the
9230 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009231 _PyUnicode_FastCopyCharacters(v, 0,
9232 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009233 maxchar_old = fixfct(v);
9234 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 }
9236 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009237 _PyUnicode_FastCopyCharacters(v, 0,
9238 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009240 Py_DECREF(u);
9241 assert(_PyUnicode_CheckConsistency(v, 1));
9242 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243}
9244
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009245static PyObject *
9246ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009248 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9249 char *resdata, *data = PyUnicode_DATA(self);
9250 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009251
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009252 res = PyUnicode_New(len, 127);
9253 if (res == NULL)
9254 return NULL;
9255 resdata = PyUnicode_DATA(res);
9256 if (lower)
9257 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009259 _Py_bytes_upper(resdata, data, len);
9260 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261}
9262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009264handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009266 Py_ssize_t j;
9267 int final_sigma;
9268 Py_UCS4 c;
9269 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009270
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009271 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9272
9273 where ! is a negation and \p{xxx} is a character with property xxx.
9274 */
9275 for (j = i - 1; j >= 0; j--) {
9276 c = PyUnicode_READ(kind, data, j);
9277 if (!_PyUnicode_IsCaseIgnorable(c))
9278 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009280 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9281 if (final_sigma) {
9282 for (j = i + 1; j < length; j++) {
9283 c = PyUnicode_READ(kind, data, j);
9284 if (!_PyUnicode_IsCaseIgnorable(c))
9285 break;
9286 }
9287 final_sigma = j == length || !_PyUnicode_IsCased(c);
9288 }
9289 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290}
9291
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009292static int
9293lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9294 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009296 /* Obscure special case. */
9297 if (c == 0x3A3) {
9298 mapped[0] = handle_capital_sigma(kind, data, length, i);
9299 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009301 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009302}
9303
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009304static Py_ssize_t
9305do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009306{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009307 Py_ssize_t i, k = 0;
9308 int n_res, j;
9309 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009310
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009311 c = PyUnicode_READ(kind, data, 0);
9312 n_res = _PyUnicode_ToUpperFull(c, mapped);
9313 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009314 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009315 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009317 for (i = 1; i < length; i++) {
9318 c = PyUnicode_READ(kind, data, i);
9319 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9320 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009321 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009322 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009323 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009324 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009325 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009326}
9327
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009328static Py_ssize_t
9329do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9330 Py_ssize_t i, k = 0;
9331
9332 for (i = 0; i < length; i++) {
9333 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9334 int n_res, j;
9335 if (Py_UNICODE_ISUPPER(c)) {
9336 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9337 }
9338 else if (Py_UNICODE_ISLOWER(c)) {
9339 n_res = _PyUnicode_ToUpperFull(c, mapped);
9340 }
9341 else {
9342 n_res = 1;
9343 mapped[0] = c;
9344 }
9345 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009346 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009347 res[k++] = mapped[j];
9348 }
9349 }
9350 return k;
9351}
9352
9353static Py_ssize_t
9354do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9355 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009357 Py_ssize_t i, k = 0;
9358
9359 for (i = 0; i < length; i++) {
9360 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9361 int n_res, j;
9362 if (lower)
9363 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9364 else
9365 n_res = _PyUnicode_ToUpperFull(c, mapped);
9366 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009367 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009368 res[k++] = mapped[j];
9369 }
9370 }
9371 return k;
9372}
9373
9374static Py_ssize_t
9375do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9376{
9377 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9378}
9379
9380static Py_ssize_t
9381do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9382{
9383 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9384}
9385
Benjamin Petersone51757f2012-01-12 21:10:29 -05009386static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009387do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9388{
9389 Py_ssize_t i, k = 0;
9390
9391 for (i = 0; i < length; i++) {
9392 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9393 Py_UCS4 mapped[3];
9394 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9395 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009396 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009397 res[k++] = mapped[j];
9398 }
9399 }
9400 return k;
9401}
9402
9403static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009404do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9405{
9406 Py_ssize_t i, k = 0;
9407 int previous_is_cased;
9408
9409 previous_is_cased = 0;
9410 for (i = 0; i < length; i++) {
9411 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9412 Py_UCS4 mapped[3];
9413 int n_res, j;
9414
9415 if (previous_is_cased)
9416 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9417 else
9418 n_res = _PyUnicode_ToTitleFull(c, mapped);
9419
9420 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009421 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009422 res[k++] = mapped[j];
9423 }
9424
9425 previous_is_cased = _PyUnicode_IsCased(c);
9426 }
9427 return k;
9428}
9429
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009430static PyObject *
9431case_operation(PyObject *self,
9432 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9433{
9434 PyObject *res = NULL;
9435 Py_ssize_t length, newlength = 0;
9436 int kind, outkind;
9437 void *data, *outdata;
9438 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9439
Benjamin Petersoneea48462012-01-16 14:28:50 -05009440 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009441
9442 kind = PyUnicode_KIND(self);
9443 data = PyUnicode_DATA(self);
9444 length = PyUnicode_GET_LENGTH(self);
9445 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9446 if (tmp == NULL)
9447 return PyErr_NoMemory();
9448 newlength = perform(kind, data, length, tmp, &maxchar);
9449 res = PyUnicode_New(newlength, maxchar);
9450 if (res == NULL)
9451 goto leave;
9452 tmpend = tmp + newlength;
9453 outdata = PyUnicode_DATA(res);
9454 outkind = PyUnicode_KIND(res);
9455 switch (outkind) {
9456 case PyUnicode_1BYTE_KIND:
9457 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9458 break;
9459 case PyUnicode_2BYTE_KIND:
9460 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9461 break;
9462 case PyUnicode_4BYTE_KIND:
9463 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9464 break;
9465 default:
9466 assert(0);
9467 break;
9468 }
9469 leave:
9470 PyMem_FREE(tmp);
9471 return res;
9472}
9473
Tim Peters8ce9f162004-08-27 01:49:32 +00009474PyObject *
9475PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009478 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009480 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009481 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9482 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009483 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009485 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009487 int use_memcpy;
9488 unsigned char *res_data = NULL, *sep_data = NULL;
9489 PyObject *last_obj;
9490 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491
Tim Peters05eba1f2004-08-27 21:32:02 +00009492 fseq = PySequence_Fast(seq, "");
9493 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009494 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009495 }
9496
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009497 /* NOTE: the following code can't call back into Python code,
9498 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009499 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009500
Tim Peters05eba1f2004-08-27 21:32:02 +00009501 seqlen = PySequence_Fast_GET_SIZE(fseq);
9502 /* If empty sequence, return u"". */
9503 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009504 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009505 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009506 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009507
Tim Peters05eba1f2004-08-27 21:32:02 +00009508 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009509 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009510 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009511 if (seqlen == 1) {
9512 if (PyUnicode_CheckExact(items[0])) {
9513 res = items[0];
9514 Py_INCREF(res);
9515 Py_DECREF(fseq);
9516 return res;
9517 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009518 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009519 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009520 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009521 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009522 /* Set up sep and seplen */
9523 if (separator == NULL) {
9524 /* fall back to a blank space separator */
9525 sep = PyUnicode_FromOrdinal(' ');
9526 if (!sep)
9527 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009528 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009529 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009530 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009531 else {
9532 if (!PyUnicode_Check(separator)) {
9533 PyErr_Format(PyExc_TypeError,
9534 "separator: expected str instance,"
9535 " %.80s found",
9536 Py_TYPE(separator)->tp_name);
9537 goto onError;
9538 }
9539 if (PyUnicode_READY(separator))
9540 goto onError;
9541 sep = separator;
9542 seplen = PyUnicode_GET_LENGTH(separator);
9543 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9544 /* inc refcount to keep this code path symmetric with the
9545 above case of a blank separator */
9546 Py_INCREF(sep);
9547 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009548 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009549 }
9550
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009551 /* There are at least two things to join, or else we have a subclass
9552 * of str in the sequence.
9553 * Do a pre-pass to figure out the total amount of space we'll
9554 * need (sz), and see whether all argument are strings.
9555 */
9556 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009557#ifdef Py_DEBUG
9558 use_memcpy = 0;
9559#else
9560 use_memcpy = 1;
9561#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009562 for (i = 0; i < seqlen; i++) {
9563 const Py_ssize_t old_sz = sz;
9564 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009565 if (!PyUnicode_Check(item)) {
9566 PyErr_Format(PyExc_TypeError,
9567 "sequence item %zd: expected str instance,"
9568 " %.80s found",
9569 i, Py_TYPE(item)->tp_name);
9570 goto onError;
9571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 if (PyUnicode_READY(item) == -1)
9573 goto onError;
9574 sz += PyUnicode_GET_LENGTH(item);
9575 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009576 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009577 if (i != 0)
9578 sz += seplen;
9579 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9580 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009581 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009582 goto onError;
9583 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009584 if (use_memcpy && last_obj != NULL) {
9585 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9586 use_memcpy = 0;
9587 }
9588 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009589 }
Tim Petersced69f82003-09-16 20:30:58 +00009590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009592 if (res == NULL)
9593 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009594
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009595 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009596#ifdef Py_DEBUG
9597 use_memcpy = 0;
9598#else
9599 if (use_memcpy) {
9600 res_data = PyUnicode_1BYTE_DATA(res);
9601 kind = PyUnicode_KIND(res);
9602 if (seplen != 0)
9603 sep_data = PyUnicode_1BYTE_DATA(sep);
9604 }
9605#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009606 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009607 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009608 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009609 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009610 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009611 if (use_memcpy) {
9612 Py_MEMCPY(res_data,
9613 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009614 kind * seplen);
9615 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009616 }
9617 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009618 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 res_offset += seplen;
9620 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009621 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009622 itemlen = PyUnicode_GET_LENGTH(item);
9623 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009624 if (use_memcpy) {
9625 Py_MEMCPY(res_data,
9626 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009627 kind * itemlen);
9628 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009629 }
9630 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009631 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009632 res_offset += itemlen;
9633 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009634 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009635 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009636 if (use_memcpy)
9637 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009638 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009639 else
9640 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009641
Tim Peters05eba1f2004-08-27 21:32:02 +00009642 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009643 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009644 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646
Benjamin Peterson29060642009-01-31 22:14:21 +00009647 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009648 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009650 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009651 return NULL;
9652}
9653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654#define FILL(kind, data, value, start, length) \
9655 do { \
9656 Py_ssize_t i_ = 0; \
9657 assert(kind != PyUnicode_WCHAR_KIND); \
9658 switch ((kind)) { \
9659 case PyUnicode_1BYTE_KIND: { \
9660 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009661 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 break; \
9663 } \
9664 case PyUnicode_2BYTE_KIND: { \
9665 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9666 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9667 break; \
9668 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009669 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9671 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9672 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009673 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009674 } \
9675 } \
9676 } while (0)
9677
Victor Stinnerd3f08822012-05-29 12:57:52 +02009678void
9679_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9680 Py_UCS4 fill_char)
9681{
9682 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9683 const void *data = PyUnicode_DATA(unicode);
9684 assert(PyUnicode_IS_READY(unicode));
9685 assert(unicode_modifiable(unicode));
9686 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9687 assert(start >= 0);
9688 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9689 FILL(kind, data, fill_char, start, length);
9690}
9691
Victor Stinner3fe55312012-01-04 00:33:50 +01009692Py_ssize_t
9693PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9694 Py_UCS4 fill_char)
9695{
9696 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009697
9698 if (!PyUnicode_Check(unicode)) {
9699 PyErr_BadInternalCall();
9700 return -1;
9701 }
9702 if (PyUnicode_READY(unicode) == -1)
9703 return -1;
9704 if (unicode_check_modifiable(unicode))
9705 return -1;
9706
Victor Stinnerd3f08822012-05-29 12:57:52 +02009707 if (start < 0) {
9708 PyErr_SetString(PyExc_IndexError, "string index out of range");
9709 return -1;
9710 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009711 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9712 PyErr_SetString(PyExc_ValueError,
9713 "fill character is bigger than "
9714 "the string maximum character");
9715 return -1;
9716 }
9717
9718 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9719 length = Py_MIN(maxlen, length);
9720 if (length <= 0)
9721 return 0;
9722
Victor Stinnerd3f08822012-05-29 12:57:52 +02009723 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009724 return length;
9725}
9726
Victor Stinner9310abb2011-10-05 00:59:23 +02009727static PyObject *
9728pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009729 Py_ssize_t left,
9730 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009732{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 PyObject *u;
9734 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009735 int kind;
9736 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009737
9738 if (left < 0)
9739 left = 0;
9740 if (right < 0)
9741 right = 0;
9742
Victor Stinnerc4b49542011-12-11 22:44:26 +01009743 if (left == 0 && right == 0)
9744 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009746 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9747 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009748 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9749 return NULL;
9750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009752 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009754 if (!u)
9755 return NULL;
9756
9757 kind = PyUnicode_KIND(u);
9758 data = PyUnicode_DATA(u);
9759 if (left)
9760 FILL(kind, data, fill, 0, left);
9761 if (right)
9762 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009763 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009764 assert(_PyUnicode_CheckConsistency(u, 1));
9765 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009766}
9767
Alexander Belopolsky40018472011-02-26 01:02:56 +00009768PyObject *
9769PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009771 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772
9773 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009774 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009775 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009776 if (PyUnicode_READY(string) == -1) {
9777 Py_DECREF(string);
9778 return NULL;
9779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780
Benjamin Petersonead6b532011-12-20 17:23:42 -06009781 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009782 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009783 if (PyUnicode_IS_ASCII(string))
9784 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009785 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009786 PyUnicode_GET_LENGTH(string), keepends);
9787 else
9788 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009789 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009790 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009791 break;
9792 case PyUnicode_2BYTE_KIND:
9793 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009794 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009795 PyUnicode_GET_LENGTH(string), keepends);
9796 break;
9797 case PyUnicode_4BYTE_KIND:
9798 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009799 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 PyUnicode_GET_LENGTH(string), keepends);
9801 break;
9802 default:
9803 assert(0);
9804 list = 0;
9805 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806 Py_DECREF(string);
9807 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808}
9809
Alexander Belopolsky40018472011-02-26 01:02:56 +00009810static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009811split(PyObject *self,
9812 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009813 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009814{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 int kind1, kind2, kind;
9816 void *buf1, *buf2;
9817 Py_ssize_t len1, len2;
9818 PyObject* out;
9819
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009821 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009823 if (PyUnicode_READY(self) == -1)
9824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009827 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009829 if (PyUnicode_IS_ASCII(self))
9830 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009831 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009832 PyUnicode_GET_LENGTH(self), maxcount
9833 );
9834 else
9835 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009836 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009837 PyUnicode_GET_LENGTH(self), maxcount
9838 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009839 case PyUnicode_2BYTE_KIND:
9840 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009841 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009842 PyUnicode_GET_LENGTH(self), maxcount
9843 );
9844 case PyUnicode_4BYTE_KIND:
9845 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009846 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 PyUnicode_GET_LENGTH(self), maxcount
9848 );
9849 default:
9850 assert(0);
9851 return NULL;
9852 }
9853
9854 if (PyUnicode_READY(substring) == -1)
9855 return NULL;
9856
9857 kind1 = PyUnicode_KIND(self);
9858 kind2 = PyUnicode_KIND(substring);
9859 kind = kind1 > kind2 ? kind1 : kind2;
9860 buf1 = PyUnicode_DATA(self);
9861 buf2 = PyUnicode_DATA(substring);
9862 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009863 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 if (!buf1)
9865 return NULL;
9866 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009867 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 if (!buf2) {
9869 if (kind1 != kind) PyMem_Free(buf1);
9870 return NULL;
9871 }
9872 len1 = PyUnicode_GET_LENGTH(self);
9873 len2 = PyUnicode_GET_LENGTH(substring);
9874
Benjamin Petersonead6b532011-12-20 17:23:42 -06009875 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009877 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9878 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009879 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009880 else
9881 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009882 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 break;
9884 case PyUnicode_2BYTE_KIND:
9885 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009886 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009887 break;
9888 case PyUnicode_4BYTE_KIND:
9889 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009890 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 break;
9892 default:
9893 out = NULL;
9894 }
9895 if (kind1 != kind)
9896 PyMem_Free(buf1);
9897 if (kind2 != kind)
9898 PyMem_Free(buf2);
9899 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009900}
9901
Alexander Belopolsky40018472011-02-26 01:02:56 +00009902static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009903rsplit(PyObject *self,
9904 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009905 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009906{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 int kind1, kind2, kind;
9908 void *buf1, *buf2;
9909 Py_ssize_t len1, len2;
9910 PyObject* out;
9911
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009912 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009913 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 if (PyUnicode_READY(self) == -1)
9916 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009919 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009921 if (PyUnicode_IS_ASCII(self))
9922 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009924 PyUnicode_GET_LENGTH(self), maxcount
9925 );
9926 else
9927 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009928 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009929 PyUnicode_GET_LENGTH(self), maxcount
9930 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 case PyUnicode_2BYTE_KIND:
9932 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009933 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 PyUnicode_GET_LENGTH(self), maxcount
9935 );
9936 case PyUnicode_4BYTE_KIND:
9937 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009938 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 PyUnicode_GET_LENGTH(self), maxcount
9940 );
9941 default:
9942 assert(0);
9943 return NULL;
9944 }
9945
9946 if (PyUnicode_READY(substring) == -1)
9947 return NULL;
9948
9949 kind1 = PyUnicode_KIND(self);
9950 kind2 = PyUnicode_KIND(substring);
9951 kind = kind1 > kind2 ? kind1 : kind2;
9952 buf1 = PyUnicode_DATA(self);
9953 buf2 = PyUnicode_DATA(substring);
9954 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009955 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009956 if (!buf1)
9957 return NULL;
9958 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009959 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009960 if (!buf2) {
9961 if (kind1 != kind) PyMem_Free(buf1);
9962 return NULL;
9963 }
9964 len1 = PyUnicode_GET_LENGTH(self);
9965 len2 = PyUnicode_GET_LENGTH(substring);
9966
Benjamin Petersonead6b532011-12-20 17:23:42 -06009967 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009969 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9970 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009971 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009972 else
9973 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009974 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009975 break;
9976 case PyUnicode_2BYTE_KIND:
9977 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009978 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979 break;
9980 case PyUnicode_4BYTE_KIND:
9981 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009982 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 break;
9984 default:
9985 out = NULL;
9986 }
9987 if (kind1 != kind)
9988 PyMem_Free(buf1);
9989 if (kind2 != kind)
9990 PyMem_Free(buf2);
9991 return out;
9992}
9993
9994static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009995anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9996 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009998 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010000 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10001 return asciilib_find(buf1, len1, buf2, len2, offset);
10002 else
10003 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 case PyUnicode_2BYTE_KIND:
10005 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10006 case PyUnicode_4BYTE_KIND:
10007 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10008 }
10009 assert(0);
10010 return -1;
10011}
10012
10013static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010014anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10015 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010017 switch (kind) {
10018 case PyUnicode_1BYTE_KIND:
10019 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10020 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10021 else
10022 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10023 case PyUnicode_2BYTE_KIND:
10024 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10025 case PyUnicode_4BYTE_KIND:
10026 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10027 }
10028 assert(0);
10029 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010030}
10031
Alexander Belopolsky40018472011-02-26 01:02:56 +000010032static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033replace(PyObject *self, PyObject *str1,
10034 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010035{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 PyObject *u;
10037 char *sbuf = PyUnicode_DATA(self);
10038 char *buf1 = PyUnicode_DATA(str1);
10039 char *buf2 = PyUnicode_DATA(str2);
10040 int srelease = 0, release1 = 0, release2 = 0;
10041 int skind = PyUnicode_KIND(self);
10042 int kind1 = PyUnicode_KIND(str1);
10043 int kind2 = PyUnicode_KIND(str2);
10044 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10045 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10046 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010047 int mayshrink;
10048 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049
10050 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010051 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010053 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010054
Victor Stinner59de0ee2011-10-07 10:01:28 +020010055 if (str1 == str2)
10056 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 if (skind < kind1)
10058 /* substring too wide to be present */
10059 goto nothing;
10060
Victor Stinner49a0a212011-10-12 23:46:10 +020010061 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10062 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10063 /* Replacing str1 with str2 may cause a maxchar reduction in the
10064 result string. */
10065 mayshrink = (maxchar_str2 < maxchar);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010066 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010069 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010071 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010073 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010074 Py_UCS4 u1, u2;
10075 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010076 Py_ssize_t index, pos;
10077 char *src;
10078
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010080 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10081 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010082 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010085 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010087 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010089
10090 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10091 index = 0;
10092 src = sbuf;
10093 while (--maxcount)
10094 {
10095 pos++;
10096 src += pos * PyUnicode_KIND(self);
10097 slen -= pos;
10098 index += pos;
10099 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10100 if (pos < 0)
10101 break;
10102 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10103 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010104 }
10105 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 int rkind = skind;
10107 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010108 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 if (kind1 < rkind) {
10111 /* widen substring */
10112 buf1 = _PyUnicode_AsKind(str1, rkind);
10113 if (!buf1) goto error;
10114 release1 = 1;
10115 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010116 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010117 if (i < 0)
10118 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 if (rkind > kind2) {
10120 /* widen replacement */
10121 buf2 = _PyUnicode_AsKind(str2, rkind);
10122 if (!buf2) goto error;
10123 release2 = 1;
10124 }
10125 else if (rkind < kind2) {
10126 /* widen self and buf1 */
10127 rkind = kind2;
10128 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010129 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 sbuf = _PyUnicode_AsKind(self, rkind);
10131 if (!sbuf) goto error;
10132 srelease = 1;
10133 buf1 = _PyUnicode_AsKind(str1, rkind);
10134 if (!buf1) goto error;
10135 release1 = 1;
10136 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010137 u = PyUnicode_New(slen, maxchar);
10138 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010140 assert(PyUnicode_KIND(u) == rkind);
10141 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010142
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010143 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010144 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010145 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010147 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010149
10150 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010151 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010152 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010153 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010154 if (i == -1)
10155 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010156 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010158 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010160 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010161 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010162 }
10163 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010165 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 int rkind = skind;
10167 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010170 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 buf1 = _PyUnicode_AsKind(str1, rkind);
10172 if (!buf1) goto error;
10173 release1 = 1;
10174 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010175 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010176 if (n == 0)
10177 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010179 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 buf2 = _PyUnicode_AsKind(str2, rkind);
10181 if (!buf2) goto error;
10182 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010185 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 rkind = kind2;
10187 sbuf = _PyUnicode_AsKind(self, rkind);
10188 if (!sbuf) goto error;
10189 srelease = 1;
10190 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010191 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 buf1 = _PyUnicode_AsKind(str1, rkind);
10193 if (!buf1) goto error;
10194 release1 = 1;
10195 }
10196 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10197 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010198 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 PyErr_SetString(PyExc_OverflowError,
10200 "replace string is too long");
10201 goto error;
10202 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010203 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010204 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010205 _Py_INCREF_UNICODE_EMPTY();
10206 if (!unicode_empty)
10207 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010208 u = unicode_empty;
10209 goto done;
10210 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010211 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 PyErr_SetString(PyExc_OverflowError,
10213 "replace string is too long");
10214 goto error;
10215 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 u = PyUnicode_New(new_size, maxchar);
10217 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010219 assert(PyUnicode_KIND(u) == rkind);
10220 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 ires = i = 0;
10222 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 while (n-- > 0) {
10224 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010225 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010227 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010228 if (j == -1)
10229 break;
10230 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010231 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010232 memcpy(res + rkind * ires,
10233 sbuf + rkind * i,
10234 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010236 }
10237 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010239 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010241 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010247 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010248 memcpy(res + rkind * ires,
10249 sbuf + rkind * i,
10250 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010251 }
10252 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010253 /* interleave */
10254 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010255 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010257 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010259 if (--n <= 0)
10260 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010261 memcpy(res + rkind * ires,
10262 sbuf + rkind * i,
10263 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 ires++;
10265 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010266 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010267 memcpy(res + rkind * ires,
10268 sbuf + rkind * i,
10269 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010270 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010271 }
10272
10273 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010274 unicode_adjust_maxchar(&u);
10275 if (u == NULL)
10276 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010277 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010278
10279 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 if (srelease)
10281 PyMem_FREE(sbuf);
10282 if (release1)
10283 PyMem_FREE(buf1);
10284 if (release2)
10285 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010286 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288
Benjamin Peterson29060642009-01-31 22:14:21 +000010289 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010290 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 if (srelease)
10292 PyMem_FREE(sbuf);
10293 if (release1)
10294 PyMem_FREE(buf1);
10295 if (release2)
10296 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010297 return unicode_result_unchanged(self);
10298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 error:
10300 if (srelease && sbuf)
10301 PyMem_FREE(sbuf);
10302 if (release1 && buf1)
10303 PyMem_FREE(buf1);
10304 if (release2 && buf2)
10305 PyMem_FREE(buf2);
10306 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307}
10308
10309/* --- Unicode Object Methods --------------------------------------------- */
10310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010311PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010312 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313\n\
10314Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010315characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316
10317static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010318unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010319{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010320 if (PyUnicode_READY(self) == -1)
10321 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010322 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010323}
10324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010325PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010326 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327\n\
10328Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010329have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330
10331static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010332unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010333{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010334 if (PyUnicode_READY(self) == -1)
10335 return NULL;
10336 if (PyUnicode_GET_LENGTH(self) == 0)
10337 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010338 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010339}
10340
Benjamin Petersond5890c82012-01-14 13:23:30 -050010341PyDoc_STRVAR(casefold__doc__,
10342 "S.casefold() -> str\n\
10343\n\
10344Return a version of S suitable for caseless comparisons.");
10345
10346static PyObject *
10347unicode_casefold(PyObject *self)
10348{
10349 if (PyUnicode_READY(self) == -1)
10350 return NULL;
10351 if (PyUnicode_IS_ASCII(self))
10352 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010353 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010354}
10355
10356
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010357/* Argument converter. Coerces to a single unicode character */
10358
10359static int
10360convert_uc(PyObject *obj, void *addr)
10361{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010363 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010364
Benjamin Peterson14339b62009-01-31 16:36:08 +000010365 uniobj = PyUnicode_FromObject(obj);
10366 if (uniobj == NULL) {
10367 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010368 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010369 return 0;
10370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010372 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010373 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010374 Py_DECREF(uniobj);
10375 return 0;
10376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010378 Py_DECREF(uniobj);
10379 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010380}
10381
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010382PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010383 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010385Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010386done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387
10388static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010389unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010390{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010391 Py_ssize_t marg, left;
10392 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 Py_UCS4 fillchar = ' ';
10394
Victor Stinnere9a29352011-10-01 02:14:59 +020010395 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397
Benjamin Petersonbac79492012-01-14 13:34:47 -050010398 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399 return NULL;
10400
Victor Stinnerc4b49542011-12-11 22:44:26 +010010401 if (PyUnicode_GET_LENGTH(self) >= width)
10402 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403
Victor Stinnerc4b49542011-12-11 22:44:26 +010010404 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010405 left = marg / 2 + (marg & width & 1);
10406
Victor Stinner9310abb2011-10-05 00:59:23 +020010407 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010408}
10409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410/* This function assumes that str1 and str2 are readied by the caller. */
10411
Marc-André Lemburge5034372000-08-08 08:04:29 +000010412static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010413unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010414{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 int kind1, kind2;
10416 void *data1, *data2;
10417 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 kind1 = PyUnicode_KIND(str1);
10420 kind2 = PyUnicode_KIND(str2);
10421 data1 = PyUnicode_DATA(str1);
10422 data2 = PyUnicode_DATA(str2);
10423 len1 = PyUnicode_GET_LENGTH(str1);
10424 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 for (i = 0; i < len1 && i < len2; ++i) {
10427 Py_UCS4 c1, c2;
10428 c1 = PyUnicode_READ(kind1, data1, i);
10429 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010430
10431 if (c1 != c2)
10432 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010433 }
10434
10435 return (len1 < len2) ? -1 : (len1 != len2);
10436}
10437
Alexander Belopolsky40018472011-02-26 01:02:56 +000010438int
10439PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010440{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10442 if (PyUnicode_READY(left) == -1 ||
10443 PyUnicode_READY(right) == -1)
10444 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010445 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010447 PyErr_Format(PyExc_TypeError,
10448 "Can't compare %.100s and %.100s",
10449 left->ob_type->tp_name,
10450 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451 return -1;
10452}
10453
Martin v. Löwis5b222132007-06-10 09:51:05 +000010454int
10455PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 Py_ssize_t i;
10458 int kind;
10459 void *data;
10460 Py_UCS4 chr;
10461
Victor Stinner910337b2011-10-03 03:20:16 +020010462 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 if (PyUnicode_READY(uni) == -1)
10464 return -1;
10465 kind = PyUnicode_KIND(uni);
10466 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010467 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10469 if (chr != str[i])
10470 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010471 /* This check keeps Python strings that end in '\0' from comparing equal
10472 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010474 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010475 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010476 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010477 return 0;
10478}
10479
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010480
Benjamin Peterson29060642009-01-31 22:14:21 +000010481#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010482 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010483
Alexander Belopolsky40018472011-02-26 01:02:56 +000010484PyObject *
10485PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010486{
10487 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010488
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010489 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10490 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 if (PyUnicode_READY(left) == -1 ||
10492 PyUnicode_READY(right) == -1)
10493 return NULL;
10494 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10495 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010496 if (op == Py_EQ) {
10497 Py_INCREF(Py_False);
10498 return Py_False;
10499 }
10500 if (op == Py_NE) {
10501 Py_INCREF(Py_True);
10502 return Py_True;
10503 }
10504 }
10505 if (left == right)
10506 result = 0;
10507 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010508 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010509
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010510 /* Convert the return value to a Boolean */
10511 switch (op) {
10512 case Py_EQ:
10513 v = TEST_COND(result == 0);
10514 break;
10515 case Py_NE:
10516 v = TEST_COND(result != 0);
10517 break;
10518 case Py_LE:
10519 v = TEST_COND(result <= 0);
10520 break;
10521 case Py_GE:
10522 v = TEST_COND(result >= 0);
10523 break;
10524 case Py_LT:
10525 v = TEST_COND(result == -1);
10526 break;
10527 case Py_GT:
10528 v = TEST_COND(result == 1);
10529 break;
10530 default:
10531 PyErr_BadArgument();
10532 return NULL;
10533 }
10534 Py_INCREF(v);
10535 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010536 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010537
Brian Curtindfc80e32011-08-10 20:28:54 -050010538 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010539}
10540
Alexander Belopolsky40018472011-02-26 01:02:56 +000010541int
10542PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010543{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010544 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010545 int kind1, kind2, kind;
10546 void *buf1, *buf2;
10547 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010548 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010549
10550 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010551 sub = PyUnicode_FromObject(element);
10552 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010553 PyErr_Format(PyExc_TypeError,
10554 "'in <string>' requires string as left operand, not %s",
10555 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010556 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010557 }
10558
Thomas Wouters477c8d52006-05-27 19:21:47 +000010559 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010560 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010561 Py_DECREF(sub);
10562 return -1;
10563 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010564 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10565 Py_DECREF(sub);
10566 Py_DECREF(str);
10567 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 kind1 = PyUnicode_KIND(str);
10570 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010571 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 buf1 = PyUnicode_DATA(str);
10573 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010574 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010575 if (kind2 > kind) {
10576 Py_DECREF(sub);
10577 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010578 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010579 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010580 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 if (!buf2) {
10583 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010584 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 return -1;
10586 }
10587 len1 = PyUnicode_GET_LENGTH(str);
10588 len2 = PyUnicode_GET_LENGTH(sub);
10589
Benjamin Petersonead6b532011-12-20 17:23:42 -060010590 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 case PyUnicode_1BYTE_KIND:
10592 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10593 break;
10594 case PyUnicode_2BYTE_KIND:
10595 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10596 break;
10597 case PyUnicode_4BYTE_KIND:
10598 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10599 break;
10600 default:
10601 result = -1;
10602 assert(0);
10603 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604
10605 Py_DECREF(str);
10606 Py_DECREF(sub);
10607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 if (kind2 != kind)
10609 PyMem_Free(buf2);
10610
Guido van Rossum403d68b2000-03-13 15:55:09 +000010611 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010612}
10613
Guido van Rossumd57fd912000-03-10 22:53:23 +000010614/* Concat to string or Unicode object giving a new Unicode object. */
10615
Alexander Belopolsky40018472011-02-26 01:02:56 +000010616PyObject *
10617PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010620 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010621 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622
10623 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010626 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010629 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630
10631 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010632 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010633 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010636 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010637 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639 }
10640
Victor Stinner488fa492011-12-12 00:01:39 +010010641 u_len = PyUnicode_GET_LENGTH(u);
10642 v_len = PyUnicode_GET_LENGTH(v);
10643 if (u_len > PY_SSIZE_T_MAX - v_len) {
10644 PyErr_SetString(PyExc_OverflowError,
10645 "strings are too large to concat");
10646 goto onError;
10647 }
10648 new_len = u_len + v_len;
10649
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010651 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010652 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010655 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010657 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010658 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10659 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660 Py_DECREF(u);
10661 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010662 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664
Benjamin Peterson29060642009-01-31 22:14:21 +000010665 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010666 Py_XDECREF(u);
10667 Py_XDECREF(v);
10668 return NULL;
10669}
10670
Walter Dörwald1ab83302007-05-18 17:15:44 +000010671void
Victor Stinner23e56682011-10-03 03:54:37 +020010672PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010673{
Victor Stinner23e56682011-10-03 03:54:37 +020010674 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010675 Py_UCS4 maxchar, maxchar2;
10676 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010677
10678 if (p_left == NULL) {
10679 if (!PyErr_Occurred())
10680 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010681 return;
10682 }
Victor Stinner23e56682011-10-03 03:54:37 +020010683 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010684 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010685 if (!PyErr_Occurred())
10686 PyErr_BadInternalCall();
10687 goto error;
10688 }
10689
Benjamin Petersonbac79492012-01-14 13:34:47 -050010690 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010691 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010692 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010693 goto error;
10694
Victor Stinner488fa492011-12-12 00:01:39 +010010695 /* Shortcuts */
10696 if (left == unicode_empty) {
10697 Py_DECREF(left);
10698 Py_INCREF(right);
10699 *p_left = right;
10700 return;
10701 }
10702 if (right == unicode_empty)
10703 return;
10704
10705 left_len = PyUnicode_GET_LENGTH(left);
10706 right_len = PyUnicode_GET_LENGTH(right);
10707 if (left_len > PY_SSIZE_T_MAX - right_len) {
10708 PyErr_SetString(PyExc_OverflowError,
10709 "strings are too large to concat");
10710 goto error;
10711 }
10712 new_len = left_len + right_len;
10713
10714 if (unicode_modifiable(left)
10715 && PyUnicode_CheckExact(right)
10716 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010717 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10718 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010719 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010720 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010721 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10722 {
10723 /* append inplace */
10724 if (unicode_resize(p_left, new_len) != 0) {
10725 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10726 * deallocated so it cannot be put back into
10727 * 'variable'. The MemoryError is raised when there
10728 * is no value in 'variable', which might (very
10729 * remotely) be a cause of incompatibilities.
10730 */
10731 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010732 }
Victor Stinner488fa492011-12-12 00:01:39 +010010733 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010734 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010735 }
Victor Stinner488fa492011-12-12 00:01:39 +010010736 else {
10737 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10738 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010739 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010740
Victor Stinner488fa492011-12-12 00:01:39 +010010741 /* Concat the two Unicode strings */
10742 res = PyUnicode_New(new_len, maxchar);
10743 if (res == NULL)
10744 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010745 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10746 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010747 Py_DECREF(left);
10748 *p_left = res;
10749 }
10750 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010751 return;
10752
10753error:
Victor Stinner488fa492011-12-12 00:01:39 +010010754 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010755}
10756
10757void
10758PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10759{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010760 PyUnicode_Append(pleft, right);
10761 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010762}
10763
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010764PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010765 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010767Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010768string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010769interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770
10771static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010772unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010774 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010775 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010776 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010777 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778 int kind1, kind2, kind;
10779 void *buf1, *buf2;
10780 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781
Jesus Ceaac451502011-04-20 17:09:23 +020010782 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10783 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010784 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 kind1 = PyUnicode_KIND(self);
10787 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010788 if (kind2 > kind1)
10789 return PyLong_FromLong(0);
10790 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010791 buf1 = PyUnicode_DATA(self);
10792 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010794 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 if (!buf2) {
10796 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 return NULL;
10798 }
10799 len1 = PyUnicode_GET_LENGTH(self);
10800 len2 = PyUnicode_GET_LENGTH(substring);
10801
10802 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010803 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 case PyUnicode_1BYTE_KIND:
10805 iresult = ucs1lib_count(
10806 ((Py_UCS1*)buf1) + start, end - start,
10807 buf2, len2, PY_SSIZE_T_MAX
10808 );
10809 break;
10810 case PyUnicode_2BYTE_KIND:
10811 iresult = ucs2lib_count(
10812 ((Py_UCS2*)buf1) + start, end - start,
10813 buf2, len2, PY_SSIZE_T_MAX
10814 );
10815 break;
10816 case PyUnicode_4BYTE_KIND:
10817 iresult = ucs4lib_count(
10818 ((Py_UCS4*)buf1) + start, end - start,
10819 buf2, len2, PY_SSIZE_T_MAX
10820 );
10821 break;
10822 default:
10823 assert(0); iresult = 0;
10824 }
10825
10826 result = PyLong_FromSsize_t(iresult);
10827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010828 if (kind2 != kind)
10829 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830
10831 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010832
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833 return result;
10834}
10835
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010836PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010837 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010839Encode S using the codec registered for encoding. Default encoding\n\
10840is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010841handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010842a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10843'xmlcharrefreplace' as well as any other name registered with\n\
10844codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845
10846static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010847unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010848{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010849 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850 char *encoding = NULL;
10851 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010852
Benjamin Peterson308d6372009-09-18 21:42:35 +000010853 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10854 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010856 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010857}
10858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010859PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010860 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861\n\
10862Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010863If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864
10865static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010866unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010868 Py_ssize_t i, j, line_pos, src_len, incr;
10869 Py_UCS4 ch;
10870 PyObject *u;
10871 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010873 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010874 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875
10876 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010877 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878
Antoine Pitrou22425222011-10-04 19:10:51 +020010879 if (PyUnicode_READY(self) == -1)
10880 return NULL;
10881
Thomas Wouters7e474022000-07-16 12:04:32 +000010882 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010883 src_len = PyUnicode_GET_LENGTH(self);
10884 i = j = line_pos = 0;
10885 kind = PyUnicode_KIND(self);
10886 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010887 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010888 for (; i < src_len; i++) {
10889 ch = PyUnicode_READ(kind, src_data, i);
10890 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010891 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010892 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010893 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010895 goto overflow;
10896 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010897 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010898 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010899 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010901 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010902 goto overflow;
10903 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010905 if (ch == '\n' || ch == '\r')
10906 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010908 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010909 if (!found)
10910 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010911
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010913 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914 if (!u)
10915 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917
Antoine Pitroue71d5742011-10-04 15:55:09 +020010918 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919
Antoine Pitroue71d5742011-10-04 15:55:09 +020010920 for (; i < src_len; i++) {
10921 ch = PyUnicode_READ(kind, src_data, i);
10922 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010923 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010924 incr = tabsize - (line_pos % tabsize);
10925 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010926 FILL(kind, dest_data, ' ', j, incr);
10927 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010928 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010929 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 line_pos++;
10932 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010933 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 if (ch == '\n' || ch == '\r')
10935 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010937 }
10938 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010939 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010940
Antoine Pitroue71d5742011-10-04 15:55:09 +020010941 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010942 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10943 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944}
10945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010946PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010947 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948\n\
10949Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010950such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951arguments start and end are interpreted as in slice notation.\n\
10952\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010953Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954
10955static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010956unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010958 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010959 Py_ssize_t start;
10960 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010961 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962
Jesus Ceaac451502011-04-20 17:09:23 +020010963 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10964 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010966
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010967 if (PyUnicode_READY(self) == -1)
10968 return NULL;
10969 if (PyUnicode_READY(substring) == -1)
10970 return NULL;
10971
Victor Stinner7931d9a2011-11-04 00:22:48 +010010972 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973
10974 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976 if (result == -2)
10977 return NULL;
10978
Christian Heimes217cfd12007-12-02 14:31:20 +000010979 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980}
10981
10982static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010983unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010985 void *data;
10986 enum PyUnicode_Kind kind;
10987 Py_UCS4 ch;
10988 PyObject *res;
10989
10990 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10991 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010992 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010993 }
10994 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10995 PyErr_SetString(PyExc_IndexError, "string index out of range");
10996 return NULL;
10997 }
10998 kind = PyUnicode_KIND(self);
10999 data = PyUnicode_DATA(self);
11000 ch = PyUnicode_READ(kind, data, index);
11001 if (ch < 256)
11002 return get_latin1_char(ch);
11003
11004 res = PyUnicode_New(1, ch);
11005 if (res == NULL)
11006 return NULL;
11007 kind = PyUnicode_KIND(res);
11008 data = PyUnicode_DATA(res);
11009 PyUnicode_WRITE(kind, data, 0, ch);
11010 assert(_PyUnicode_CheckConsistency(res, 1));
11011 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012}
11013
Guido van Rossumc2504932007-09-18 19:42:40 +000011014/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011015 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011016static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011017unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018{
Guido van Rossumc2504932007-09-18 19:42:40 +000011019 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011020 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011021
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011022#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011023 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011024#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011025 if (_PyUnicode_HASH(self) != -1)
11026 return _PyUnicode_HASH(self);
11027 if (PyUnicode_READY(self) == -1)
11028 return -1;
11029 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011030 /*
11031 We make the hash of the empty string be 0, rather than using
11032 (prefix ^ suffix), since this slightly obfuscates the hash secret
11033 */
11034 if (len == 0) {
11035 _PyUnicode_HASH(self) = 0;
11036 return 0;
11037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011038
11039 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011040#define HASH(P) \
11041 x ^= (Py_uhash_t) *P << 7; \
11042 while (--len >= 0) \
11043 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011044
Georg Brandl2fb477c2012-02-21 00:33:36 +010011045 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046 switch (PyUnicode_KIND(self)) {
11047 case PyUnicode_1BYTE_KIND: {
11048 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11049 HASH(c);
11050 break;
11051 }
11052 case PyUnicode_2BYTE_KIND: {
11053 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11054 HASH(s);
11055 break;
11056 }
11057 default: {
11058 Py_UCS4 *l;
11059 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11060 "Impossible switch case in unicode_hash");
11061 l = PyUnicode_4BYTE_DATA(self);
11062 HASH(l);
11063 break;
11064 }
11065 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011066 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11067 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068
Guido van Rossumc2504932007-09-18 19:42:40 +000011069 if (x == -1)
11070 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011072 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011076PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011077 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011079Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080
11081static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011084 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011085 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011086 Py_ssize_t start;
11087 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
Jesus Ceaac451502011-04-20 17:09:23 +020011089 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11090 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011093 if (PyUnicode_READY(self) == -1)
11094 return NULL;
11095 if (PyUnicode_READY(substring) == -1)
11096 return NULL;
11097
Victor Stinner7931d9a2011-11-04 00:22:48 +010011098 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099
11100 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011102 if (result == -2)
11103 return NULL;
11104
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105 if (result < 0) {
11106 PyErr_SetString(PyExc_ValueError, "substring not found");
11107 return NULL;
11108 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011109
Christian Heimes217cfd12007-12-02 14:31:20 +000011110 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111}
11112
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011113PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011114 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011116Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011117at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118
11119static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011120unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122 Py_ssize_t i, length;
11123 int kind;
11124 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125 int cased;
11126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 if (PyUnicode_READY(self) == -1)
11128 return NULL;
11129 length = PyUnicode_GET_LENGTH(self);
11130 kind = PyUnicode_KIND(self);
11131 data = PyUnicode_DATA(self);
11132
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 if (length == 1)
11135 return PyBool_FromLong(
11136 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011138 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011140 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011141
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 for (i = 0; i < length; i++) {
11144 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011145
Benjamin Peterson29060642009-01-31 22:14:21 +000011146 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11147 return PyBool_FromLong(0);
11148 else if (!cased && Py_UNICODE_ISLOWER(ch))
11149 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011151 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011152}
11153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011154PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011155 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011157Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011158at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159
11160static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011161unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011163 Py_ssize_t i, length;
11164 int kind;
11165 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166 int cased;
11167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 if (PyUnicode_READY(self) == -1)
11169 return NULL;
11170 length = PyUnicode_GET_LENGTH(self);
11171 kind = PyUnicode_KIND(self);
11172 data = PyUnicode_DATA(self);
11173
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011175 if (length == 1)
11176 return PyBool_FromLong(
11177 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011179 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011180 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011181 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011182
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011184 for (i = 0; i < length; i++) {
11185 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011186
Benjamin Peterson29060642009-01-31 22:14:21 +000011187 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11188 return PyBool_FromLong(0);
11189 else if (!cased && Py_UNICODE_ISUPPER(ch))
11190 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011192 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193}
11194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011195PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011196 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011198Return True if S is a titlecased string and there is at least one\n\
11199character in S, i.e. upper- and titlecase characters may only\n\
11200follow uncased characters and lowercase characters only cased ones.\n\
11201Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011204unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206 Py_ssize_t i, length;
11207 int kind;
11208 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209 int cased, previous_is_cased;
11210
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011211 if (PyUnicode_READY(self) == -1)
11212 return NULL;
11213 length = PyUnicode_GET_LENGTH(self);
11214 kind = PyUnicode_KIND(self);
11215 data = PyUnicode_DATA(self);
11216
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218 if (length == 1) {
11219 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11220 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11221 (Py_UNICODE_ISUPPER(ch) != 0));
11222 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011224 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011227
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228 cased = 0;
11229 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 for (i = 0; i < length; i++) {
11231 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011232
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11234 if (previous_is_cased)
11235 return PyBool_FromLong(0);
11236 previous_is_cased = 1;
11237 cased = 1;
11238 }
11239 else if (Py_UNICODE_ISLOWER(ch)) {
11240 if (!previous_is_cased)
11241 return PyBool_FromLong(0);
11242 previous_is_cased = 1;
11243 cased = 1;
11244 }
11245 else
11246 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011248 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249}
11250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011251PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011252 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011254Return True if all characters in S are whitespace\n\
11255and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256
11257static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011258unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011260 Py_ssize_t i, length;
11261 int kind;
11262 void *data;
11263
11264 if (PyUnicode_READY(self) == -1)
11265 return NULL;
11266 length = PyUnicode_GET_LENGTH(self);
11267 kind = PyUnicode_KIND(self);
11268 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 if (length == 1)
11272 return PyBool_FromLong(
11273 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011275 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011278
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 for (i = 0; i < length; i++) {
11280 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011281 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011284 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285}
11286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011287PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011289\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011290Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011291and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011292
11293static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011294unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 Py_ssize_t i, length;
11297 int kind;
11298 void *data;
11299
11300 if (PyUnicode_READY(self) == -1)
11301 return NULL;
11302 length = PyUnicode_GET_LENGTH(self);
11303 kind = PyUnicode_KIND(self);
11304 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011305
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011306 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 if (length == 1)
11308 return PyBool_FromLong(
11309 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011310
11311 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011313 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 for (i = 0; i < length; i++) {
11316 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011319 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011320}
11321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011322PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011323 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011324\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011325Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011326and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327
11328static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011329unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011330{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 int kind;
11332 void *data;
11333 Py_ssize_t len, i;
11334
11335 if (PyUnicode_READY(self) == -1)
11336 return NULL;
11337
11338 kind = PyUnicode_KIND(self);
11339 data = PyUnicode_DATA(self);
11340 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011341
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011342 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 if (len == 1) {
11344 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11345 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11346 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011347
11348 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011350 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011351
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 for (i = 0; i < len; i++) {
11353 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011354 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011356 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011357 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011358}
11359
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011360PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011361 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011363Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011364False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365
11366static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011367unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 Py_ssize_t i, length;
11370 int kind;
11371 void *data;
11372
11373 if (PyUnicode_READY(self) == -1)
11374 return NULL;
11375 length = PyUnicode_GET_LENGTH(self);
11376 kind = PyUnicode_KIND(self);
11377 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 if (length == 1)
11381 return PyBool_FromLong(
11382 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011384 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011386 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388 for (i = 0; i < length; i++) {
11389 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011390 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011392 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393}
11394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011395PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011396 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011398Return True if all characters in S are digits\n\
11399and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
11401static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011402unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 Py_ssize_t i, length;
11405 int kind;
11406 void *data;
11407
11408 if (PyUnicode_READY(self) == -1)
11409 return NULL;
11410 length = PyUnicode_GET_LENGTH(self);
11411 kind = PyUnicode_KIND(self);
11412 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415 if (length == 1) {
11416 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11417 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11418 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 for (i = 0; i < length; i++) {
11425 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011428 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429}
11430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011431PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011434Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011435False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
11437static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011438unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 Py_ssize_t i, length;
11441 int kind;
11442 void *data;
11443
11444 if (PyUnicode_READY(self) == -1)
11445 return NULL;
11446 length = PyUnicode_GET_LENGTH(self);
11447 kind = PyUnicode_KIND(self);
11448 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 if (length == 1)
11452 return PyBool_FromLong(
11453 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011455 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011456 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 for (i = 0; i < length; i++) {
11460 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011463 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464}
11465
Martin v. Löwis47383402007-08-15 07:32:56 +000011466int
11467PyUnicode_IsIdentifier(PyObject *self)
11468{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 int kind;
11470 void *data;
11471 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011472 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 if (PyUnicode_READY(self) == -1) {
11475 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 }
11478
11479 /* Special case for empty strings */
11480 if (PyUnicode_GET_LENGTH(self) == 0)
11481 return 0;
11482 kind = PyUnicode_KIND(self);
11483 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011484
11485 /* PEP 3131 says that the first character must be in
11486 XID_Start and subsequent characters in XID_Continue,
11487 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011488 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011489 letters, digits, underscore). However, given the current
11490 definition of XID_Start and XID_Continue, it is sufficient
11491 to check just for these, except that _ must be allowed
11492 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011494 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011495 return 0;
11496
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011497 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011500 return 1;
11501}
11502
11503PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011504 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011505\n\
11506Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011507to the language definition.\n\
11508\n\
11509Use keyword.iskeyword() to test for reserved identifiers\n\
11510such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011511
11512static PyObject*
11513unicode_isidentifier(PyObject *self)
11514{
11515 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11516}
11517
Georg Brandl559e5d72008-06-11 18:37:52 +000011518PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011519 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011520\n\
11521Return True if all characters in S are considered\n\
11522printable in repr() or S is empty, False otherwise.");
11523
11524static PyObject*
11525unicode_isprintable(PyObject *self)
11526{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 Py_ssize_t i, length;
11528 int kind;
11529 void *data;
11530
11531 if (PyUnicode_READY(self) == -1)
11532 return NULL;
11533 length = PyUnicode_GET_LENGTH(self);
11534 kind = PyUnicode_KIND(self);
11535 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011536
11537 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 if (length == 1)
11539 return PyBool_FromLong(
11540 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 for (i = 0; i < length; i++) {
11543 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011544 Py_RETURN_FALSE;
11545 }
11546 }
11547 Py_RETURN_TRUE;
11548}
11549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011550PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011551 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552\n\
11553Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011554iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
11556static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011557unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011559 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560}
11561
Martin v. Löwis18e16552006-02-15 17:27:45 +000011562static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011563unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 if (PyUnicode_READY(self) == -1)
11566 return -1;
11567 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568}
11569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011570PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011571 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011573Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011574done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
11576static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011577unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011579 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 Py_UCS4 fillchar = ' ';
11581
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011582 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 return NULL;
11584
Benjamin Petersonbac79492012-01-14 13:34:47 -050011585 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011586 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587
Victor Stinnerc4b49542011-12-11 22:44:26 +010011588 if (PyUnicode_GET_LENGTH(self) >= width)
11589 return unicode_result_unchanged(self);
11590
11591 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592}
11593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011594PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011597Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598
11599static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011600unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011602 if (PyUnicode_READY(self) == -1)
11603 return NULL;
11604 if (PyUnicode_IS_ASCII(self))
11605 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011606 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607}
11608
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011609#define LEFTSTRIP 0
11610#define RIGHTSTRIP 1
11611#define BOTHSTRIP 2
11612
11613/* Arrays indexed by above */
11614static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11615
11616#define STRIPNAME(i) (stripformat[i]+3)
11617
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011618/* externally visible for str.strip(unicode) */
11619PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011620_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011621{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 void *data;
11623 int kind;
11624 Py_ssize_t i, j, len;
11625 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011627 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11628 return NULL;
11629
11630 kind = PyUnicode_KIND(self);
11631 data = PyUnicode_DATA(self);
11632 len = PyUnicode_GET_LENGTH(self);
11633 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11634 PyUnicode_DATA(sepobj),
11635 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011636
Benjamin Peterson14339b62009-01-31 16:36:08 +000011637 i = 0;
11638 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 while (i < len &&
11640 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011641 i++;
11642 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011643 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011644
Benjamin Peterson14339b62009-01-31 16:36:08 +000011645 j = len;
11646 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011647 do {
11648 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 } while (j >= i &&
11650 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011651 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011652 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011653
Victor Stinner7931d9a2011-11-04 00:22:48 +010011654 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655}
11656
11657PyObject*
11658PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11659{
11660 unsigned char *data;
11661 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011662 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663
Victor Stinnerde636f32011-10-01 03:55:54 +020011664 if (PyUnicode_READY(self) == -1)
11665 return NULL;
11666
Victor Stinner684d5fd2012-05-03 02:32:34 +020011667 length = PyUnicode_GET_LENGTH(self);
11668 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011669
Victor Stinner684d5fd2012-05-03 02:32:34 +020011670 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011671 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672
Victor Stinnerde636f32011-10-01 03:55:54 +020011673 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011674 PyErr_SetString(PyExc_IndexError, "string index out of range");
11675 return NULL;
11676 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011677 if (start >= length || end < start)
11678 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011679
Victor Stinner684d5fd2012-05-03 02:32:34 +020011680 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011681 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011682 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011683 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011684 }
11685 else {
11686 kind = PyUnicode_KIND(self);
11687 data = PyUnicode_1BYTE_DATA(self);
11688 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011689 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011690 length);
11691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693
11694static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011695do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 int kind;
11698 void *data;
11699 Py_ssize_t len, i, j;
11700
11701 if (PyUnicode_READY(self) == -1)
11702 return NULL;
11703
11704 kind = PyUnicode_KIND(self);
11705 data = PyUnicode_DATA(self);
11706 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011707
Benjamin Peterson14339b62009-01-31 16:36:08 +000011708 i = 0;
11709 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011711 i++;
11712 }
11713 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011714
Benjamin Peterson14339b62009-01-31 16:36:08 +000011715 j = len;
11716 if (striptype != LEFTSTRIP) {
11717 do {
11718 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011720 j++;
11721 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722
Victor Stinner7931d9a2011-11-04 00:22:48 +010011723 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724}
11725
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011726
11727static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011728do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011729{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011730 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011731
Benjamin Peterson14339b62009-01-31 16:36:08 +000011732 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11733 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011734
Benjamin Peterson14339b62009-01-31 16:36:08 +000011735 if (sep != NULL && sep != Py_None) {
11736 if (PyUnicode_Check(sep))
11737 return _PyUnicode_XStrip(self, striptype, sep);
11738 else {
11739 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011740 "%s arg must be None or str",
11741 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011742 return NULL;
11743 }
11744 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011745
Benjamin Peterson14339b62009-01-31 16:36:08 +000011746 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011747}
11748
11749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011750PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011751 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011752\n\
11753Return a copy of the string S with leading and trailing\n\
11754whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011755If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756
11757static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011758unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011760 if (PyTuple_GET_SIZE(args) == 0)
11761 return do_strip(self, BOTHSTRIP); /* Common case */
11762 else
11763 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011764}
11765
11766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011767PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011769\n\
11770Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011771If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011772
11773static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011774unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011776 if (PyTuple_GET_SIZE(args) == 0)
11777 return do_strip(self, LEFTSTRIP); /* Common case */
11778 else
11779 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011780}
11781
11782
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011783PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011784 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011785\n\
11786Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011787If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
11789static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011790unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011791{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011792 if (PyTuple_GET_SIZE(args) == 0)
11793 return do_strip(self, RIGHTSTRIP); /* Common case */
11794 else
11795 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796}
11797
11798
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011800unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011802 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804
Serhiy Storchaka05997252013-01-26 12:14:02 +020011805 if (len < 1)
11806 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807
Victor Stinnerc4b49542011-12-11 22:44:26 +010011808 /* no repeat, return original string */
11809 if (len == 1)
11810 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011811
Benjamin Petersonbac79492012-01-14 13:34:47 -050011812 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 return NULL;
11814
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011815 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011816 PyErr_SetString(PyExc_OverflowError,
11817 "repeated string is too long");
11818 return NULL;
11819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011821
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011822 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823 if (!u)
11824 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011825 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 if (PyUnicode_GET_LENGTH(str) == 1) {
11828 const int kind = PyUnicode_KIND(str);
11829 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011830 if (kind == PyUnicode_1BYTE_KIND) {
11831 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011832 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011833 }
11834 else if (kind == PyUnicode_2BYTE_KIND) {
11835 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011836 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011837 ucs2[n] = fill_char;
11838 } else {
11839 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11840 assert(kind == PyUnicode_4BYTE_KIND);
11841 for (n = 0; n < len; ++n)
11842 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011844 }
11845 else {
11846 /* number of characters copied this far */
11847 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011848 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011849 char *to = (char *) PyUnicode_DATA(u);
11850 Py_MEMCPY(to, PyUnicode_DATA(str),
11851 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011852 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011853 n = (done <= nchars-done) ? done : nchars-done;
11854 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011855 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011856 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857 }
11858
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011859 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011860 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861}
11862
Alexander Belopolsky40018472011-02-26 01:02:56 +000011863PyObject *
11864PyUnicode_Replace(PyObject *obj,
11865 PyObject *subobj,
11866 PyObject *replobj,
11867 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868{
11869 PyObject *self;
11870 PyObject *str1;
11871 PyObject *str2;
11872 PyObject *result;
11873
11874 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011875 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011878 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 Py_DECREF(self);
11880 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881 }
11882 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011883 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 Py_DECREF(self);
11885 Py_DECREF(str1);
11886 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011888 if (PyUnicode_READY(self) == -1 ||
11889 PyUnicode_READY(str1) == -1 ||
11890 PyUnicode_READY(str2) == -1)
11891 result = NULL;
11892 else
11893 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 Py_DECREF(self);
11895 Py_DECREF(str1);
11896 Py_DECREF(str2);
11897 return result;
11898}
11899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011900PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011901 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902\n\
11903Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011904old replaced by new. If the optional argument count is\n\
11905given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906
11907static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 PyObject *str1;
11911 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011912 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913 PyObject *result;
11914
Martin v. Löwis18e16552006-02-15 17:27:45 +000011915 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011917 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011918 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011920 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 return NULL;
11922 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011923 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011924 Py_DECREF(str1);
11925 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011926 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011927 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11928 result = NULL;
11929 else
11930 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931
11932 Py_DECREF(str1);
11933 Py_DECREF(str2);
11934 return result;
11935}
11936
Alexander Belopolsky40018472011-02-26 01:02:56 +000011937static PyObject *
11938unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011940 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 Py_ssize_t isize;
11942 Py_ssize_t osize, squote, dquote, i, o;
11943 Py_UCS4 max, quote;
11944 int ikind, okind;
11945 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011948 return NULL;
11949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 isize = PyUnicode_GET_LENGTH(unicode);
11951 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 /* Compute length of output, quote characters, and
11954 maximum character */
11955 osize = 2; /* quotes */
11956 max = 127;
11957 squote = dquote = 0;
11958 ikind = PyUnicode_KIND(unicode);
11959 for (i = 0; i < isize; i++) {
11960 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11961 switch (ch) {
11962 case '\'': squote++; osize++; break;
11963 case '"': dquote++; osize++; break;
11964 case '\\': case '\t': case '\r': case '\n':
11965 osize += 2; break;
11966 default:
11967 /* Fast-path ASCII */
11968 if (ch < ' ' || ch == 0x7f)
11969 osize += 4; /* \xHH */
11970 else if (ch < 0x7f)
11971 osize++;
11972 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11973 osize++;
11974 max = ch > max ? ch : max;
11975 }
11976 else if (ch < 0x100)
11977 osize += 4; /* \xHH */
11978 else if (ch < 0x10000)
11979 osize += 6; /* \uHHHH */
11980 else
11981 osize += 10; /* \uHHHHHHHH */
11982 }
11983 }
11984
11985 quote = '\'';
11986 if (squote) {
11987 if (dquote)
11988 /* Both squote and dquote present. Use squote,
11989 and escape them */
11990 osize += squote;
11991 else
11992 quote = '"';
11993 }
11994
11995 repr = PyUnicode_New(osize, max);
11996 if (repr == NULL)
11997 return NULL;
11998 okind = PyUnicode_KIND(repr);
11999 odata = PyUnicode_DATA(repr);
12000
12001 PyUnicode_WRITE(okind, odata, 0, quote);
12002 PyUnicode_WRITE(okind, odata, osize-1, quote);
12003
12004 for (i = 0, o = 1; i < isize; i++) {
12005 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012006
12007 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008 if ((ch == quote) || (ch == '\\')) {
12009 PyUnicode_WRITE(okind, odata, o++, '\\');
12010 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012011 continue;
12012 }
12013
Benjamin Peterson29060642009-01-31 22:14:21 +000012014 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012015 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 PyUnicode_WRITE(okind, odata, o++, '\\');
12017 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012018 }
12019 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 PyUnicode_WRITE(okind, odata, o++, '\\');
12021 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012022 }
12023 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 PyUnicode_WRITE(okind, odata, o++, '\\');
12025 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012026 }
12027
12028 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012029 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 PyUnicode_WRITE(okind, odata, o++, '\\');
12031 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012032 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12033 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012034 }
12035
Georg Brandl559e5d72008-06-11 18:37:52 +000012036 /* Copy ASCII characters as-is */
12037 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012039 }
12040
Benjamin Peterson29060642009-01-31 22:14:21 +000012041 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012042 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012043 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 (categories Z* and C* except ASCII space)
12045 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012047 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012048 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012051 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12052 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012053 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012054 /* Map 16-bit characters to '\uxxxx' */
12055 else if (ch <= 0xffff) {
12056 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12058 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12059 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12060 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012061 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012062 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012063 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012064 PyUnicode_WRITE(okind, odata, o++, 'U');
12065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012069 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12070 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12071 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12072 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012073 }
12074 }
12075 /* Copy characters as-is */
12076 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012078 }
12079 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012082 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012083 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084}
12085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012086PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012087 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012088\n\
12089Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012090such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091arguments start and end are interpreted as in slice notation.\n\
12092\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012093Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094
12095static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012097{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012098 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012099 Py_ssize_t start;
12100 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012101 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
Jesus Ceaac451502011-04-20 17:09:23 +020012103 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12104 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012105 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 if (PyUnicode_READY(self) == -1)
12108 return NULL;
12109 if (PyUnicode_READY(substring) == -1)
12110 return NULL;
12111
Victor Stinner7931d9a2011-11-04 00:22:48 +010012112 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
12114 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012115
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 if (result == -2)
12117 return NULL;
12118
Christian Heimes217cfd12007-12-02 14:31:20 +000012119 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120}
12121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012122PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012123 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012125Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126
12127static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012129{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012130 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012131 Py_ssize_t start;
12132 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012133 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134
Jesus Ceaac451502011-04-20 17:09:23 +020012135 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12136 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012137 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 if (PyUnicode_READY(self) == -1)
12140 return NULL;
12141 if (PyUnicode_READY(substring) == -1)
12142 return NULL;
12143
Victor Stinner7931d9a2011-11-04 00:22:48 +010012144 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
12146 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 if (result == -2)
12149 return NULL;
12150
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151 if (result < 0) {
12152 PyErr_SetString(PyExc_ValueError, "substring not found");
12153 return NULL;
12154 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155
Christian Heimes217cfd12007-12-02 14:31:20 +000012156 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157}
12158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012159PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012160 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012162Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012163done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164
12165static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012166unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012168 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 Py_UCS4 fillchar = ' ';
12170
Victor Stinnere9a29352011-10-01 02:14:59 +020012171 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012173
Benjamin Petersonbac79492012-01-14 13:34:47 -050012174 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175 return NULL;
12176
Victor Stinnerc4b49542011-12-11 22:44:26 +010012177 if (PyUnicode_GET_LENGTH(self) >= width)
12178 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
Victor Stinnerc4b49542011-12-11 22:44:26 +010012180 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181}
12182
Alexander Belopolsky40018472011-02-26 01:02:56 +000012183PyObject *
12184PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185{
12186 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012187
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188 s = PyUnicode_FromObject(s);
12189 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012190 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012191 if (sep != NULL) {
12192 sep = PyUnicode_FromObject(sep);
12193 if (sep == NULL) {
12194 Py_DECREF(s);
12195 return NULL;
12196 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197 }
12198
Victor Stinner9310abb2011-10-05 00:59:23 +020012199 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200
12201 Py_DECREF(s);
12202 Py_XDECREF(sep);
12203 return result;
12204}
12205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012206PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012207 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208\n\
12209Return a list of the words in S, using sep as the\n\
12210delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012211splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012212whitespace string is a separator and empty strings are\n\
12213removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214
12215static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012216unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012218 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012220 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012222 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12223 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224 return NULL;
12225
12226 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012227 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012229 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012231 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232}
12233
Thomas Wouters477c8d52006-05-27 19:21:47 +000012234PyObject *
12235PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12236{
12237 PyObject* str_obj;
12238 PyObject* sep_obj;
12239 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240 int kind1, kind2, kind;
12241 void *buf1 = NULL, *buf2 = NULL;
12242 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012243
12244 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012245 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012247 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012248 if (!sep_obj) {
12249 Py_DECREF(str_obj);
12250 return NULL;
12251 }
12252 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12253 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012254 Py_DECREF(str_obj);
12255 return NULL;
12256 }
12257
Victor Stinner14f8f022011-10-05 20:58:25 +020012258 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012260 kind = Py_MAX(kind1, kind2);
12261 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012263 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 if (!buf1)
12265 goto onError;
12266 buf2 = PyUnicode_DATA(sep_obj);
12267 if (kind2 != kind)
12268 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12269 if (!buf2)
12270 goto onError;
12271 len1 = PyUnicode_GET_LENGTH(str_obj);
12272 len2 = PyUnicode_GET_LENGTH(sep_obj);
12273
Benjamin Petersonead6b532011-12-20 17:23:42 -060012274 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012275 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012276 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12277 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12278 else
12279 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012280 break;
12281 case PyUnicode_2BYTE_KIND:
12282 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12283 break;
12284 case PyUnicode_4BYTE_KIND:
12285 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12286 break;
12287 default:
12288 assert(0);
12289 out = 0;
12290 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012291
12292 Py_DECREF(sep_obj);
12293 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 if (kind1 != kind)
12295 PyMem_Free(buf1);
12296 if (kind2 != kind)
12297 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012298
12299 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 onError:
12301 Py_DECREF(sep_obj);
12302 Py_DECREF(str_obj);
12303 if (kind1 != kind && buf1)
12304 PyMem_Free(buf1);
12305 if (kind2 != kind && buf2)
12306 PyMem_Free(buf2);
12307 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012308}
12309
12310
12311PyObject *
12312PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12313{
12314 PyObject* str_obj;
12315 PyObject* sep_obj;
12316 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 int kind1, kind2, kind;
12318 void *buf1 = NULL, *buf2 = NULL;
12319 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012320
12321 str_obj = PyUnicode_FromObject(str_in);
12322 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012323 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012324 sep_obj = PyUnicode_FromObject(sep_in);
12325 if (!sep_obj) {
12326 Py_DECREF(str_obj);
12327 return NULL;
12328 }
12329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 kind1 = PyUnicode_KIND(str_in);
12331 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012332 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 buf1 = PyUnicode_DATA(str_in);
12334 if (kind1 != kind)
12335 buf1 = _PyUnicode_AsKind(str_in, kind);
12336 if (!buf1)
12337 goto onError;
12338 buf2 = PyUnicode_DATA(sep_obj);
12339 if (kind2 != kind)
12340 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12341 if (!buf2)
12342 goto onError;
12343 len1 = PyUnicode_GET_LENGTH(str_obj);
12344 len2 = PyUnicode_GET_LENGTH(sep_obj);
12345
Benjamin Petersonead6b532011-12-20 17:23:42 -060012346 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012348 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12349 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12350 else
12351 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 break;
12353 case PyUnicode_2BYTE_KIND:
12354 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12355 break;
12356 case PyUnicode_4BYTE_KIND:
12357 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12358 break;
12359 default:
12360 assert(0);
12361 out = 0;
12362 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012363
12364 Py_DECREF(sep_obj);
12365 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 if (kind1 != kind)
12367 PyMem_Free(buf1);
12368 if (kind2 != kind)
12369 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012370
12371 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012372 onError:
12373 Py_DECREF(sep_obj);
12374 Py_DECREF(str_obj);
12375 if (kind1 != kind && buf1)
12376 PyMem_Free(buf1);
12377 if (kind2 != kind && buf2)
12378 PyMem_Free(buf2);
12379 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012380}
12381
12382PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012383 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012384\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012385Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012386the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012387found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012388
12389static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012390unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012391{
Victor Stinner9310abb2011-10-05 00:59:23 +020012392 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393}
12394
12395PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012396 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012397\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012398Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012400separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012401
12402static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012403unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404{
Victor Stinner9310abb2011-10-05 00:59:23 +020012405 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406}
12407
Alexander Belopolsky40018472011-02-26 01:02:56 +000012408PyObject *
12409PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012410{
12411 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012412
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012413 s = PyUnicode_FromObject(s);
12414 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012415 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012416 if (sep != NULL) {
12417 sep = PyUnicode_FromObject(sep);
12418 if (sep == NULL) {
12419 Py_DECREF(s);
12420 return NULL;
12421 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012422 }
12423
Victor Stinner9310abb2011-10-05 00:59:23 +020012424 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012425
12426 Py_DECREF(s);
12427 Py_XDECREF(sep);
12428 return result;
12429}
12430
12431PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012432 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012433\n\
12434Return a list of the words in S, using sep as the\n\
12435delimiter string, starting at the end of the string and\n\
12436working to the front. If maxsplit is given, at most maxsplit\n\
12437splits are done. If sep is not specified, any whitespace string\n\
12438is a separator.");
12439
12440static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012441unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012442{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012443 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012444 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012445 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012446
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012447 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12448 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012449 return NULL;
12450
12451 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012453 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012455 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012456 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012457}
12458
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012459PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012460 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461\n\
12462Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012463Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012464is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465
12466static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012467unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012468{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012469 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012470 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012471
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012472 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12473 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474 return NULL;
12475
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012476 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477}
12478
12479static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012480PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012482 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483}
12484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012485PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012486 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012487\n\
12488Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012489and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490
12491static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012492unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012494 if (PyUnicode_READY(self) == -1)
12495 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012496 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012497}
12498
Georg Brandlceee0772007-11-27 23:48:05 +000012499PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012500 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012501\n\
12502Return a translation table usable for str.translate().\n\
12503If there is only one argument, it must be a dictionary mapping Unicode\n\
12504ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012505Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012506If there are two arguments, they must be strings of equal length, and\n\
12507in the resulting dictionary, each character in x will be mapped to the\n\
12508character at the same position in y. If there is a third argument, it\n\
12509must be a string, whose characters will be mapped to None in the result.");
12510
12511static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012512unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012513{
12514 PyObject *x, *y = NULL, *z = NULL;
12515 PyObject *new = NULL, *key, *value;
12516 Py_ssize_t i = 0;
12517 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012518
Georg Brandlceee0772007-11-27 23:48:05 +000012519 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12520 return NULL;
12521 new = PyDict_New();
12522 if (!new)
12523 return NULL;
12524 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012525 int x_kind, y_kind, z_kind;
12526 void *x_data, *y_data, *z_data;
12527
Georg Brandlceee0772007-11-27 23:48:05 +000012528 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012529 if (!PyUnicode_Check(x)) {
12530 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12531 "be a string if there is a second argument");
12532 goto err;
12533 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012535 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12536 "arguments must have equal length");
12537 goto err;
12538 }
12539 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 x_kind = PyUnicode_KIND(x);
12541 y_kind = PyUnicode_KIND(y);
12542 x_data = PyUnicode_DATA(x);
12543 y_data = PyUnicode_DATA(y);
12544 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12545 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012546 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012547 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012548 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012549 if (!value) {
12550 Py_DECREF(key);
12551 goto err;
12552 }
Georg Brandlceee0772007-11-27 23:48:05 +000012553 res = PyDict_SetItem(new, key, value);
12554 Py_DECREF(key);
12555 Py_DECREF(value);
12556 if (res < 0)
12557 goto err;
12558 }
12559 /* create entries for deleting chars in z */
12560 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 z_kind = PyUnicode_KIND(z);
12562 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012563 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012565 if (!key)
12566 goto err;
12567 res = PyDict_SetItem(new, key, Py_None);
12568 Py_DECREF(key);
12569 if (res < 0)
12570 goto err;
12571 }
12572 }
12573 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 int kind;
12575 void *data;
12576
Georg Brandlceee0772007-11-27 23:48:05 +000012577 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012578 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012579 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12580 "to maketrans it must be a dict");
12581 goto err;
12582 }
12583 /* copy entries into the new dict, converting string keys to int keys */
12584 while (PyDict_Next(x, &i, &key, &value)) {
12585 if (PyUnicode_Check(key)) {
12586 /* convert string keys to integer keys */
12587 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012588 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012589 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12590 "table must be of length 1");
12591 goto err;
12592 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 kind = PyUnicode_KIND(key);
12594 data = PyUnicode_DATA(key);
12595 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012596 if (!newkey)
12597 goto err;
12598 res = PyDict_SetItem(new, newkey, value);
12599 Py_DECREF(newkey);
12600 if (res < 0)
12601 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012602 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012603 /* just keep integer keys */
12604 if (PyDict_SetItem(new, key, value) < 0)
12605 goto err;
12606 } else {
12607 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12608 "be strings or integers");
12609 goto err;
12610 }
12611 }
12612 }
12613 return new;
12614 err:
12615 Py_DECREF(new);
12616 return NULL;
12617}
12618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012619PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012620 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621\n\
12622Return a copy of the string S, where all characters have been mapped\n\
12623through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012624Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012625Unmapped characters are left untouched. Characters mapped to None\n\
12626are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627
12628static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632}
12633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012634PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012635 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012637Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638
12639static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012640unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012642 if (PyUnicode_READY(self) == -1)
12643 return NULL;
12644 if (PyUnicode_IS_ASCII(self))
12645 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012646 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647}
12648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012649PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012650 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012652Pad a numeric string S with zeros on the left, to fill a field\n\
12653of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654
12655static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012656unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012658 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012659 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012660 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 int kind;
12662 void *data;
12663 Py_UCS4 chr;
12664
Martin v. Löwis18e16552006-02-15 17:27:45 +000012665 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666 return NULL;
12667
Benjamin Petersonbac79492012-01-14 13:34:47 -050012668 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012669 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670
Victor Stinnerc4b49542011-12-11 22:44:26 +010012671 if (PyUnicode_GET_LENGTH(self) >= width)
12672 return unicode_result_unchanged(self);
12673
12674 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675
12676 u = pad(self, fill, 0, '0');
12677
Walter Dörwald068325e2002-04-15 13:36:47 +000012678 if (u == NULL)
12679 return NULL;
12680
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 kind = PyUnicode_KIND(u);
12682 data = PyUnicode_DATA(u);
12683 chr = PyUnicode_READ(kind, data, fill);
12684
12685 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 PyUnicode_WRITE(kind, data, 0, chr);
12688 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689 }
12690
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012691 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012692 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694
12695#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012696static PyObject *
12697unicode__decimal2ascii(PyObject *self)
12698{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012699 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012700}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701#endif
12702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012703PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012704 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012706Return True if S starts with the specified prefix, False otherwise.\n\
12707With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012708With optional end, stop comparing S at that position.\n\
12709prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710
12711static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012712unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012713 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012715 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012716 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012717 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012718 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012719 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720
Jesus Ceaac451502011-04-20 17:09:23 +020012721 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012722 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012723 if (PyTuple_Check(subobj)) {
12724 Py_ssize_t i;
12725 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012726 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012727 if (substring == NULL)
12728 return NULL;
12729 result = tailmatch(self, substring, start, end, -1);
12730 Py_DECREF(substring);
12731 if (result) {
12732 Py_RETURN_TRUE;
12733 }
12734 }
12735 /* nothing matched */
12736 Py_RETURN_FALSE;
12737 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012738 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012739 if (substring == NULL) {
12740 if (PyErr_ExceptionMatches(PyExc_TypeError))
12741 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12742 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012743 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012744 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012745 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012746 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012747 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012748}
12749
12750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012751PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012754Return True if S ends with the specified suffix, False otherwise.\n\
12755With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012756With optional end, stop comparing S at that position.\n\
12757suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758
12759static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012760unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012761 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012762{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012763 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012764 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012765 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012766 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012767 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768
Jesus Ceaac451502011-04-20 17:09:23 +020012769 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012770 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012771 if (PyTuple_Check(subobj)) {
12772 Py_ssize_t i;
12773 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012774 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012775 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012778 result = tailmatch(self, substring, start, end, +1);
12779 Py_DECREF(substring);
12780 if (result) {
12781 Py_RETURN_TRUE;
12782 }
12783 }
12784 Py_RETURN_FALSE;
12785 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012786 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012787 if (substring == NULL) {
12788 if (PyErr_ExceptionMatches(PyExc_TypeError))
12789 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12790 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012791 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012792 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012793 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012795 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796}
12797
Victor Stinner202fdca2012-05-07 12:47:02 +020012798Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012799_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012800{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012801 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012802 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12803 writer->data = PyUnicode_DATA(writer->buffer);
12804 writer->kind = PyUnicode_KIND(writer->buffer);
12805}
12806
Victor Stinnerd3f08822012-05-29 12:57:52 +020012807void
12808_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012809{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012810 memset(writer, 0, sizeof(*writer));
12811#ifdef Py_DEBUG
12812 writer->kind = 5; /* invalid kind */
12813#endif
12814 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012815 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012816}
12817
Victor Stinnerd3f08822012-05-29 12:57:52 +020012818int
12819_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12820 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012821{
12822 Py_ssize_t newlen;
12823 PyObject *newbuffer;
12824
Victor Stinnerd3f08822012-05-29 12:57:52 +020012825 assert(length > 0);
12826
Victor Stinner202fdca2012-05-07 12:47:02 +020012827 if (length > PY_SSIZE_T_MAX - writer->pos) {
12828 PyErr_NoMemory();
12829 return -1;
12830 }
12831 newlen = writer->pos + length;
12832
Victor Stinnerd3f08822012-05-29 12:57:52 +020012833 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012834 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012835 /* overallocate 25% to limit the number of resize */
12836 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12837 newlen += newlen / 4;
12838 if (newlen < writer->min_length)
12839 newlen = writer->min_length;
12840 }
12841 writer->buffer = PyUnicode_New(newlen, maxchar);
12842 if (writer->buffer == NULL)
12843 return -1;
12844 _PyUnicodeWriter_Update(writer);
12845 return 0;
12846 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012847
Victor Stinnerd3f08822012-05-29 12:57:52 +020012848 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012849 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012850 /* overallocate 25% to limit the number of resize */
12851 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12852 newlen += newlen / 4;
12853 if (newlen < writer->min_length)
12854 newlen = writer->min_length;
12855 }
12856
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012857 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012858 /* resize + widen */
12859 newbuffer = PyUnicode_New(newlen, maxchar);
12860 if (newbuffer == NULL)
12861 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012862 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12863 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012864 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012865 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012866 }
12867 else {
12868 newbuffer = resize_compact(writer->buffer, newlen);
12869 if (newbuffer == NULL)
12870 return -1;
12871 }
12872 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012873 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012874 }
12875 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012876 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012877 newbuffer = PyUnicode_New(writer->size, maxchar);
12878 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012879 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012880 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12881 writer->buffer, 0, writer->pos);
12882 Py_DECREF(writer->buffer);
12883 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012884 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012885 }
12886 return 0;
12887}
12888
Victor Stinnerd3f08822012-05-29 12:57:52 +020012889int
12890_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12891{
12892 Py_UCS4 maxchar;
12893 Py_ssize_t len;
12894
12895 if (PyUnicode_READY(str) == -1)
12896 return -1;
12897 len = PyUnicode_GET_LENGTH(str);
12898 if (len == 0)
12899 return 0;
12900 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12901 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012902 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012903 Py_INCREF(str);
12904 writer->buffer = str;
12905 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012906 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012907 writer->size = 0;
12908 writer->pos += len;
12909 return 0;
12910 }
12911 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12912 return -1;
12913 }
12914 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12915 str, 0, len);
12916 writer->pos += len;
12917 return 0;
12918}
12919
12920PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012921_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012922{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012923 if (writer->pos == 0) {
12924 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020012925 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020012926 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012927 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012928 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12929 return writer->buffer;
12930 }
12931 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12932 PyObject *newbuffer;
12933 newbuffer = resize_compact(writer->buffer, writer->pos);
12934 if (newbuffer == NULL) {
12935 Py_DECREF(writer->buffer);
12936 return NULL;
12937 }
12938 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012939 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012940 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner2cb16aa2013-03-06 19:28:37 +010012941 return unicode_result_ready(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012942}
12943
Victor Stinnerd3f08822012-05-29 12:57:52 +020012944void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012945_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012946{
12947 Py_CLEAR(writer->buffer);
12948}
12949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012950#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012951
12952PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012954\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012955Return a formatted version of S, using substitutions from args and kwargs.\n\
12956The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012957
Eric Smith27bbca62010-11-04 17:06:58 +000012958PyDoc_STRVAR(format_map__doc__,
12959 "S.format_map(mapping) -> str\n\
12960\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012961Return a formatted version of S, using substitutions from mapping.\n\
12962The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012963
Eric Smith4a7d76d2008-05-30 18:10:19 +000012964static PyObject *
12965unicode__format__(PyObject* self, PyObject* args)
12966{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012967 PyObject *format_spec;
12968 _PyUnicodeWriter writer;
12969 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012970
12971 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12972 return NULL;
12973
Victor Stinnerd3f08822012-05-29 12:57:52 +020012974 if (PyUnicode_READY(self) == -1)
12975 return NULL;
12976 _PyUnicodeWriter_Init(&writer, 0);
12977 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12978 self, format_spec, 0,
12979 PyUnicode_GET_LENGTH(format_spec));
12980 if (ret == -1) {
12981 _PyUnicodeWriter_Dealloc(&writer);
12982 return NULL;
12983 }
12984 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012985}
12986
Eric Smith8c663262007-08-25 02:26:07 +000012987PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012988 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012989\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012990Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012991
12992static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012993unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012994{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012995 Py_ssize_t size;
12996
12997 /* If it's a compact object, account for base structure +
12998 character data. */
12999 if (PyUnicode_IS_COMPACT_ASCII(v))
13000 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13001 else if (PyUnicode_IS_COMPACT(v))
13002 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013003 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013004 else {
13005 /* If it is a two-block object, account for base object, and
13006 for character block if present. */
13007 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013008 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013009 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013010 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 }
13012 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013013 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013014 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013015 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013016 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013017 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013018
13019 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013020}
13021
13022PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013023 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013024
13025static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013026unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013027{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013028 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013029 if (!copy)
13030 return NULL;
13031 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013032}
13033
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013035 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013036 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013037 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13038 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013039 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13040 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013041 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013042 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13043 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13044 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13045 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13046 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013047 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013048 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13049 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13050 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013051 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013052 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13053 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13054 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013055 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013056 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013057 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013058 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013059 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13060 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13061 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13062 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13063 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13064 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13065 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13066 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13067 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13068 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13069 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13070 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13071 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13072 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013073 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013074 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013075 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013076 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013077 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013078 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013079 {"maketrans", (PyCFunction) unicode_maketrans,
13080 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013081 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013082#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013083 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013084 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013085#endif
13086
Benjamin Peterson14339b62009-01-31 16:36:08 +000013087 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088 {NULL, NULL}
13089};
13090
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013091static PyObject *
13092unicode_mod(PyObject *v, PyObject *w)
13093{
Brian Curtindfc80e32011-08-10 20:28:54 -050013094 if (!PyUnicode_Check(v))
13095 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013097}
13098
13099static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013100 0, /*nb_add*/
13101 0, /*nb_subtract*/
13102 0, /*nb_multiply*/
13103 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013104};
13105
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013107 (lenfunc) unicode_length, /* sq_length */
13108 PyUnicode_Concat, /* sq_concat */
13109 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13110 (ssizeargfunc) unicode_getitem, /* sq_item */
13111 0, /* sq_slice */
13112 0, /* sq_ass_item */
13113 0, /* sq_ass_slice */
13114 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115};
13116
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013117static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013118unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013119{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 if (PyUnicode_READY(self) == -1)
13121 return NULL;
13122
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013123 if (PyIndex_Check(item)) {
13124 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013125 if (i == -1 && PyErr_Occurred())
13126 return NULL;
13127 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013129 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013130 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013131 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013132 PyObject *result;
13133 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013134 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013135 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013137 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013138 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013139 return NULL;
13140 }
13141
13142 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013143 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013145 slicelength == PyUnicode_GET_LENGTH(self)) {
13146 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013147 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013148 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013149 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013150 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013151 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013152 src_kind = PyUnicode_KIND(self);
13153 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013154 if (!PyUnicode_IS_ASCII(self)) {
13155 kind_limit = kind_maxchar_limit(src_kind);
13156 max_char = 0;
13157 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13158 ch = PyUnicode_READ(src_kind, src_data, cur);
13159 if (ch > max_char) {
13160 max_char = ch;
13161 if (max_char >= kind_limit)
13162 break;
13163 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013164 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013165 }
Victor Stinner55c99112011-10-13 01:17:06 +020013166 else
13167 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013168 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013169 if (result == NULL)
13170 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013171 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013172 dest_data = PyUnicode_DATA(result);
13173
13174 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013175 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13176 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013177 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013178 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013179 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013180 } else {
13181 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13182 return NULL;
13183 }
13184}
13185
13186static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013187 (lenfunc)unicode_length, /* mp_length */
13188 (binaryfunc)unicode_subscript, /* mp_subscript */
13189 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013190};
13191
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193/* Helpers for PyUnicode_Format() */
13194
13195static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013196getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013198 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 (*p_argidx)++;
13201 if (arglen < 0)
13202 return args;
13203 else
13204 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 }
13206 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013207 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208 return NULL;
13209}
13210
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013211/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212
Victor Stinnerd3f08822012-05-29 12:57:52 +020013213static int
13214formatfloat(PyObject *v, int flags, int prec, int type,
13215 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013217 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013219 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013220
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221 x = PyFloat_AsDouble(v);
13222 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013223 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013224
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013227
Eric Smith0923d1d2009-04-16 20:16:10 +000013228 p = PyOS_double_to_string(x, type, prec,
13229 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013230 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013231 return -1;
13232 len = strlen(p);
13233 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013234 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13235 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013236 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013237 }
Victor Stinner184252a2012-06-16 02:57:41 +020013238 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013239 writer->pos += len;
13240 }
13241 else
13242 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013243 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013244 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245}
13246
Victor Stinnerd0880d52012-04-27 23:40:13 +020013247/* formatlong() emulates the format codes d, u, o, x and X, and
13248 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13249 * Python's regular ints.
13250 * Return value: a new PyUnicodeObject*, or NULL if error.
13251 * The output string is of the form
13252 * "-"? ("0x" | "0X")? digit+
13253 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13254 * set in flags. The case of hex digits will be correct,
13255 * There will be at least prec digits, zero-filled on the left if
13256 * necessary to get that many.
13257 * val object to be converted
13258 * flags bitmask of format flags; only F_ALT is looked at
13259 * prec minimum number of digits; 0-fill on left if needed
13260 * type a character in [duoxX]; u acts the same as d
13261 *
13262 * CAUTION: o, x and X conversions on regular ints can never
13263 * produce a '-' sign, but can for Python's unbounded ints.
13264 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013265static PyObject*
13266formatlong(PyObject *val, int flags, int prec, int type)
13267{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013268 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013269 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013270 Py_ssize_t i;
13271 int sign; /* 1 if '-', else 0 */
13272 int len; /* number of characters */
13273 Py_ssize_t llen;
13274 int numdigits; /* len == numnondigits + numdigits */
13275 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013276
Victor Stinnerd0880d52012-04-27 23:40:13 +020013277 /* Avoid exceeding SSIZE_T_MAX */
13278 if (prec > INT_MAX-3) {
13279 PyErr_SetString(PyExc_OverflowError,
13280 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013281 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013282 }
13283
13284 assert(PyLong_Check(val));
13285
13286 switch (type) {
13287 case 'd':
13288 case 'u':
13289 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013290 if (PyBool_Check(val))
13291 result = PyNumber_ToBase(val, 10);
13292 else
13293 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013294 break;
13295 case 'o':
13296 numnondigits = 2;
13297 result = PyNumber_ToBase(val, 8);
13298 break;
13299 case 'x':
13300 case 'X':
13301 numnondigits = 2;
13302 result = PyNumber_ToBase(val, 16);
13303 break;
13304 default:
13305 assert(!"'type' not in [duoxX]");
13306 }
13307 if (!result)
13308 return NULL;
13309
13310 assert(unicode_modifiable(result));
13311 assert(PyUnicode_IS_READY(result));
13312 assert(PyUnicode_IS_ASCII(result));
13313
13314 /* To modify the string in-place, there can only be one reference. */
13315 if (Py_REFCNT(result) != 1) {
13316 PyErr_BadInternalCall();
13317 return NULL;
13318 }
13319 buf = PyUnicode_DATA(result);
13320 llen = PyUnicode_GET_LENGTH(result);
13321 if (llen > INT_MAX) {
13322 PyErr_SetString(PyExc_ValueError,
13323 "string too large in _PyBytes_FormatLong");
13324 return NULL;
13325 }
13326 len = (int)llen;
13327 sign = buf[0] == '-';
13328 numnondigits += sign;
13329 numdigits = len - numnondigits;
13330 assert(numdigits > 0);
13331
13332 /* Get rid of base marker unless F_ALT */
13333 if (((flags & F_ALT) == 0 &&
13334 (type == 'o' || type == 'x' || type == 'X'))) {
13335 assert(buf[sign] == '0');
13336 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13337 buf[sign+1] == 'o');
13338 numnondigits -= 2;
13339 buf += 2;
13340 len -= 2;
13341 if (sign)
13342 buf[0] = '-';
13343 assert(len == numnondigits + numdigits);
13344 assert(numdigits > 0);
13345 }
13346
13347 /* Fill with leading zeroes to meet minimum width. */
13348 if (prec > numdigits) {
13349 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13350 numnondigits + prec);
13351 char *b1;
13352 if (!r1) {
13353 Py_DECREF(result);
13354 return NULL;
13355 }
13356 b1 = PyBytes_AS_STRING(r1);
13357 for (i = 0; i < numnondigits; ++i)
13358 *b1++ = *buf++;
13359 for (i = 0; i < prec - numdigits; i++)
13360 *b1++ = '0';
13361 for (i = 0; i < numdigits; i++)
13362 *b1++ = *buf++;
13363 *b1 = '\0';
13364 Py_DECREF(result);
13365 result = r1;
13366 buf = PyBytes_AS_STRING(result);
13367 len = numnondigits + prec;
13368 }
13369
13370 /* Fix up case for hex conversions. */
13371 if (type == 'X') {
13372 /* Need to convert all lower case letters to upper case.
13373 and need to convert 0x to 0X (and -0x to -0X). */
13374 for (i = 0; i < len; i++)
13375 if (buf[i] >= 'a' && buf[i] <= 'x')
13376 buf[i] -= 'a'-'A';
13377 }
13378 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13379 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013380 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013381 Py_DECREF(result);
13382 result = unicode;
13383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013384 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013385}
13386
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013387static Py_UCS4
13388formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013389{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013390 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013391 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013392 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013393 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 goto onError;
13396 }
13397 else {
13398 /* Integer input truncated to a character */
13399 long x;
13400 x = PyLong_AsLong(v);
13401 if (x == -1 && PyErr_Occurred())
13402 goto onError;
13403
Victor Stinner8faf8212011-12-08 22:14:11 +010013404 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 PyErr_SetString(PyExc_OverflowError,
13406 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013407 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 }
13409
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013410 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013411 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013412
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013414 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013416 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013417}
13418
Alexander Belopolsky40018472011-02-26 01:02:56 +000013419PyObject *
13420PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013422 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013423 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013424 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013425 PyObject *temp = NULL;
13426 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013427 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013428 void *fmt;
13429 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013430 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013431 Py_ssize_t sublen;
13432 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013433
Guido van Rossumd57fd912000-03-10 22:53:23 +000013434 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013435 PyErr_BadInternalCall();
13436 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013437 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013438 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013439 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 return NULL;
Victor Stinner19294072012-10-05 00:09:33 +020013441 if (PyUnicode_READY(uformat) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013442 Py_DECREF(uformat);
Victor Stinner19294072012-10-05 00:09:33 +020013443 return NULL;
13444 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013446 fmt = PyUnicode_DATA(uformat);
13447 fmtkind = PyUnicode_KIND(uformat);
13448 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13449 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013450
Victor Stinnerd3f08822012-05-29 12:57:52 +020013451 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013452
Guido van Rossumd57fd912000-03-10 22:53:23 +000013453 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 arglen = PyTuple_Size(args);
13455 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013456 }
13457 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013458 arglen = -1;
13459 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013460 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013461 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013463
13464 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013465 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013466 Py_ssize_t nonfmtpos;
13467 nonfmtpos = fmtpos++;
13468 while (fmtcnt >= 0 &&
13469 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13470 fmtpos++;
13471 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013472 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013473 if (fmtcnt < 0)
13474 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013475 sublen = fmtpos - nonfmtpos;
13476 maxchar = _PyUnicode_FindMaxChar(uformat,
13477 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013478 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013479 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013480
Victor Stinnerd3f08822012-05-29 12:57:52 +020013481 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13482 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013483 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013484 }
13485 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013486 /* Got a format specifier */
13487 int flags = 0;
13488 Py_ssize_t width = -1;
13489 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013490 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013491 Py_UCS4 fill;
13492 int sign;
13493 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 int isnumok;
13495 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013496 void *pbuf = NULL;
13497 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013498 Py_UCS4 bufmaxchar;
13499 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013501 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013502 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13503 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013504 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 Py_ssize_t keylen;
13506 PyObject *key;
13507 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013508
Benjamin Peterson29060642009-01-31 22:14:21 +000013509 if (dict == NULL) {
13510 PyErr_SetString(PyExc_TypeError,
13511 "format requires a mapping");
13512 goto onError;
13513 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013514 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013515 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013516 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013517 /* Skip over balanced parentheses */
13518 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013519 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13520 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013522 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013526 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 if (fmtcnt < 0 || pcount > 0) {
13528 PyErr_SetString(PyExc_ValueError,
13529 "incomplete format key");
13530 goto onError;
13531 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013532 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013533 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 if (key == NULL)
13535 goto onError;
13536 if (args_owned) {
13537 Py_DECREF(args);
13538 args_owned = 0;
13539 }
13540 args = PyObject_GetItem(dict, key);
13541 Py_DECREF(key);
13542 if (args == NULL) {
13543 goto onError;
13544 }
13545 args_owned = 1;
13546 arglen = -1;
13547 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013548 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013549 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013550 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13551 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013552 case '-': flags |= F_LJUST; continue;
13553 case '+': flags |= F_SIGN; continue;
13554 case ' ': flags |= F_BLANK; continue;
13555 case '#': flags |= F_ALT; continue;
13556 case '0': flags |= F_ZERO; continue;
13557 }
13558 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013559 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 if (c == '*') {
13561 v = getnextarg(args, arglen, &argidx);
13562 if (v == NULL)
13563 goto onError;
13564 if (!PyLong_Check(v)) {
13565 PyErr_SetString(PyExc_TypeError,
13566 "* wants int");
13567 goto onError;
13568 }
Serhiy Storchaka441d30f2013-01-19 12:26:26 +020013569 width = PyLong_AsSsize_t(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013570 if (width == -1 && PyErr_Occurred())
13571 goto onError;
13572 if (width < 0) {
13573 flags |= F_LJUST;
13574 width = -width;
13575 }
13576 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013577 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 }
13579 else if (c >= '0' && c <= '9') {
13580 width = c - '0';
13581 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 if (c < '0' || c > '9')
13584 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013585 /* Since c is unsigned, the RHS would end up as unsigned,
13586 mixing signed and unsigned comparison. Since c is between
13587 '0' and '9', casting to int is safe. */
13588 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 PyErr_SetString(PyExc_ValueError,
13590 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013591 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 }
13593 width = width*10 + (c - '0');
13594 }
13595 }
13596 if (c == '.') {
13597 prec = 0;
13598 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013599 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 if (c == '*') {
13601 v = getnextarg(args, arglen, &argidx);
13602 if (v == NULL)
13603 goto onError;
13604 if (!PyLong_Check(v)) {
13605 PyErr_SetString(PyExc_TypeError,
13606 "* wants int");
13607 goto onError;
13608 }
Serhiy Storchaka441d30f2013-01-19 12:26:26 +020013609 prec = _PyLong_AsInt(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 if (prec == -1 && PyErr_Occurred())
13611 goto onError;
13612 if (prec < 0)
13613 prec = 0;
13614 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013616 }
13617 else if (c >= '0' && c <= '9') {
13618 prec = c - '0';
13619 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 if (c < '0' || c > '9')
13622 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013623 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 PyErr_SetString(PyExc_ValueError,
13625 "prec too big");
13626 goto onError;
13627 }
13628 prec = prec*10 + (c - '0');
13629 }
13630 }
13631 } /* prec */
13632 if (fmtcnt >= 0) {
13633 if (c == 'h' || c == 'l' || c == 'L') {
13634 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013636 }
13637 }
13638 if (fmtcnt < 0) {
13639 PyErr_SetString(PyExc_ValueError,
13640 "incomplete format");
13641 goto onError;
13642 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013643 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013644 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013645
13646 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013647 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013648 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013649 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13650 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013651 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013653
Victor Stinneraff3cc62012-04-30 05:19:21 +020013654 v = getnextarg(args, arglen, &argidx);
13655 if (v == NULL)
13656 goto onError;
13657
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013659 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013660 fill = ' ';
13661 switch (c) {
13662
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 case 's':
13664 case 'r':
13665 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013666 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13667 /* Fast path */
13668 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13669 goto onError;
13670 goto nextarg;
13671 }
13672
Victor Stinner808fc0a2010-03-22 12:50:40 +000013673 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 temp = v;
13675 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013676 }
13677 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 if (c == 's')
13679 temp = PyObject_Str(v);
13680 else if (c == 'r')
13681 temp = PyObject_Repr(v);
13682 else
13683 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 break;
13686
13687 case 'i':
13688 case 'd':
13689 case 'u':
13690 case 'o':
13691 case 'x':
13692 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013693 if (PyLong_CheckExact(v)
13694 && width == -1 && prec == -1
13695 && !(flags & (F_SIGN | F_BLANK)))
13696 {
13697 /* Fast path */
13698 switch(c)
13699 {
13700 case 'd':
13701 case 'i':
13702 case 'u':
13703 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13704 goto onError;
13705 goto nextarg;
13706 case 'x':
13707 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13708 goto onError;
13709 goto nextarg;
13710 case 'o':
13711 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13712 goto onError;
13713 goto nextarg;
13714 default:
13715 break;
13716 }
13717 }
13718
Benjamin Peterson29060642009-01-31 22:14:21 +000013719 isnumok = 0;
13720 if (PyNumber_Check(v)) {
13721 PyObject *iobj=NULL;
13722
13723 if (PyLong_Check(v)) {
13724 iobj = v;
13725 Py_INCREF(iobj);
13726 }
13727 else {
13728 iobj = PyNumber_Long(v);
13729 }
13730 if (iobj!=NULL) {
13731 if (PyLong_Check(iobj)) {
13732 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013733 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013734 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013735 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013736 }
13737 else {
13738 Py_DECREF(iobj);
13739 }
13740 }
13741 }
13742 if (!isnumok) {
13743 PyErr_Format(PyExc_TypeError,
13744 "%%%c format: a number is required, "
13745 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13746 goto onError;
13747 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013748 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 fill = '0';
13750 break;
13751
13752 case 'e':
13753 case 'E':
13754 case 'f':
13755 case 'F':
13756 case 'g':
13757 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013758 if (width == -1 && prec == -1
13759 && !(flags & (F_SIGN | F_BLANK)))
13760 {
13761 /* Fast path */
13762 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13763 goto onError;
13764 goto nextarg;
13765 }
13766
Benjamin Peterson29060642009-01-31 22:14:21 +000013767 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013768 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013770 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13771 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 break;
13773
13774 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013775 {
13776 Py_UCS4 ch = formatchar(v);
13777 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013779 if (width == -1 && prec == -1) {
13780 /* Fast path */
13781 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13782 goto onError;
13783 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13784 writer.pos += 1;
13785 goto nextarg;
13786 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013787 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013788 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013789 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013790
13791 default:
13792 PyErr_Format(PyExc_ValueError,
13793 "unsupported format character '%c' (0x%x) "
13794 "at index %zd",
13795 (31<=c && c<=126) ? (char)c : '?',
13796 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013798 goto onError;
13799 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013800 if (temp == NULL)
13801 goto onError;
13802 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013803
13804 if (width == -1 && prec == -1
13805 && !(flags & (F_SIGN | F_BLANK)))
13806 {
13807 /* Fast path */
13808 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13809 goto onError;
13810 goto nextarg;
13811 }
13812
Victor Stinneraff3cc62012-04-30 05:19:21 +020013813 if (PyUnicode_READY(temp) == -1) {
13814 Py_CLEAR(temp);
13815 goto onError;
13816 }
13817 kind = PyUnicode_KIND(temp);
13818 pbuf = PyUnicode_DATA(temp);
13819 len = PyUnicode_GET_LENGTH(temp);
13820
13821 if (c == 's' || c == 'r' || c == 'a') {
13822 if (prec >= 0 && len > prec)
13823 len = prec;
13824 }
13825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013826 /* pbuf is initialized here. */
13827 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013829 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13830 if (ch == '-' || ch == '+') {
13831 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013832 len--;
13833 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013834 }
13835 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013836 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013838 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 else
13840 sign = 0;
13841 }
13842 if (width < len)
13843 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013844
13845 /* Compute the length and maximum character of the
13846 written characters */
13847 bufmaxchar = 127;
13848 if (!(flags & F_LJUST)) {
13849 if (sign) {
13850 if ((width-1) > len)
Benjamin Peterson7e303732013-06-10 09:19:46 -070013851 bufmaxchar = Py_MAX(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013852 }
13853 else {
13854 if (width > len)
Benjamin Peterson7e303732013-06-10 09:19:46 -070013855 bufmaxchar = Py_MAX(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013856 }
13857 }
13858 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Benjamin Peterson7e303732013-06-10 09:19:46 -070013859 bufmaxchar = Py_MAX(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013860
13861 buflen = width;
13862 if (sign && len == width)
13863 buflen++;
13864
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013865 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013866 goto onError;
13867
13868 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013871 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13872 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013873 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013874 if (width > len)
13875 width--;
13876 }
13877 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013878 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013879 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013880 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013881 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13882 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13883 writer.pos += 2;
13884 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013885 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013886 width -= 2;
13887 if (width < 0)
13888 width = 0;
13889 len -= 2;
13890 }
13891 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013892 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013893 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13894 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013895 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013896 }
13897 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013898 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013899 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13900 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013901 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013902 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13904 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013905 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13906 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13907 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013908 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 }
13910 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013911
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013912 if (len) {
13913 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13914 temp, pindex, len);
13915 writer.pos += len;
13916 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013917 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013918 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013919 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13920 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013921 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013922
Victor Stinnerd3f08822012-05-29 12:57:52 +020013923nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013924 if (dict && (argidx < arglen) && c != '%') {
13925 PyErr_SetString(PyExc_TypeError,
13926 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013927 goto onError;
13928 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013929 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013930 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931 } /* until end */
13932 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013933 PyErr_SetString(PyExc_TypeError,
13934 "not all arguments converted during string formatting");
13935 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013936 }
13937
13938 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013939 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940 }
13941 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013942 Py_XDECREF(temp);
13943 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013944 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945
Benjamin Peterson29060642009-01-31 22:14:21 +000013946 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013948 Py_XDECREF(temp);
13949 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013950 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013951 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013952 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953 }
13954 return NULL;
13955}
13956
Jeremy Hylton938ace62002-07-17 16:30:39 +000013957static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013958unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13959
Tim Peters6d6c1a32001-08-02 04:15:00 +000013960static PyObject *
13961unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13962{
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 static char *kwlist[] = {"object", "encoding", "errors", 0};
13965 char *encoding = NULL;
13966 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013967
Benjamin Peterson14339b62009-01-31 16:36:08 +000013968 if (type != &PyUnicode_Type)
13969 return unicode_subtype_new(type, args, kwds);
13970 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013971 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013972 return NULL;
13973 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020013974 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000013975 if (encoding == NULL && errors == NULL)
13976 return PyObject_Str(x);
13977 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013978 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013979}
13980
Guido van Rossume023fe02001-08-30 03:12:59 +000013981static PyObject *
13982unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13983{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013984 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013985 Py_ssize_t length, char_size;
13986 int share_wstr, share_utf8;
13987 unsigned int kind;
13988 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013989
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013991
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013992 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013994 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013995 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013996 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013997 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013998 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013999 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014000
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014001 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014002 if (self == NULL) {
14003 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014004 return NULL;
14005 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014006 kind = PyUnicode_KIND(unicode);
14007 length = PyUnicode_GET_LENGTH(unicode);
14008
14009 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014010#ifdef Py_DEBUG
14011 _PyUnicode_HASH(self) = -1;
14012#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014013 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014014#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014015 _PyUnicode_STATE(self).interned = 0;
14016 _PyUnicode_STATE(self).kind = kind;
14017 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014018 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014019 _PyUnicode_STATE(self).ready = 1;
14020 _PyUnicode_WSTR(self) = NULL;
14021 _PyUnicode_UTF8_LENGTH(self) = 0;
14022 _PyUnicode_UTF8(self) = NULL;
14023 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014024 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014025
14026 share_utf8 = 0;
14027 share_wstr = 0;
14028 if (kind == PyUnicode_1BYTE_KIND) {
14029 char_size = 1;
14030 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14031 share_utf8 = 1;
14032 }
14033 else if (kind == PyUnicode_2BYTE_KIND) {
14034 char_size = 2;
14035 if (sizeof(wchar_t) == 2)
14036 share_wstr = 1;
14037 }
14038 else {
14039 assert(kind == PyUnicode_4BYTE_KIND);
14040 char_size = 4;
14041 if (sizeof(wchar_t) == 4)
14042 share_wstr = 1;
14043 }
14044
14045 /* Ensure we won't overflow the length. */
14046 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14047 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014048 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014049 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014050 data = PyObject_MALLOC((length + 1) * char_size);
14051 if (data == NULL) {
14052 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014053 goto onError;
14054 }
14055
Victor Stinnerc3c74152011-10-02 20:39:55 +020014056 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014057 if (share_utf8) {
14058 _PyUnicode_UTF8_LENGTH(self) = length;
14059 _PyUnicode_UTF8(self) = data;
14060 }
14061 if (share_wstr) {
14062 _PyUnicode_WSTR_LENGTH(self) = length;
14063 _PyUnicode_WSTR(self) = (wchar_t *)data;
14064 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014065
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014066 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014067 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014068 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014069#ifdef Py_DEBUG
14070 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14071#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014072 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014073 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014074
14075onError:
14076 Py_DECREF(unicode);
14077 Py_DECREF(self);
14078 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014079}
14080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014081PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014082"str(object='') -> str\n\
14083str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014084\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014085Create a new string object from the given object. If encoding or\n\
14086errors is specified, then the object must expose a data buffer\n\
14087that will be decoded using the given encoding and error handler.\n\
14088Otherwise, returns the result of object.__str__() (if defined)\n\
14089or repr(object).\n\
14090encoding defaults to sys.getdefaultencoding().\n\
14091errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014092
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014093static PyObject *unicode_iter(PyObject *seq);
14094
Guido van Rossumd57fd912000-03-10 22:53:23 +000014095PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014096 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 "str", /* tp_name */
14098 sizeof(PyUnicodeObject), /* tp_size */
14099 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014100 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014101 (destructor)unicode_dealloc, /* tp_dealloc */
14102 0, /* tp_print */
14103 0, /* tp_getattr */
14104 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014105 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014106 unicode_repr, /* tp_repr */
14107 &unicode_as_number, /* tp_as_number */
14108 &unicode_as_sequence, /* tp_as_sequence */
14109 &unicode_as_mapping, /* tp_as_mapping */
14110 (hashfunc) unicode_hash, /* tp_hash*/
14111 0, /* tp_call*/
14112 (reprfunc) unicode_str, /* tp_str */
14113 PyObject_GenericGetAttr, /* tp_getattro */
14114 0, /* tp_setattro */
14115 0, /* tp_as_buffer */
14116 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014117 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014118 unicode_doc, /* tp_doc */
14119 0, /* tp_traverse */
14120 0, /* tp_clear */
14121 PyUnicode_RichCompare, /* tp_richcompare */
14122 0, /* tp_weaklistoffset */
14123 unicode_iter, /* tp_iter */
14124 0, /* tp_iternext */
14125 unicode_methods, /* tp_methods */
14126 0, /* tp_members */
14127 0, /* tp_getset */
14128 &PyBaseObject_Type, /* tp_base */
14129 0, /* tp_dict */
14130 0, /* tp_descr_get */
14131 0, /* tp_descr_set */
14132 0, /* tp_dictoffset */
14133 0, /* tp_init */
14134 0, /* tp_alloc */
14135 unicode_new, /* tp_new */
14136 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014137};
14138
14139/* Initialize the Unicode implementation */
14140
Victor Stinner3a50e702011-10-18 21:21:00 +020014141int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014142{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014143 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014144 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014145 0x000A, /* LINE FEED */
14146 0x000D, /* CARRIAGE RETURN */
14147 0x001C, /* FILE SEPARATOR */
14148 0x001D, /* GROUP SEPARATOR */
14149 0x001E, /* RECORD SEPARATOR */
14150 0x0085, /* NEXT LINE */
14151 0x2028, /* LINE SEPARATOR */
14152 0x2029, /* PARAGRAPH SEPARATOR */
14153 };
14154
Fred Drakee4315f52000-05-09 19:53:39 +000014155 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014156 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014157 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014158 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014159 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014160
Guido van Rossumcacfc072002-05-24 19:01:59 +000014161 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014162 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014163
14164 /* initialize the linebreak bloom filter */
14165 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014166 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014167 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014168
Christian Heimes26532f72013-07-20 14:57:16 +020014169 if (PyType_Ready(&EncodingMapType) < 0)
14170 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014171
Benjamin Petersonc4311282012-10-30 23:21:10 -040014172 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14173 Py_FatalError("Can't initialize field name iterator type");
14174
14175 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14176 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014177
Victor Stinner3a50e702011-10-18 21:21:00 +020014178#ifdef HAVE_MBCS
14179 winver.dwOSVersionInfoSize = sizeof(winver);
14180 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14181 PyErr_SetFromWindowsErr(0);
14182 return -1;
14183 }
14184#endif
14185 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014186}
14187
14188/* Finalize the Unicode implementation */
14189
Christian Heimesa156e092008-02-16 07:38:31 +000014190int
14191PyUnicode_ClearFreeList(void)
14192{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014193 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014194}
14195
Guido van Rossumd57fd912000-03-10 22:53:23 +000014196void
Thomas Wouters78890102000-07-22 19:25:51 +000014197_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014198{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014199 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014200
Serhiy Storchaka05997252013-01-26 12:14:02 +020014201 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014202
Serhiy Storchaka05997252013-01-26 12:14:02 +020014203 for (i = 0; i < 256; i++)
14204 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014205 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014206 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014207}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014208
Walter Dörwald16807132007-05-25 13:52:07 +000014209void
14210PyUnicode_InternInPlace(PyObject **p)
14211{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014212 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014213 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014214#ifdef Py_DEBUG
14215 assert(s != NULL);
14216 assert(_PyUnicode_CHECK(s));
14217#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014218 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014219 return;
14220#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014221 /* If it's a subclass, we don't really know what putting
14222 it in the interned dict might do. */
14223 if (!PyUnicode_CheckExact(s))
14224 return;
14225 if (PyUnicode_CHECK_INTERNED(s))
14226 return;
14227 if (interned == NULL) {
14228 interned = PyDict_New();
14229 if (interned == NULL) {
14230 PyErr_Clear(); /* Don't leave an exception */
14231 return;
14232 }
14233 }
14234 /* It might be that the GetItem call fails even
14235 though the key is present in the dictionary,
14236 namely when this happens during a stack overflow. */
14237 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014238 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014240
Benjamin Peterson29060642009-01-31 22:14:21 +000014241 if (t) {
14242 Py_INCREF(t);
14243 Py_DECREF(*p);
14244 *p = t;
14245 return;
14246 }
Walter Dörwald16807132007-05-25 13:52:07 +000014247
Benjamin Peterson14339b62009-01-31 16:36:08 +000014248 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014249 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014250 PyErr_Clear();
14251 PyThreadState_GET()->recursion_critical = 0;
14252 return;
14253 }
14254 PyThreadState_GET()->recursion_critical = 0;
14255 /* The two references in interned are not counted by refcnt.
14256 The deallocator will take care of this */
14257 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014258 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014259}
14260
14261void
14262PyUnicode_InternImmortal(PyObject **p)
14263{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014264 PyUnicode_InternInPlace(p);
14265 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014266 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014267 Py_INCREF(*p);
14268 }
Walter Dörwald16807132007-05-25 13:52:07 +000014269}
14270
14271PyObject *
14272PyUnicode_InternFromString(const char *cp)
14273{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014274 PyObject *s = PyUnicode_FromString(cp);
14275 if (s == NULL)
14276 return NULL;
14277 PyUnicode_InternInPlace(&s);
14278 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014279}
14280
Alexander Belopolsky40018472011-02-26 01:02:56 +000014281void
14282_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014283{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014285 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014286 Py_ssize_t i, n;
14287 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014288
Benjamin Peterson14339b62009-01-31 16:36:08 +000014289 if (interned == NULL || !PyDict_Check(interned))
14290 return;
14291 keys = PyDict_Keys(interned);
14292 if (keys == NULL || !PyList_Check(keys)) {
14293 PyErr_Clear();
14294 return;
14295 }
Walter Dörwald16807132007-05-25 13:52:07 +000014296
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14298 detector, interned unicode strings are not forcibly deallocated;
14299 rather, we give them their stolen references back, and then clear
14300 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014301
Benjamin Peterson14339b62009-01-31 16:36:08 +000014302 n = PyList_GET_SIZE(keys);
14303 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014304 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014305 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014306 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014307 if (PyUnicode_READY(s) == -1) {
14308 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014309 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014311 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014312 case SSTATE_NOT_INTERNED:
14313 /* XXX Shouldn't happen */
14314 break;
14315 case SSTATE_INTERNED_IMMORTAL:
14316 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014317 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014318 break;
14319 case SSTATE_INTERNED_MORTAL:
14320 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014321 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014322 break;
14323 default:
14324 Py_FatalError("Inconsistent interned string state.");
14325 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014326 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014327 }
14328 fprintf(stderr, "total size of all interned strings: "
14329 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14330 "mortal/immortal\n", mortal_size, immortal_size);
14331 Py_DECREF(keys);
14332 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014333 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014334}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014335
14336
14337/********************* Unicode Iterator **************************/
14338
14339typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014340 PyObject_HEAD
14341 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014342 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014343} unicodeiterobject;
14344
14345static void
14346unicodeiter_dealloc(unicodeiterobject *it)
14347{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014348 _PyObject_GC_UNTRACK(it);
14349 Py_XDECREF(it->it_seq);
14350 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014351}
14352
14353static int
14354unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14355{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014356 Py_VISIT(it->it_seq);
14357 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014358}
14359
14360static PyObject *
14361unicodeiter_next(unicodeiterobject *it)
14362{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014363 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014364
Benjamin Peterson14339b62009-01-31 16:36:08 +000014365 assert(it != NULL);
14366 seq = it->it_seq;
14367 if (seq == NULL)
14368 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014369 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014371 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14372 int kind = PyUnicode_KIND(seq);
14373 void *data = PyUnicode_DATA(seq);
14374 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14375 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014376 if (item != NULL)
14377 ++it->it_index;
14378 return item;
14379 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014380
Benjamin Peterson14339b62009-01-31 16:36:08 +000014381 Py_DECREF(seq);
14382 it->it_seq = NULL;
14383 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014384}
14385
14386static PyObject *
14387unicodeiter_len(unicodeiterobject *it)
14388{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014389 Py_ssize_t len = 0;
14390 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014391 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014392 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014393}
14394
14395PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14396
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014397static PyObject *
14398unicodeiter_reduce(unicodeiterobject *it)
14399{
14400 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014401 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014402 it->it_seq, it->it_index);
14403 } else {
14404 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14405 if (u == NULL)
14406 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014407 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014408 }
14409}
14410
14411PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14412
14413static PyObject *
14414unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14415{
14416 Py_ssize_t index = PyLong_AsSsize_t(state);
14417 if (index == -1 && PyErr_Occurred())
14418 return NULL;
14419 if (index < 0)
14420 index = 0;
14421 it->it_index = index;
14422 Py_RETURN_NONE;
14423}
14424
14425PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14426
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014427static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014428 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014429 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014430 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14431 reduce_doc},
14432 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14433 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014434 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014435};
14436
14437PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014438 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14439 "str_iterator", /* tp_name */
14440 sizeof(unicodeiterobject), /* tp_basicsize */
14441 0, /* tp_itemsize */
14442 /* methods */
14443 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14444 0, /* tp_print */
14445 0, /* tp_getattr */
14446 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014447 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014448 0, /* tp_repr */
14449 0, /* tp_as_number */
14450 0, /* tp_as_sequence */
14451 0, /* tp_as_mapping */
14452 0, /* tp_hash */
14453 0, /* tp_call */
14454 0, /* tp_str */
14455 PyObject_GenericGetAttr, /* tp_getattro */
14456 0, /* tp_setattro */
14457 0, /* tp_as_buffer */
14458 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14459 0, /* tp_doc */
14460 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14461 0, /* tp_clear */
14462 0, /* tp_richcompare */
14463 0, /* tp_weaklistoffset */
14464 PyObject_SelfIter, /* tp_iter */
14465 (iternextfunc)unicodeiter_next, /* tp_iternext */
14466 unicodeiter_methods, /* tp_methods */
14467 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014468};
14469
14470static PyObject *
14471unicode_iter(PyObject *seq)
14472{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014473 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014474
Benjamin Peterson14339b62009-01-31 16:36:08 +000014475 if (!PyUnicode_Check(seq)) {
14476 PyErr_BadInternalCall();
14477 return NULL;
14478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014479 if (PyUnicode_READY(seq) == -1)
14480 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014481 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14482 if (it == NULL)
14483 return NULL;
14484 it->it_index = 0;
14485 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014486 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014487 _PyObject_GC_TRACK(it);
14488 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014489}
14490
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014491
14492size_t
14493Py_UNICODE_strlen(const Py_UNICODE *u)
14494{
14495 int res = 0;
14496 while(*u++)
14497 res++;
14498 return res;
14499}
14500
14501Py_UNICODE*
14502Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14503{
14504 Py_UNICODE *u = s1;
14505 while ((*u++ = *s2++));
14506 return s1;
14507}
14508
14509Py_UNICODE*
14510Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14511{
14512 Py_UNICODE *u = s1;
14513 while ((*u++ = *s2++))
14514 if (n-- == 0)
14515 break;
14516 return s1;
14517}
14518
14519Py_UNICODE*
14520Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14521{
14522 Py_UNICODE *u1 = s1;
14523 u1 += Py_UNICODE_strlen(u1);
14524 Py_UNICODE_strcpy(u1, s2);
14525 return s1;
14526}
14527
14528int
14529Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14530{
14531 while (*s1 && *s2 && *s1 == *s2)
14532 s1++, s2++;
14533 if (*s1 && *s2)
14534 return (*s1 < *s2) ? -1 : +1;
14535 if (*s1)
14536 return 1;
14537 if (*s2)
14538 return -1;
14539 return 0;
14540}
14541
14542int
14543Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14544{
14545 register Py_UNICODE u1, u2;
14546 for (; n != 0; n--) {
14547 u1 = *s1;
14548 u2 = *s2;
14549 if (u1 != u2)
14550 return (u1 < u2) ? -1 : +1;
14551 if (u1 == '\0')
14552 return 0;
14553 s1++;
14554 s2++;
14555 }
14556 return 0;
14557}
14558
14559Py_UNICODE*
14560Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14561{
14562 const Py_UNICODE *p;
14563 for (p = s; *p; p++)
14564 if (*p == c)
14565 return (Py_UNICODE*)p;
14566 return NULL;
14567}
14568
14569Py_UNICODE*
14570Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14571{
14572 const Py_UNICODE *p;
14573 p = s + Py_UNICODE_strlen(s);
14574 while (p != s) {
14575 p--;
14576 if (*p == c)
14577 return (Py_UNICODE*)p;
14578 }
14579 return NULL;
14580}
Victor Stinner331ea922010-08-10 16:37:20 +000014581
Victor Stinner71133ff2010-09-01 23:43:53 +000014582Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014583PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014584{
Victor Stinner577db2c2011-10-11 22:12:48 +020014585 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014586 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014588 if (!PyUnicode_Check(unicode)) {
14589 PyErr_BadArgument();
14590 return NULL;
14591 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014592 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014593 if (u == NULL)
14594 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014595 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014596 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014597 PyErr_NoMemory();
14598 return NULL;
14599 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014600 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014601 size *= sizeof(Py_UNICODE);
14602 copy = PyMem_Malloc(size);
14603 if (copy == NULL) {
14604 PyErr_NoMemory();
14605 return NULL;
14606 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014607 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014608 return copy;
14609}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014610
Georg Brandl66c221e2010-10-14 07:04:07 +000014611/* A _string module, to export formatter_parser and formatter_field_name_split
14612 to the string.Formatter class implemented in Python. */
14613
14614static PyMethodDef _string_methods[] = {
14615 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14616 METH_O, PyDoc_STR("split the argument as a field name")},
14617 {"formatter_parser", (PyCFunction) formatter_parser,
14618 METH_O, PyDoc_STR("parse the argument as a format string")},
14619 {NULL, NULL}
14620};
14621
14622static struct PyModuleDef _string_module = {
14623 PyModuleDef_HEAD_INIT,
14624 "_string",
14625 PyDoc_STR("string helper module"),
14626 0,
14627 _string_methods,
14628 NULL,
14629 NULL,
14630 NULL,
14631 NULL
14632};
14633
14634PyMODINIT_FUNC
14635PyInit__string(void)
14636{
14637 return PyModule_Create(&_string_module);
14638}
14639
14640
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014641#ifdef __cplusplus
14642}
14643#endif