blob: beafaa44963436da679d3d2d697350dfee577cc8 [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) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004477 *consumed = startinpos;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004478 if (outpos != shiftOutStart &&
4479 PyUnicode_MAX_CHAR_VALUE(unicode) > 127) {
4480 PyObject *result = PyUnicode_FromKindAndData(
4481 PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4482 shiftOutStart);
4483 Py_DECREF(unicode);
4484 unicode = result;
4485 }
4486 outpos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 }
4488 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004489 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004491 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004493 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 goto onError;
4495
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004496 Py_XDECREF(errorHandler);
4497 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004498 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499
Benjamin Peterson29060642009-01-31 22:14:21 +00004500 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004501 Py_XDECREF(errorHandler);
4502 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503 Py_DECREF(unicode);
4504 return NULL;
4505}
4506
4507
Alexander Belopolsky40018472011-02-26 01:02:56 +00004508PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004509_PyUnicode_EncodeUTF7(PyObject *str,
4510 int base64SetO,
4511 int base64WhiteSpace,
4512 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004513{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004514 int kind;
4515 void *data;
4516 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004517 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004519 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520 unsigned int base64bits = 0;
4521 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004522 char * out;
4523 char * start;
4524
Benjamin Petersonbac79492012-01-14 13:34:47 -05004525 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004526 return NULL;
4527 kind = PyUnicode_KIND(str);
4528 data = PyUnicode_DATA(str);
4529 len = PyUnicode_GET_LENGTH(str);
4530
4531 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004532 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004533
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004534 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004535 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004536 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004537 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 if (v == NULL)
4539 return NULL;
4540
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004541 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004542 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004543 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 if (inShift) {
4546 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4547 /* shifting out */
4548 if (base64bits) { /* output remaining bits */
4549 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4550 base64buffer = 0;
4551 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004552 }
4553 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 /* Characters not in the BASE64 set implicitly unshift the sequence
4555 so no '-' is required, except if the character is itself a '-' */
4556 if (IS_BASE64(ch) || ch == '-') {
4557 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004558 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004559 *out++ = (char) ch;
4560 }
4561 else {
4562 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004563 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004564 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 else { /* not in a shift sequence */
4566 if (ch == '+') {
4567 *out++ = '+';
4568 *out++ = '-';
4569 }
4570 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4571 *out++ = (char) ch;
4572 }
4573 else {
4574 *out++ = '+';
4575 inShift = 1;
4576 goto encode_char;
4577 }
4578 }
4579 continue;
4580encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004582 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004583
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 /* code first surrogate */
4585 base64bits += 16;
4586 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4587 while (base64bits >= 6) {
4588 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4589 base64bits -= 6;
4590 }
4591 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004592 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004594 base64bits += 16;
4595 base64buffer = (base64buffer << 16) | ch;
4596 while (base64bits >= 6) {
4597 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4598 base64bits -= 6;
4599 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004600 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004601 if (base64bits)
4602 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4603 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004605 if (_PyBytes_Resize(&v, out - start) < 0)
4606 return NULL;
4607 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004608}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004609PyObject *
4610PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4611 Py_ssize_t size,
4612 int base64SetO,
4613 int base64WhiteSpace,
4614 const char *errors)
4615{
4616 PyObject *result;
4617 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4618 if (tmp == NULL)
4619 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004620 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004621 base64WhiteSpace, errors);
4622 Py_DECREF(tmp);
4623 return result;
4624}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004625
Antoine Pitrou244651a2009-05-04 18:56:13 +00004626#undef IS_BASE64
4627#undef FROM_BASE64
4628#undef TO_BASE64
4629#undef DECODE_DIRECT
4630#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004631
Guido van Rossumd57fd912000-03-10 22:53:23 +00004632/* --- UTF-8 Codec -------------------------------------------------------- */
4633
Alexander Belopolsky40018472011-02-26 01:02:56 +00004634PyObject *
4635PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004636 Py_ssize_t size,
4637 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004638{
Walter Dörwald69652032004-09-07 20:24:22 +00004639 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4640}
4641
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004642#include "stringlib/asciilib.h"
4643#include "stringlib/codecs.h"
4644#include "stringlib/undef.h"
4645
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004646#include "stringlib/ucs1lib.h"
4647#include "stringlib/codecs.h"
4648#include "stringlib/undef.h"
4649
4650#include "stringlib/ucs2lib.h"
4651#include "stringlib/codecs.h"
4652#include "stringlib/undef.h"
4653
4654#include "stringlib/ucs4lib.h"
4655#include "stringlib/codecs.h"
4656#include "stringlib/undef.h"
4657
Antoine Pitrouab868312009-01-10 15:40:25 +00004658/* Mask to quickly check whether a C 'long' contains a
4659 non-ASCII, UTF8-encoded char. */
4660#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004661# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004662#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004663# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004664#else
4665# error C 'long' size should be either 4 or 8!
4666#endif
4667
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004668static Py_ssize_t
4669ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004670{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004671 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004672 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004673
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004674 /*
4675 * Issue #17237: m68k is a bit different from most architectures in
4676 * that objects do not use "natural alignment" - for example, int and
4677 * long are only aligned at 2-byte boundaries. Therefore the assert()
4678 * won't work; also, tests have shown that skipping the "optimised
4679 * version" will even speed up m68k.
4680 */
4681#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004683 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4684 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004685 /* Fast path, see in STRINGLIB(utf8_decode) for
4686 an explanation. */
4687 /* Help register allocation */
4688 register const char *_p = p;
4689 register Py_UCS1 * q = dest;
4690 while (_p < aligned_end) {
4691 unsigned long value = *(const unsigned long *) _p;
4692 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004693 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694 *((unsigned long *)q) = value;
4695 _p += SIZEOF_LONG;
4696 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004697 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698 p = _p;
4699 while (p < end) {
4700 if ((unsigned char)*p & 0x80)
4701 break;
4702 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004703 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004706#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004707#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004708 while (p < end) {
4709 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4710 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004711 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 /* Help register allocation */
4713 register const char *_p = p;
4714 while (_p < aligned_end) {
4715 unsigned long value = *(unsigned long *) _p;
4716 if (value & ASCII_CHAR_MASK)
4717 break;
4718 _p += SIZEOF_LONG;
4719 }
4720 p = _p;
4721 if (_p == end)
4722 break;
4723 }
4724 if ((unsigned char)*p & 0x80)
4725 break;
4726 ++p;
4727 }
4728 memcpy(dest, start, p - start);
4729 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004730}
Antoine Pitrouab868312009-01-10 15:40:25 +00004731
Victor Stinner785938e2011-12-11 20:09:03 +01004732PyObject *
4733PyUnicode_DecodeUTF8Stateful(const char *s,
4734 Py_ssize_t size,
4735 const char *errors,
4736 Py_ssize_t *consumed)
4737{
Victor Stinner785938e2011-12-11 20:09:03 +01004738 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004739 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004740 const char *end = s + size;
4741 Py_ssize_t outpos;
4742
4743 Py_ssize_t startinpos;
4744 Py_ssize_t endinpos;
4745 const char *errmsg = "";
4746 PyObject *errorHandler = NULL;
4747 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004748
4749 if (size == 0) {
4750 if (consumed)
4751 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004752 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004753 }
4754
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4756 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004757 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 *consumed = 1;
4759 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004760 }
4761
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004763 if (!unicode)
4764 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004765
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4767 s += outpos;
4768 while (s < end) {
4769 Py_UCS4 ch;
4770 int kind = PyUnicode_KIND(unicode);
4771 if (kind == PyUnicode_1BYTE_KIND) {
4772 if (PyUnicode_IS_ASCII(unicode))
4773 ch = asciilib_utf8_decode(&s, end,
4774 PyUnicode_1BYTE_DATA(unicode), &outpos);
4775 else
4776 ch = ucs1lib_utf8_decode(&s, end,
4777 PyUnicode_1BYTE_DATA(unicode), &outpos);
4778 } else if (kind == PyUnicode_2BYTE_KIND) {
4779 ch = ucs2lib_utf8_decode(&s, end,
4780 PyUnicode_2BYTE_DATA(unicode), &outpos);
4781 } else {
4782 assert(kind == PyUnicode_4BYTE_KIND);
4783 ch = ucs4lib_utf8_decode(&s, end,
4784 PyUnicode_4BYTE_DATA(unicode), &outpos);
4785 }
4786
4787 switch (ch) {
4788 case 0:
4789 if (s == end || consumed)
4790 goto End;
4791 errmsg = "unexpected end of data";
4792 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004793 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004794 break;
4795 case 1:
4796 errmsg = "invalid start byte";
4797 startinpos = s - starts;
4798 endinpos = startinpos + 1;
4799 break;
4800 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004801 case 3:
4802 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004803 errmsg = "invalid continuation byte";
4804 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004805 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806 break;
4807 default:
4808 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4809 goto onError;
4810 continue;
4811 }
4812
4813 if (unicode_decode_call_errorhandler(
4814 errors, &errorHandler,
4815 "utf-8", errmsg,
4816 &starts, &end, &startinpos, &endinpos, &exc, &s,
4817 &unicode, &outpos))
4818 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004819 }
4820
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004821End:
4822 if (unicode_resize(&unicode, outpos) < 0)
4823 goto onError;
4824
4825 if (consumed)
4826 *consumed = s - starts;
4827
4828 Py_XDECREF(errorHandler);
4829 Py_XDECREF(exc);
4830 assert(_PyUnicode_CheckConsistency(unicode, 1));
4831 return unicode;
4832
4833onError:
4834 Py_XDECREF(errorHandler);
4835 Py_XDECREF(exc);
4836 Py_XDECREF(unicode);
4837 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004838}
4839
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840#ifdef __APPLE__
4841
4842/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner27b1ca22012-12-03 12:47:59 +01004843 used to decode the command line arguments on Mac OS X.
4844
4845 Return a pointer to a newly allocated wide character string (use
4846 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004847
4848wchar_t*
4849_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4850{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004851 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852 wchar_t *unicode;
4853 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004854
4855 /* Note: size will always be longer than the resulting Unicode
4856 character count */
Victor Stinner27b1ca22012-12-03 12:47:59 +01004857 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004858 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004859 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4860 if (!unicode)
4861 return NULL;
4862
4863 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004866 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004868#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004869 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004870#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004871 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004872#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004873 if (ch > 0xFF) {
4874#if SIZEOF_WCHAR_T == 4
4875 assert(0);
4876#else
4877 assert(Py_UNICODE_IS_SURROGATE(ch));
4878 /* compute and append the two surrogates: */
4879 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4880 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4881#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004882 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004883 else {
4884 if (!ch && s == e)
4885 break;
4886 /* surrogateescape */
4887 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4888 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004889 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004890 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004891 return unicode;
4892}
4893
4894#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004896/* Primary internal function which creates utf8 encoded bytes objects.
4897
4898 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004899 and allocate exactly as much space needed at the end. Else allocate the
4900 maximum possible needed (4 result bytes per Unicode character), and return
4901 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004902*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004903PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004904_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004905{
Victor Stinner6099a032011-12-18 14:22:26 +01004906 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004907 void *data;
4908 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004910 if (!PyUnicode_Check(unicode)) {
4911 PyErr_BadArgument();
4912 return NULL;
4913 }
4914
4915 if (PyUnicode_READY(unicode) == -1)
4916 return NULL;
4917
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004918 if (PyUnicode_UTF8(unicode))
4919 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4920 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004921
4922 kind = PyUnicode_KIND(unicode);
4923 data = PyUnicode_DATA(unicode);
4924 size = PyUnicode_GET_LENGTH(unicode);
4925
Benjamin Petersonead6b532011-12-20 17:23:42 -06004926 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004927 default:
4928 assert(0);
4929 case PyUnicode_1BYTE_KIND:
4930 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4931 assert(!PyUnicode_IS_ASCII(unicode));
4932 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4933 case PyUnicode_2BYTE_KIND:
4934 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4935 case PyUnicode_4BYTE_KIND:
4936 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004937 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004938}
4939
Alexander Belopolsky40018472011-02-26 01:02:56 +00004940PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004941PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4942 Py_ssize_t size,
4943 const char *errors)
4944{
4945 PyObject *v, *unicode;
4946
4947 unicode = PyUnicode_FromUnicode(s, size);
4948 if (unicode == NULL)
4949 return NULL;
4950 v = _PyUnicode_AsUTF8String(unicode, errors);
4951 Py_DECREF(unicode);
4952 return v;
4953}
4954
4955PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004956PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004957{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004958 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004959}
4960
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961/* --- UTF-32 Codec ------------------------------------------------------- */
4962
4963PyObject *
4964PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004965 Py_ssize_t size,
4966 const char *errors,
4967 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004968{
4969 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4970}
4971
4972PyObject *
4973PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004974 Py_ssize_t size,
4975 const char *errors,
4976 int *byteorder,
4977 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004978{
4979 const char *starts = s;
4980 Py_ssize_t startinpos;
4981 Py_ssize_t endinpos;
4982 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004983 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004984 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004985 int bo = 0; /* assume native ordering by default */
4986 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004987 /* Offsets from q for retrieving bytes in the right order. */
4988#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4989 int iorder[] = {0, 1, 2, 3};
4990#else
4991 int iorder[] = {3, 2, 1, 0};
4992#endif
4993 PyObject *errorHandler = NULL;
4994 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004995
Walter Dörwald41980ca2007-08-16 21:55:45 +00004996 q = (unsigned char *)s;
4997 e = q + size;
4998
4999 if (byteorder)
5000 bo = *byteorder;
5001
5002 /* Check for BOM marks (U+FEFF) in the input and adjust current
5003 byte order setting accordingly. In native mode, the leading BOM
5004 mark is skipped, in all other modes, it is copied to the output
5005 stream as-is (giving a ZWNBSP character). */
5006 if (bo == 0) {
5007 if (size >= 4) {
5008 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005010#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005011 if (bom == 0x0000FEFF) {
5012 q += 4;
5013 bo = -1;
5014 }
5015 else if (bom == 0xFFFE0000) {
5016 q += 4;
5017 bo = 1;
5018 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 if (bom == 0x0000FEFF) {
5021 q += 4;
5022 bo = 1;
5023 }
5024 else if (bom == 0xFFFE0000) {
5025 q += 4;
5026 bo = -1;
5027 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005028#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005030 }
5031
5032 if (bo == -1) {
5033 /* force LE */
5034 iorder[0] = 0;
5035 iorder[1] = 1;
5036 iorder[2] = 2;
5037 iorder[3] = 3;
5038 }
5039 else if (bo == 1) {
5040 /* force BE */
5041 iorder[0] = 3;
5042 iorder[1] = 2;
5043 iorder[2] = 1;
5044 iorder[3] = 0;
5045 }
5046
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005047 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005048 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005049 if (!unicode)
5050 return NULL;
5051 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005052 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005053 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005054
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 Py_UCS4 ch;
5057 /* remaining bytes at the end? (size should be divisible by 4) */
5058 if (e-q<4) {
5059 if (consumed)
5060 break;
5061 errmsg = "truncated data";
5062 startinpos = ((const char *)q)-starts;
5063 endinpos = ((const char *)e)-starts;
5064 goto utf32Error;
5065 /* The remaining input chars are ignored if the callback
5066 chooses to skip the input */
5067 }
5068 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5069 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070
Benjamin Peterson29060642009-01-31 22:14:21 +00005071 if (ch >= 0x110000)
5072 {
5073 errmsg = "codepoint not in range(0x110000)";
5074 startinpos = ((const char *)q)-starts;
5075 endinpos = startinpos+4;
5076 goto utf32Error;
5077 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005078 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5079 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 q += 4;
5081 continue;
5082 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005083 if (unicode_decode_call_errorhandler(
5084 errors, &errorHandler,
5085 "utf32", errmsg,
5086 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005087 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005088 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089 }
5090
5091 if (byteorder)
5092 *byteorder = bo;
5093
5094 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005095 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096
5097 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005098 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005099 goto onError;
5100
5101 Py_XDECREF(errorHandler);
5102 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005103 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104
Benjamin Peterson29060642009-01-31 22:14:21 +00005105 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106 Py_DECREF(unicode);
5107 Py_XDECREF(errorHandler);
5108 Py_XDECREF(exc);
5109 return NULL;
5110}
5111
5112PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005113_PyUnicode_EncodeUTF32(PyObject *str,
5114 const char *errors,
5115 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005116{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005117 int kind;
5118 void *data;
5119 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005120 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005122 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005123 /* Offsets from p for storing byte pairs in the right order. */
5124#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5125 int iorder[] = {0, 1, 2, 3};
5126#else
5127 int iorder[] = {3, 2, 1, 0};
5128#endif
5129
Benjamin Peterson29060642009-01-31 22:14:21 +00005130#define STORECHAR(CH) \
5131 do { \
5132 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5133 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5134 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5135 p[iorder[0]] = (CH) & 0xff; \
5136 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005137 } while(0)
5138
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005139 if (!PyUnicode_Check(str)) {
5140 PyErr_BadArgument();
5141 return NULL;
5142 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005143 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005144 return NULL;
5145 kind = PyUnicode_KIND(str);
5146 data = PyUnicode_DATA(str);
5147 len = PyUnicode_GET_LENGTH(str);
5148
5149 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005150 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005151 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005152 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153 if (v == NULL)
5154 return NULL;
5155
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005156 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005157 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005159 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005160 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005161
5162 if (byteorder == -1) {
5163 /* force LE */
5164 iorder[0] = 0;
5165 iorder[1] = 1;
5166 iorder[2] = 2;
5167 iorder[3] = 3;
5168 }
5169 else if (byteorder == 1) {
5170 /* force BE */
5171 iorder[0] = 3;
5172 iorder[1] = 2;
5173 iorder[2] = 1;
5174 iorder[3] = 0;
5175 }
5176
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005177 for (i = 0; i < len; i++)
5178 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005179
5180 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005181 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005182#undef STORECHAR
5183}
5184
Alexander Belopolsky40018472011-02-26 01:02:56 +00005185PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005186PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5187 Py_ssize_t size,
5188 const char *errors,
5189 int byteorder)
5190{
5191 PyObject *result;
5192 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5193 if (tmp == NULL)
5194 return NULL;
5195 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5196 Py_DECREF(tmp);
5197 return result;
5198}
5199
5200PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005201PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005202{
Victor Stinnerb960b342011-11-20 19:12:52 +01005203 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005204}
5205
Guido van Rossumd57fd912000-03-10 22:53:23 +00005206/* --- UTF-16 Codec ------------------------------------------------------- */
5207
Tim Peters772747b2001-08-09 22:21:55 +00005208PyObject *
5209PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 Py_ssize_t size,
5211 const char *errors,
5212 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213{
Walter Dörwald69652032004-09-07 20:24:22 +00005214 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5215}
5216
5217PyObject *
5218PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 Py_ssize_t size,
5220 const char *errors,
5221 int *byteorder,
5222 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005223{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005224 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005225 Py_ssize_t startinpos;
5226 Py_ssize_t endinpos;
5227 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005228 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005229 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005230 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005231 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005232 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005233 PyObject *errorHandler = NULL;
5234 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005235
Tim Peters772747b2001-08-09 22:21:55 +00005236 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005237 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005238
5239 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005240 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005241
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005242 /* Check for BOM marks (U+FEFF) in the input and adjust current
5243 byte order setting accordingly. In native mode, the leading BOM
5244 mark is skipped, in all other modes, it is copied to the output
5245 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005246 if (bo == 0 && size >= 2) {
5247 const Py_UCS4 bom = (q[1] << 8) | q[0];
5248 if (bom == 0xFEFF) {
5249 q += 2;
5250 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005251 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005252 else if (bom == 0xFFFE) {
5253 q += 2;
5254 bo = 1;
5255 }
5256 if (byteorder)
5257 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005259
Antoine Pitrou63065d72012-05-15 23:48:04 +02005260 if (q == e) {
5261 if (consumed)
5262 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005263 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005264 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005265
Antoine Pitrouab868312009-01-10 15:40:25 +00005266#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005267 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005268#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005269 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005270#endif
Tim Peters772747b2001-08-09 22:21:55 +00005271
Antoine Pitrou63065d72012-05-15 23:48:04 +02005272 /* Note: size will always be longer than the resulting Unicode
5273 character count */
5274 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5275 if (!unicode)
5276 return NULL;
5277
5278 outpos = 0;
5279 while (1) {
5280 Py_UCS4 ch = 0;
5281 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005282 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005283 if (kind == PyUnicode_1BYTE_KIND) {
5284 if (PyUnicode_IS_ASCII(unicode))
5285 ch = asciilib_utf16_decode(&q, e,
5286 PyUnicode_1BYTE_DATA(unicode), &outpos,
5287 native_ordering);
5288 else
5289 ch = ucs1lib_utf16_decode(&q, e,
5290 PyUnicode_1BYTE_DATA(unicode), &outpos,
5291 native_ordering);
5292 } else if (kind == PyUnicode_2BYTE_KIND) {
5293 ch = ucs2lib_utf16_decode(&q, e,
5294 PyUnicode_2BYTE_DATA(unicode), &outpos,
5295 native_ordering);
5296 } else {
5297 assert(kind == PyUnicode_4BYTE_KIND);
5298 ch = ucs4lib_utf16_decode(&q, e,
5299 PyUnicode_4BYTE_DATA(unicode), &outpos,
5300 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005301 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005302 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005303
Antoine Pitrou63065d72012-05-15 23:48:04 +02005304 switch (ch)
5305 {
5306 case 0:
5307 /* remaining byte at the end? (size should be even) */
5308 if (q == e || consumed)
5309 goto End;
5310 errmsg = "truncated data";
5311 startinpos = ((const char *)q) - starts;
5312 endinpos = ((const char *)e) - starts;
5313 break;
5314 /* The remaining input chars are ignored if the callback
5315 chooses to skip the input */
5316 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005317 q -= 2;
5318 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005319 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005320 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005321 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005322 endinpos = ((const char *)e) - starts;
5323 break;
5324 case 2:
5325 errmsg = "illegal encoding";
5326 startinpos = ((const char *)q) - 2 - starts;
5327 endinpos = startinpos + 2;
5328 break;
5329 case 3:
5330 errmsg = "illegal UTF-16 surrogate";
5331 startinpos = ((const char *)q) - 4 - starts;
5332 endinpos = startinpos + 2;
5333 break;
5334 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005335 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5336 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 continue;
5338 }
5339
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005341 errors,
5342 &errorHandler,
5343 "utf16", errmsg,
5344 &starts,
5345 (const char **)&e,
5346 &startinpos,
5347 &endinpos,
5348 &exc,
5349 (const char **)&q,
5350 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005351 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005353 }
5354
Antoine Pitrou63065d72012-05-15 23:48:04 +02005355End:
Walter Dörwald69652032004-09-07 20:24:22 +00005356 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005358
Guido van Rossumd57fd912000-03-10 22:53:23 +00005359 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005360 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005361 goto onError;
5362
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005363 Py_XDECREF(errorHandler);
5364 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005365 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005366
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005368 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005369 Py_XDECREF(errorHandler);
5370 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005371 return NULL;
5372}
5373
Tim Peters772747b2001-08-09 22:21:55 +00005374PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005375_PyUnicode_EncodeUTF16(PyObject *str,
5376 const char *errors,
5377 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005378{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005379 enum PyUnicode_Kind kind;
5380 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005382 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005383 unsigned short *out;
5384 Py_ssize_t bytesize;
5385 Py_ssize_t pairs;
5386#ifdef WORDS_BIGENDIAN
5387 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005388#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005389 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005390#endif
5391
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005392 if (!PyUnicode_Check(str)) {
5393 PyErr_BadArgument();
5394 return NULL;
5395 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005396 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005397 return NULL;
5398 kind = PyUnicode_KIND(str);
5399 data = PyUnicode_DATA(str);
5400 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005401
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005402 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005403 if (kind == PyUnicode_4BYTE_KIND) {
5404 const Py_UCS4 *in = (const Py_UCS4 *)data;
5405 const Py_UCS4 *end = in + len;
5406 while (in < end)
5407 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005408 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005409 }
5410 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005411 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005412 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005413 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005414 if (v == NULL)
5415 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005417 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005418 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005419 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005421 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005422 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005423 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005424
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005425 switch (kind) {
5426 case PyUnicode_1BYTE_KIND: {
5427 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5428 break;
Tim Peters772747b2001-08-09 22:21:55 +00005429 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005430 case PyUnicode_2BYTE_KIND: {
5431 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5432 break;
Tim Peters772747b2001-08-09 22:21:55 +00005433 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005434 case PyUnicode_4BYTE_KIND: {
5435 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5436 break;
5437 }
5438 default:
5439 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005440 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005441
5442 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005443 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444}
5445
Alexander Belopolsky40018472011-02-26 01:02:56 +00005446PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005447PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5448 Py_ssize_t size,
5449 const char *errors,
5450 int byteorder)
5451{
5452 PyObject *result;
5453 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5454 if (tmp == NULL)
5455 return NULL;
5456 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5457 Py_DECREF(tmp);
5458 return result;
5459}
5460
5461PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005462PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005463{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005464 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005465}
5466
5467/* --- Unicode Escape Codec ----------------------------------------------- */
5468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005469/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5470 if all the escapes in the string make it still a valid ASCII string.
5471 Returns -1 if any escapes were found which cause the string to
5472 pop out of ASCII range. Otherwise returns the length of the
5473 required buffer to hold the string.
5474 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005475static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005476length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5477{
5478 const unsigned char *p = (const unsigned char *)s;
5479 const unsigned char *end = p + size;
5480 Py_ssize_t length = 0;
5481
5482 if (size < 0)
5483 return -1;
5484
5485 for (; p < end; ++p) {
5486 if (*p > 127) {
5487 /* Non-ASCII */
5488 return -1;
5489 }
5490 else if (*p != '\\') {
5491 /* Normal character */
5492 ++length;
5493 }
5494 else {
5495 /* Backslash-escape, check next char */
5496 ++p;
5497 /* Escape sequence reaches till end of string or
5498 non-ASCII follow-up. */
5499 if (p >= end || *p > 127)
5500 return -1;
5501 switch (*p) {
5502 case '\n':
5503 /* backslash + \n result in zero characters */
5504 break;
5505 case '\\': case '\'': case '\"':
5506 case 'b': case 'f': case 't':
5507 case 'n': case 'r': case 'v': case 'a':
5508 ++length;
5509 break;
5510 case '0': case '1': case '2': case '3':
5511 case '4': case '5': case '6': case '7':
5512 case 'x': case 'u': case 'U': case 'N':
5513 /* these do not guarantee ASCII characters */
5514 return -1;
5515 default:
5516 /* count the backslash + the other character */
5517 length += 2;
5518 }
5519 }
5520 }
5521 return length;
5522}
5523
Fredrik Lundh06d12682001-01-24 07:59:11 +00005524static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005525
Alexander Belopolsky40018472011-02-26 01:02:56 +00005526PyObject *
5527PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005528 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005529 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005531 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005532 Py_ssize_t startinpos;
5533 Py_ssize_t endinpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005534 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005535 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005536 char* message;
5537 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005538 PyObject *errorHandler = NULL;
5539 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005540 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005541 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005542
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005543 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544
5545 /* After length_of_escaped_ascii_string() there are two alternatives,
5546 either the string is pure ASCII with named escapes like \n, etc.
5547 and we determined it's exact size (common case)
5548 or it contains \x, \u, ... escape sequences. then we create a
5549 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005550 if (len >= 0) {
5551 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005552 if (!v)
5553 goto onError;
5554 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005555 }
5556 else {
5557 /* Escaped strings will always be longer than the resulting
5558 Unicode string, so we start with size here and then reduce the
5559 length after conversion to the true value.
5560 (but if the error callback returns a long replacement string
5561 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005562 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005563 if (!v)
5564 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005565 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005566 }
5567
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005569 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005570 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005572
Guido van Rossumd57fd912000-03-10 22:53:23 +00005573 while (s < end) {
5574 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005575 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005576 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005578 /* The only case in which i == ascii_length is a backslash
5579 followed by a newline. */
5580 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005581
Guido van Rossumd57fd912000-03-10 22:53:23 +00005582 /* Non-escape characters are interpreted as Unicode ordinals */
5583 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005584 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5585 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586 continue;
5587 }
5588
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005589 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590 /* \ - Escapes */
5591 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005592 c = *s++;
5593 if (s > end)
5594 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005595
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005596 /* The only case in which i == ascii_length is a backslash
5597 followed by a newline. */
5598 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005599
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005600 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601
Benjamin Peterson29060642009-01-31 22:14:21 +00005602 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005603#define WRITECHAR(ch) \
5604 do { \
5605 if (unicode_putchar(&v, &i, ch) < 0) \
5606 goto onError; \
5607 }while(0)
5608
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005610 case '\\': WRITECHAR('\\'); break;
5611 case '\'': WRITECHAR('\''); break;
5612 case '\"': WRITECHAR('\"'); break;
5613 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005614 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005615 case 'f': WRITECHAR('\014'); break;
5616 case 't': WRITECHAR('\t'); break;
5617 case 'n': WRITECHAR('\n'); break;
5618 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005619 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005620 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005621 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005622 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623
Benjamin Peterson29060642009-01-31 22:14:21 +00005624 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625 case '0': case '1': case '2': case '3':
5626 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005627 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005628 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005629 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005630 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005631 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005633 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634 break;
5635
Benjamin Peterson29060642009-01-31 22:14:21 +00005636 /* hex escapes */
5637 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005638 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005639 digits = 2;
5640 message = "truncated \\xXX escape";
5641 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005645 digits = 4;
5646 message = "truncated \\uXXXX escape";
5647 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005648
Benjamin Peterson29060642009-01-31 22:14:21 +00005649 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005650 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005651 digits = 8;
5652 message = "truncated \\UXXXXXXXX escape";
5653 hexescape:
5654 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005655 if (end - s < digits) {
5656 /* count only hex digits */
5657 for (; s < end; ++s) {
5658 c = (unsigned char)*s;
5659 if (!Py_ISXDIGIT(c))
5660 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005661 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005662 goto error;
5663 }
5664 for (; digits--; ++s) {
5665 c = (unsigned char)*s;
5666 if (!Py_ISXDIGIT(c))
5667 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005668 chr = (chr<<4) & ~0xF;
5669 if (c >= '0' && c <= '9')
5670 chr += c - '0';
5671 else if (c >= 'a' && c <= 'f')
5672 chr += 10 + c - 'a';
5673 else
5674 chr += 10 + c - 'A';
5675 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005676 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005677 /* _decoding_error will have already written into the
5678 target buffer. */
5679 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005680 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005681 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005682 message = "illegal Unicode character";
5683 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005684 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005685 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005686 break;
5687
Benjamin Peterson29060642009-01-31 22:14:21 +00005688 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005689 case 'N':
5690 message = "malformed \\N character escape";
5691 if (ucnhash_CAPI == NULL) {
5692 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005693 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5694 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005695 if (ucnhash_CAPI == NULL)
5696 goto ucnhashError;
5697 }
5698 if (*s == '{') {
5699 const char *start = s+1;
5700 /* look for the closing brace */
5701 while (*s != '}' && s < end)
5702 s++;
5703 if (s > start && s < end && *s == '}') {
5704 /* found a name. look it up in the unicode database */
5705 message = "unknown Unicode character name";
5706 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005707 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005708 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005709 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005710 goto store;
5711 }
5712 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005713 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005714
5715 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005716 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005717 message = "\\ at end of string";
5718 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005719 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005720 }
5721 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005722 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005723 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005724 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005725 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005727 continue;
5728
5729 error:
5730 endinpos = s-starts;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005731 if (unicode_decode_call_errorhandler(
5732 errors, &errorHandler,
5733 "unicodeescape", message,
5734 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005735 &v, &i))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005736 goto onError;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005737 len = PyUnicode_GET_LENGTH(v);
Serhiy Storchakad6793772013-01-29 10:20:44 +02005738 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005740#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005741
Victor Stinner16e6a802011-12-12 13:24:15 +01005742 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005743 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005744 Py_XDECREF(errorHandler);
5745 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005746 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005749 PyErr_SetString(
5750 PyExc_UnicodeError,
5751 "\\N escapes not supported (can't load unicodedata module)"
5752 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005753 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005754 Py_XDECREF(errorHandler);
5755 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005756 return NULL;
5757
Benjamin Peterson29060642009-01-31 22:14:21 +00005758 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005760 Py_XDECREF(errorHandler);
5761 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005762 return NULL;
5763}
5764
5765/* Return a Unicode-Escape string version of the Unicode object.
5766
5767 If quotes is true, the string is enclosed in u"" or u'' quotes as
5768 appropriate.
5769
5770*/
5771
Alexander Belopolsky40018472011-02-26 01:02:56 +00005772PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005773PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005774{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005775 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005776 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005778 int kind;
5779 void *data;
5780 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005781
Ezio Melottie7f90372012-10-05 03:33:31 +03005782 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005783 escape.
5784
Ezio Melottie7f90372012-10-05 03:33:31 +03005785 For UCS1 strings it's '\xxx', 4 bytes per source character.
5786 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5787 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005788 */
5789
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005790 if (!PyUnicode_Check(unicode)) {
5791 PyErr_BadArgument();
5792 return NULL;
5793 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005794 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005795 return NULL;
5796 len = PyUnicode_GET_LENGTH(unicode);
5797 kind = PyUnicode_KIND(unicode);
5798 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005799 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005800 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5801 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5802 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5803 }
5804
5805 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005806 return PyBytes_FromStringAndSize(NULL, 0);
5807
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005808 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005809 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005810
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005811 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005812 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005813 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005814 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005815 if (repr == NULL)
5816 return NULL;
5817
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005818 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005819
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005820 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005821 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005822
Walter Dörwald79e913e2007-05-12 11:08:06 +00005823 /* Escape backslashes */
5824 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005825 *p++ = '\\';
5826 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005827 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005828 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005829
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005830 /* Map 21-bit characters to '\U00xxxxxx' */
5831 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005832 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005833 *p++ = '\\';
5834 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005835 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5836 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5837 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5838 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5839 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5840 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5841 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5842 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005844 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005845
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005847 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 *p++ = '\\';
5849 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005850 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5851 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5852 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5853 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005855
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005856 /* Map special whitespace to '\t', \n', '\r' */
5857 else if (ch == '\t') {
5858 *p++ = '\\';
5859 *p++ = 't';
5860 }
5861 else if (ch == '\n') {
5862 *p++ = '\\';
5863 *p++ = 'n';
5864 }
5865 else if (ch == '\r') {
5866 *p++ = '\\';
5867 *p++ = 'r';
5868 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005869
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005870 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005871 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005873 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005874 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5875 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005876 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005877
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 /* Copy everything else as-is */
5879 else
5880 *p++ = (char) ch;
5881 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005883 assert(p - PyBytes_AS_STRING(repr) > 0);
5884 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5885 return NULL;
5886 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887}
5888
Alexander Belopolsky40018472011-02-26 01:02:56 +00005889PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005890PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5891 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005893 PyObject *result;
5894 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5895 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005897 result = PyUnicode_AsUnicodeEscapeString(tmp);
5898 Py_DECREF(tmp);
5899 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900}
5901
5902/* --- Raw Unicode Escape Codec ------------------------------------------- */
5903
Alexander Belopolsky40018472011-02-26 01:02:56 +00005904PyObject *
5905PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005906 Py_ssize_t size,
5907 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005909 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005910 Py_ssize_t startinpos;
5911 Py_ssize_t endinpos;
5912 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005913 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 const char *end;
5915 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005916 PyObject *errorHandler = NULL;
5917 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005918
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 /* Escaped strings will always be longer than the resulting
5920 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005921 length after conversion to the true value. (But decoding error
5922 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005923 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005927 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005928 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 end = s + size;
5930 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005931 unsigned char c;
5932 Py_UCS4 x;
5933 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005934 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 /* Non-escape characters are interpreted as Unicode ordinals */
5937 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005938 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5939 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005941 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 startinpos = s-starts;
5943
5944 /* \u-escapes are only interpreted iff the number of leading
5945 backslashes if odd */
5946 bs = s;
5947 for (;s < end;) {
5948 if (*s != '\\')
5949 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005950 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5951 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 }
5953 if (((s - bs) & 1) == 0 ||
5954 s >= end ||
5955 (*s != 'u' && *s != 'U')) {
5956 continue;
5957 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005958 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 count = *s=='u' ? 4 : 8;
5960 s++;
5961
5962 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 for (x = 0, i = 0; i < count; ++i, ++s) {
5964 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005965 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005966 endinpos = s-starts;
5967 if (unicode_decode_call_errorhandler(
5968 errors, &errorHandler,
5969 "rawunicodeescape", "truncated \\uXXXX",
5970 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005971 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005972 goto onError;
5973 goto nextByte;
5974 }
5975 x = (x<<4) & ~0xF;
5976 if (c >= '0' && c <= '9')
5977 x += c - '0';
5978 else if (c >= 'a' && c <= 'f')
5979 x += 10 + c - 'a';
5980 else
5981 x += 10 + c - 'A';
5982 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005983 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005984 if (unicode_putchar(&v, &outpos, x) < 0)
5985 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005986 } else {
5987 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005988 if (unicode_decode_call_errorhandler(
5989 errors, &errorHandler,
5990 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005992 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005994 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 nextByte:
5996 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005998 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006000 Py_XDECREF(errorHandler);
6001 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006002 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006003
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006006 Py_XDECREF(errorHandler);
6007 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 return NULL;
6009}
6010
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006011
Alexander Belopolsky40018472011-02-26 01:02:56 +00006012PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006013PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006015 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016 char *p;
6017 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006018 Py_ssize_t expandsize, pos;
6019 int kind;
6020 void *data;
6021 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006023 if (!PyUnicode_Check(unicode)) {
6024 PyErr_BadArgument();
6025 return NULL;
6026 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006027 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006028 return NULL;
6029 kind = PyUnicode_KIND(unicode);
6030 data = PyUnicode_DATA(unicode);
6031 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006032 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6033 bytes, and 1 byte characters 4. */
6034 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006035
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006037 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006038
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006039 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040 if (repr == NULL)
6041 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006043 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006045 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006046 for (pos = 0; pos < len; pos++) {
6047 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 /* Map 32-bit characters to '\Uxxxxxxxx' */
6049 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006050 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006051 *p++ = '\\';
6052 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006053 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6054 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6055 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6056 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6057 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6058 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6059 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6060 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006061 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006062 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006063 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 *p++ = '\\';
6065 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006066 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6067 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6068 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6069 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006071 /* Copy everything else as-is */
6072 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 *p++ = (char) ch;
6074 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006075
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006076 assert(p > q);
6077 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006078 return NULL;
6079 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080}
6081
Alexander Belopolsky40018472011-02-26 01:02:56 +00006082PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006083PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6084 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006086 PyObject *result;
6087 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6088 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006089 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006090 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6091 Py_DECREF(tmp);
6092 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093}
6094
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006095/* --- Unicode Internal Codec ------------------------------------------- */
6096
Alexander Belopolsky40018472011-02-26 01:02:56 +00006097PyObject *
6098_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006099 Py_ssize_t size,
6100 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006101{
6102 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006103 Py_ssize_t startinpos;
6104 Py_ssize_t endinpos;
6105 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006106 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006107 const char *end;
6108 const char *reason;
6109 PyObject *errorHandler = NULL;
6110 PyObject *exc = NULL;
6111
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006112 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006113 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006114 1))
6115 return NULL;
6116
Thomas Wouters89f507f2006-12-13 04:49:30 +00006117 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006118 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006119 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006121 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006122 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006123 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006124 end = s + size;
6125
6126 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006127 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006128 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006129 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006130 endinpos = end-starts;
6131 reason = "truncated input";
6132 goto error;
6133 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006134 /* We copy the raw representation one byte at a time because the
6135 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006136 ((char *) &uch)[0] = s[0];
6137 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006138#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006139 ((char *) &uch)[2] = s[2];
6140 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006141#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006142 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006143#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006144 /* We have to sanity check the raw data, otherwise doom looms for
6145 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006146 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006147 endinpos = s - starts + Py_UNICODE_SIZE;
6148 reason = "illegal code point (> 0x10FFFF)";
6149 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006150 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006151#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006152 s += Py_UNICODE_SIZE;
6153#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006154 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006155 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006156 Py_UNICODE uch2;
6157 ((char *) &uch2)[0] = s[0];
6158 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006159 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006160 {
Victor Stinner551ac952011-11-29 22:58:13 +01006161 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006162 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006163 }
6164 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006165#endif
6166
6167 if (unicode_putchar(&v, &outpos, ch) < 0)
6168 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006169 continue;
6170
6171 error:
6172 startinpos = s - starts;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006173 if (unicode_decode_call_errorhandler(
6174 errors, &errorHandler,
6175 "unicode_internal", reason,
6176 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006177 &v, &outpos))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006178 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006179 }
6180
Victor Stinner16e6a802011-12-12 13:24:15 +01006181 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006182 goto onError;
6183 Py_XDECREF(errorHandler);
6184 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006185 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006186
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006188 Py_XDECREF(v);
6189 Py_XDECREF(errorHandler);
6190 Py_XDECREF(exc);
6191 return NULL;
6192}
6193
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194/* --- Latin-1 Codec ------------------------------------------------------ */
6195
Alexander Belopolsky40018472011-02-26 01:02:56 +00006196PyObject *
6197PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006198 Py_ssize_t size,
6199 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006202 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203}
6204
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006205/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006206static void
6207make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006208 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006209 PyObject *unicode,
6210 Py_ssize_t startpos, Py_ssize_t endpos,
6211 const char *reason)
6212{
6213 if (*exceptionObject == NULL) {
6214 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006215 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006216 encoding, unicode, startpos, endpos, reason);
6217 }
6218 else {
6219 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6220 goto onError;
6221 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6222 goto onError;
6223 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6224 goto onError;
6225 return;
6226 onError:
6227 Py_DECREF(*exceptionObject);
6228 *exceptionObject = NULL;
6229 }
6230}
6231
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006232/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006233static void
6234raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006235 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006236 PyObject *unicode,
6237 Py_ssize_t startpos, Py_ssize_t endpos,
6238 const char *reason)
6239{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006240 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006241 encoding, unicode, startpos, endpos, reason);
6242 if (*exceptionObject != NULL)
6243 PyCodec_StrictErrors(*exceptionObject);
6244}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006245
6246/* error handling callback helper:
6247 build arguments, call the callback and check the arguments,
6248 put the result into newpos and return the replacement string, which
6249 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006250static PyObject *
6251unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006252 PyObject **errorHandler,
6253 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006254 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006255 Py_ssize_t startpos, Py_ssize_t endpos,
6256 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006257{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006258 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006259 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006260 PyObject *restuple;
6261 PyObject *resunicode;
6262
6263 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006265 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 }
6268
Benjamin Petersonbac79492012-01-14 13:34:47 -05006269 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006270 return NULL;
6271 len = PyUnicode_GET_LENGTH(unicode);
6272
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006273 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006274 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006275 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006277
6278 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006282 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006283 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006284 Py_DECREF(restuple);
6285 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006286 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006287 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006288 &resunicode, newpos)) {
6289 Py_DECREF(restuple);
6290 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006291 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006292 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6293 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6294 Py_DECREF(restuple);
6295 return NULL;
6296 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006297 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006298 *newpos = len + *newpos;
6299 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6301 Py_DECREF(restuple);
6302 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006303 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006304 Py_INCREF(resunicode);
6305 Py_DECREF(restuple);
6306 return resunicode;
6307}
6308
Alexander Belopolsky40018472011-02-26 01:02:56 +00006309static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006310unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006311 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006312 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006313{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006314 /* input state */
6315 Py_ssize_t pos=0, size;
6316 int kind;
6317 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006318 /* output object */
6319 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320 /* pointer into the output */
6321 char *str;
6322 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006323 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006324 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6325 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 PyObject *errorHandler = NULL;
6327 PyObject *exc = NULL;
6328 /* the following variable is used for caching string comparisons
6329 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6330 int known_errorHandler = -1;
6331
Benjamin Petersonbac79492012-01-14 13:34:47 -05006332 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006333 return NULL;
6334 size = PyUnicode_GET_LENGTH(unicode);
6335 kind = PyUnicode_KIND(unicode);
6336 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337 /* allocate enough for a simple encoding without
6338 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006339 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006340 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006341 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006342 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006343 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006344 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006345 ressize = size;
6346
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006347 while (pos < size) {
6348 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349
Benjamin Peterson29060642009-01-31 22:14:21 +00006350 /* can we encode this? */
6351 if (c<limit) {
6352 /* no overflow check, because we know that the space is enough */
6353 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006354 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006355 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006356 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 Py_ssize_t requiredsize;
6358 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 Py_ssize_t collstart = pos;
6362 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006364 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 ++collend;
6366 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6367 if (known_errorHandler==-1) {
6368 if ((errors==NULL) || (!strcmp(errors, "strict")))
6369 known_errorHandler = 1;
6370 else if (!strcmp(errors, "replace"))
6371 known_errorHandler = 2;
6372 else if (!strcmp(errors, "ignore"))
6373 known_errorHandler = 3;
6374 else if (!strcmp(errors, "xmlcharrefreplace"))
6375 known_errorHandler = 4;
6376 else
6377 known_errorHandler = 0;
6378 }
6379 switch (known_errorHandler) {
6380 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006381 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006382 goto onError;
6383 case 2: /* replace */
6384 while (collstart++<collend)
6385 *str++ = '?'; /* fall through */
6386 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006387 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 break;
6389 case 4: /* xmlcharrefreplace */
6390 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006391 /* determine replacement size */
6392 for (i = collstart, repsize = 0; i < collend; ++i) {
6393 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6394 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006397 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006398 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006399 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006400 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006404 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006406 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006407 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006409 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 if (requiredsize > ressize) {
6413 if (requiredsize<2*ressize)
6414 requiredsize = 2*ressize;
6415 if (_PyBytes_Resize(&res, requiredsize))
6416 goto onError;
6417 str = PyBytes_AS_STRING(res) + respos;
6418 ressize = requiredsize;
6419 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 /* generate replacement */
6421 for (i = collstart; i < collend; ++i) {
6422 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006424 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 break;
6426 default:
6427 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006428 encoding, reason, unicode, &exc,
6429 collstart, collend, &newpos);
6430 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006431 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006433 if (PyBytes_Check(repunicode)) {
6434 /* Directly copy bytes result to output. */
6435 repsize = PyBytes_Size(repunicode);
6436 if (repsize > 1) {
6437 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006438 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006439 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6440 Py_DECREF(repunicode);
6441 goto onError;
6442 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006443 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006444 ressize += repsize-1;
6445 }
6446 memcpy(str, PyBytes_AsString(repunicode), repsize);
6447 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006449 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006450 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006451 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006452 /* need more space? (at least enough for what we
6453 have+the replacement+the rest of the string, so
6454 we won't have to check space for encodable characters) */
6455 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006456 repsize = PyUnicode_GET_LENGTH(repunicode);
6457 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 if (requiredsize > ressize) {
6459 if (requiredsize<2*ressize)
6460 requiredsize = 2*ressize;
6461 if (_PyBytes_Resize(&res, requiredsize)) {
6462 Py_DECREF(repunicode);
6463 goto onError;
6464 }
6465 str = PyBytes_AS_STRING(res) + respos;
6466 ressize = requiredsize;
6467 }
6468 /* check if there is anything unencodable in the replacement
6469 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006470 for (i = 0; repsize-->0; ++i, ++str) {
6471 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006473 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 Py_DECREF(repunicode);
6476 goto onError;
6477 }
6478 *str = (char)c;
6479 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006480 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006481 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006483 }
6484 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006485 /* Resize if we allocated to much */
6486 size = str - PyBytes_AS_STRING(res);
6487 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006488 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006489 if (_PyBytes_Resize(&res, size) < 0)
6490 goto onError;
6491 }
6492
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493 Py_XDECREF(errorHandler);
6494 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006495 return res;
6496
6497 onError:
6498 Py_XDECREF(res);
6499 Py_XDECREF(errorHandler);
6500 Py_XDECREF(exc);
6501 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006502}
6503
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006505PyObject *
6506PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006507 Py_ssize_t size,
6508 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 PyObject *result;
6511 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6512 if (unicode == NULL)
6513 return NULL;
6514 result = unicode_encode_ucs1(unicode, errors, 256);
6515 Py_DECREF(unicode);
6516 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006517}
6518
Alexander Belopolsky40018472011-02-26 01:02:56 +00006519PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006520_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006521{
6522 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 PyErr_BadArgument();
6524 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006526 if (PyUnicode_READY(unicode) == -1)
6527 return NULL;
6528 /* Fast path: if it is a one-byte string, construct
6529 bytes object directly. */
6530 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6531 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6532 PyUnicode_GET_LENGTH(unicode));
6533 /* Non-Latin-1 characters present. Defer to above function to
6534 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006536}
6537
6538PyObject*
6539PyUnicode_AsLatin1String(PyObject *unicode)
6540{
6541 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542}
6543
6544/* --- 7-bit ASCII Codec -------------------------------------------------- */
6545
Alexander Belopolsky40018472011-02-26 01:02:56 +00006546PyObject *
6547PyUnicode_DecodeASCII(const char *s,
6548 Py_ssize_t size,
6549 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006550{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006551 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006552 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006553 int kind;
6554 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006555 Py_ssize_t startinpos;
6556 Py_ssize_t endinpos;
6557 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006558 const char *e;
6559 PyObject *errorHandler = NULL;
6560 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006561
Guido van Rossumd57fd912000-03-10 22:53:23 +00006562 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006563 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006564
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006566 if (size == 1 && (unsigned char)s[0] < 128)
6567 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006568
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006569 unicode = PyUnicode_New(size, 127);
6570 if (unicode == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006573 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006574 data = PyUnicode_1BYTE_DATA(unicode);
6575 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6576 if (outpos == size)
6577 return unicode;
6578
6579 s += outpos;
6580 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 register unsigned char c = (unsigned char)*s;
6583 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006584 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 ++s;
6586 }
6587 else {
6588 startinpos = s-starts;
6589 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 if (unicode_decode_call_errorhandler(
6591 errors, &errorHandler,
6592 "ascii", "ordinal not in range(128)",
6593 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006594 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006596 kind = PyUnicode_KIND(unicode);
6597 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006599 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006600 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006601 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006602 Py_XDECREF(errorHandler);
6603 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006604 assert(_PyUnicode_CheckConsistency(unicode, 1));
6605 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006606
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006608 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609 Py_XDECREF(errorHandler);
6610 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006611 return NULL;
6612}
6613
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006615PyObject *
6616PyUnicode_EncodeASCII(const Py_UNICODE *p,
6617 Py_ssize_t size,
6618 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620 PyObject *result;
6621 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6622 if (unicode == NULL)
6623 return NULL;
6624 result = unicode_encode_ucs1(unicode, errors, 128);
6625 Py_DECREF(unicode);
6626 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627}
6628
Alexander Belopolsky40018472011-02-26 01:02:56 +00006629PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006630_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631{
6632 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 PyErr_BadArgument();
6634 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006636 if (PyUnicode_READY(unicode) == -1)
6637 return NULL;
6638 /* Fast path: if it is an ASCII-only string, construct bytes object
6639 directly. Else defer to above function to raise the exception. */
6640 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6641 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6642 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006644}
6645
6646PyObject *
6647PyUnicode_AsASCIIString(PyObject *unicode)
6648{
6649 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650}
6651
Victor Stinner99b95382011-07-04 14:23:54 +02006652#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006653
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006654/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006655
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006656#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006657#define NEED_RETRY
6658#endif
6659
Victor Stinner3a50e702011-10-18 21:21:00 +02006660#ifndef WC_ERR_INVALID_CHARS
6661# define WC_ERR_INVALID_CHARS 0x0080
6662#endif
6663
6664static char*
6665code_page_name(UINT code_page, PyObject **obj)
6666{
6667 *obj = NULL;
6668 if (code_page == CP_ACP)
6669 return "mbcs";
6670 if (code_page == CP_UTF7)
6671 return "CP_UTF7";
6672 if (code_page == CP_UTF8)
6673 return "CP_UTF8";
6674
6675 *obj = PyBytes_FromFormat("cp%u", code_page);
6676 if (*obj == NULL)
6677 return NULL;
6678 return PyBytes_AS_STRING(*obj);
6679}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006680
Alexander Belopolsky40018472011-02-26 01:02:56 +00006681static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006682is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006683{
6684 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006685 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006686
Victor Stinner3a50e702011-10-18 21:21:00 +02006687 if (!IsDBCSLeadByteEx(code_page, *curr))
6688 return 0;
6689
6690 prev = CharPrevExA(code_page, s, curr, 0);
6691 if (prev == curr)
6692 return 1;
6693 /* FIXME: This code is limited to "true" double-byte encodings,
6694 as it assumes an incomplete character consists of a single
6695 byte. */
6696 if (curr - prev == 2)
6697 return 1;
6698 if (!IsDBCSLeadByteEx(code_page, *prev))
6699 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006700 return 0;
6701}
6702
Victor Stinner3a50e702011-10-18 21:21:00 +02006703static DWORD
6704decode_code_page_flags(UINT code_page)
6705{
6706 if (code_page == CP_UTF7) {
6707 /* The CP_UTF7 decoder only supports flags=0 */
6708 return 0;
6709 }
6710 else
6711 return MB_ERR_INVALID_CHARS;
6712}
6713
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006714/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006715 * Decode a byte string from a Windows code page into unicode object in strict
6716 * mode.
6717 *
6718 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6719 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006720 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006721static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006722decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006723 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006724 const char *in,
6725 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006726{
Victor Stinner3a50e702011-10-18 21:21:00 +02006727 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006728 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006729 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006730
6731 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006732 assert(insize > 0);
6733 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6734 if (outsize <= 0)
6735 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006736
6737 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006739 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006740 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 if (*v == NULL)
6742 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006743 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006744 }
6745 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006747 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006748 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006750 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006751 }
6752
6753 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006754 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6755 if (outsize <= 0)
6756 goto error;
6757 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006758
Victor Stinner3a50e702011-10-18 21:21:00 +02006759error:
6760 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6761 return -2;
6762 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006763 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006764}
6765
Victor Stinner3a50e702011-10-18 21:21:00 +02006766/*
6767 * Decode a byte string from a code page into unicode object with an error
6768 * handler.
6769 *
6770 * Returns consumed size if succeed, or raise a WindowsError or
6771 * UnicodeDecodeError exception and returns -1 on error.
6772 */
6773static int
6774decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006775 PyObject **v,
6776 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006777 const char *errors)
6778{
6779 const char *startin = in;
6780 const char *endin = in + size;
6781 const DWORD flags = decode_code_page_flags(code_page);
6782 /* Ideally, we should get reason from FormatMessage. This is the Windows
6783 2000 English version of the message. */
6784 const char *reason = "No mapping for the Unicode character exists "
6785 "in the target code page.";
6786 /* each step cannot decode more than 1 character, but a character can be
6787 represented as a surrogate pair */
6788 wchar_t buffer[2], *startout, *out;
6789 int insize, outsize;
6790 PyObject *errorHandler = NULL;
6791 PyObject *exc = NULL;
6792 PyObject *encoding_obj = NULL;
6793 char *encoding;
6794 DWORD err;
6795 int ret = -1;
6796
6797 assert(size > 0);
6798
6799 encoding = code_page_name(code_page, &encoding_obj);
6800 if (encoding == NULL)
6801 return -1;
6802
6803 if (errors == NULL || strcmp(errors, "strict") == 0) {
6804 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6805 UnicodeDecodeError. */
6806 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6807 if (exc != NULL) {
6808 PyCodec_StrictErrors(exc);
6809 Py_CLEAR(exc);
6810 }
6811 goto error;
6812 }
6813
6814 if (*v == NULL) {
6815 /* Create unicode object */
6816 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6817 PyErr_NoMemory();
6818 goto error;
6819 }
Victor Stinnerab595942011-12-17 04:59:06 +01006820 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006821 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006822 if (*v == NULL)
6823 goto error;
6824 startout = PyUnicode_AS_UNICODE(*v);
6825 }
6826 else {
6827 /* Extend unicode object */
6828 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6829 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6830 PyErr_NoMemory();
6831 goto error;
6832 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006833 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006834 goto error;
6835 startout = PyUnicode_AS_UNICODE(*v) + n;
6836 }
6837
6838 /* Decode the byte string character per character */
6839 out = startout;
6840 while (in < endin)
6841 {
6842 /* Decode a character */
6843 insize = 1;
6844 do
6845 {
6846 outsize = MultiByteToWideChar(code_page, flags,
6847 in, insize,
6848 buffer, Py_ARRAY_LENGTH(buffer));
6849 if (outsize > 0)
6850 break;
6851 err = GetLastError();
6852 if (err != ERROR_NO_UNICODE_TRANSLATION
6853 && err != ERROR_INSUFFICIENT_BUFFER)
6854 {
6855 PyErr_SetFromWindowsErr(0);
6856 goto error;
6857 }
6858 insize++;
6859 }
6860 /* 4=maximum length of a UTF-8 sequence */
6861 while (insize <= 4 && (in + insize) <= endin);
6862
6863 if (outsize <= 0) {
6864 Py_ssize_t startinpos, endinpos, outpos;
6865
6866 startinpos = in - startin;
6867 endinpos = startinpos + 1;
6868 outpos = out - PyUnicode_AS_UNICODE(*v);
6869 if (unicode_decode_call_errorhandler(
6870 errors, &errorHandler,
6871 encoding, reason,
6872 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006873 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006874 {
6875 goto error;
6876 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006877 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006878 }
6879 else {
6880 in += insize;
6881 memcpy(out, buffer, outsize * sizeof(wchar_t));
6882 out += outsize;
6883 }
6884 }
6885
6886 /* write a NUL character at the end */
6887 *out = 0;
6888
6889 /* Extend unicode object */
6890 outsize = out - startout;
6891 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006892 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006893 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006894 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006895
6896error:
6897 Py_XDECREF(encoding_obj);
6898 Py_XDECREF(errorHandler);
6899 Py_XDECREF(exc);
6900 return ret;
6901}
6902
Victor Stinner3a50e702011-10-18 21:21:00 +02006903static PyObject *
6904decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006905 const char *s, Py_ssize_t size,
6906 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006907{
Victor Stinner76a31a62011-11-04 00:05:13 +01006908 PyObject *v = NULL;
6909 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910
Victor Stinner3a50e702011-10-18 21:21:00 +02006911 if (code_page < 0) {
6912 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6913 return NULL;
6914 }
6915
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006916 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006917 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006918
Victor Stinner76a31a62011-11-04 00:05:13 +01006919 do
6920 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006922 if (size > INT_MAX) {
6923 chunk_size = INT_MAX;
6924 final = 0;
6925 done = 0;
6926 }
6927 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006928#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006929 {
6930 chunk_size = (int)size;
6931 final = (consumed == NULL);
6932 done = 1;
6933 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006934
Victor Stinner76a31a62011-11-04 00:05:13 +01006935 /* Skip trailing lead-byte unless 'final' is set */
6936 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6937 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006938
Victor Stinner76a31a62011-11-04 00:05:13 +01006939 if (chunk_size == 0 && done) {
6940 if (v != NULL)
6941 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006942 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006943 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006944
Victor Stinner76a31a62011-11-04 00:05:13 +01006945
6946 converted = decode_code_page_strict(code_page, &v,
6947 s, chunk_size);
6948 if (converted == -2)
6949 converted = decode_code_page_errors(code_page, &v,
6950 s, chunk_size,
6951 errors);
6952 assert(converted != 0);
6953
6954 if (converted < 0) {
6955 Py_XDECREF(v);
6956 return NULL;
6957 }
6958
6959 if (consumed)
6960 *consumed += converted;
6961
6962 s += converted;
6963 size -= converted;
6964 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006965
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006966 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006967}
6968
Alexander Belopolsky40018472011-02-26 01:02:56 +00006969PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006970PyUnicode_DecodeCodePageStateful(int code_page,
6971 const char *s,
6972 Py_ssize_t size,
6973 const char *errors,
6974 Py_ssize_t *consumed)
6975{
6976 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6977}
6978
6979PyObject *
6980PyUnicode_DecodeMBCSStateful(const char *s,
6981 Py_ssize_t size,
6982 const char *errors,
6983 Py_ssize_t *consumed)
6984{
6985 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6986}
6987
6988PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006989PyUnicode_DecodeMBCS(const char *s,
6990 Py_ssize_t size,
6991 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006992{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006993 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6994}
6995
Victor Stinner3a50e702011-10-18 21:21:00 +02006996static DWORD
6997encode_code_page_flags(UINT code_page, const char *errors)
6998{
6999 if (code_page == CP_UTF8) {
7000 if (winver.dwMajorVersion >= 6)
7001 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7002 and later */
7003 return WC_ERR_INVALID_CHARS;
7004 else
7005 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7006 return 0;
7007 }
7008 else if (code_page == CP_UTF7) {
7009 /* CP_UTF7 only supports flags=0 */
7010 return 0;
7011 }
7012 else {
7013 if (errors != NULL && strcmp(errors, "replace") == 0)
7014 return 0;
7015 else
7016 return WC_NO_BEST_FIT_CHARS;
7017 }
7018}
7019
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007021 * Encode a Unicode string to a Windows code page into a byte string in strict
7022 * mode.
7023 *
7024 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7025 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007026 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007027static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007028encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007029 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031{
Victor Stinner554f3f02010-06-16 23:33:54 +00007032 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 BOOL *pusedDefaultChar = &usedDefaultChar;
7034 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007035 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007036 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007037 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 const DWORD flags = encode_code_page_flags(code_page, NULL);
7039 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007040 /* Create a substring so that we can get the UTF-16 representation
7041 of just the slice under consideration. */
7042 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007043
Martin v. Löwis3d325192011-11-04 18:23:06 +01007044 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007045
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007047 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007049 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007050
Victor Stinner2fc507f2011-11-04 20:06:39 +01007051 substring = PyUnicode_Substring(unicode, offset, offset+len);
7052 if (substring == NULL)
7053 return -1;
7054 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7055 if (p == NULL) {
7056 Py_DECREF(substring);
7057 return -1;
7058 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007059
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007060 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007061 outsize = WideCharToMultiByte(code_page, flags,
7062 p, size,
7063 NULL, 0,
7064 NULL, pusedDefaultChar);
7065 if (outsize <= 0)
7066 goto error;
7067 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007068 if (pusedDefaultChar && *pusedDefaultChar) {
7069 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007070 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007071 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007072
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007074 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007075 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007076 if (*outbytes == NULL) {
7077 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007078 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007079 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081 }
7082 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 const Py_ssize_t n = PyBytes_Size(*outbytes);
7085 if (outsize > PY_SSIZE_T_MAX - n) {
7086 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007087 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007089 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007090 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7091 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007093 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095 }
7096
7097 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 outsize = WideCharToMultiByte(code_page, flags,
7099 p, size,
7100 out, outsize,
7101 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007102 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 if (outsize <= 0)
7104 goto error;
7105 if (pusedDefaultChar && *pusedDefaultChar)
7106 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007107 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007110 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7112 return -2;
7113 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007114 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007115}
7116
Victor Stinner3a50e702011-10-18 21:21:00 +02007117/*
7118 * Encode a Unicode string to a Windows code page into a byte string using a
7119 * error handler.
7120 *
7121 * Returns consumed characters if succeed, or raise a WindowsError and returns
7122 * -1 on other error.
7123 */
7124static int
7125encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007126 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007127 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007128{
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007130 Py_ssize_t pos = unicode_offset;
7131 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 /* Ideally, we should get reason from FormatMessage. This is the Windows
7133 2000 English version of the message. */
7134 const char *reason = "invalid character";
7135 /* 4=maximum length of a UTF-8 sequence */
7136 char buffer[4];
7137 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7138 Py_ssize_t outsize;
7139 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 PyObject *errorHandler = NULL;
7141 PyObject *exc = NULL;
7142 PyObject *encoding_obj = NULL;
7143 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007144 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 PyObject *rep;
7146 int ret = -1;
7147
7148 assert(insize > 0);
7149
7150 encoding = code_page_name(code_page, &encoding_obj);
7151 if (encoding == NULL)
7152 return -1;
7153
7154 if (errors == NULL || strcmp(errors, "strict") == 0) {
7155 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7156 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007157 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 if (exc != NULL) {
7159 PyCodec_StrictErrors(exc);
7160 Py_DECREF(exc);
7161 }
7162 Py_XDECREF(encoding_obj);
7163 return -1;
7164 }
7165
7166 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7167 pusedDefaultChar = &usedDefaultChar;
7168 else
7169 pusedDefaultChar = NULL;
7170
7171 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7172 PyErr_NoMemory();
7173 goto error;
7174 }
7175 outsize = insize * Py_ARRAY_LENGTH(buffer);
7176
7177 if (*outbytes == NULL) {
7178 /* Create string object */
7179 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7180 if (*outbytes == NULL)
7181 goto error;
7182 out = PyBytes_AS_STRING(*outbytes);
7183 }
7184 else {
7185 /* Extend string object */
7186 Py_ssize_t n = PyBytes_Size(*outbytes);
7187 if (n > PY_SSIZE_T_MAX - outsize) {
7188 PyErr_NoMemory();
7189 goto error;
7190 }
7191 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7192 goto error;
7193 out = PyBytes_AS_STRING(*outbytes) + n;
7194 }
7195
7196 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007197 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007199 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7200 wchar_t chars[2];
7201 int charsize;
7202 if (ch < 0x10000) {
7203 chars[0] = (wchar_t)ch;
7204 charsize = 1;
7205 }
7206 else {
7207 ch -= 0x10000;
7208 chars[0] = 0xd800 + (ch >> 10);
7209 chars[1] = 0xdc00 + (ch & 0x3ff);
7210 charsize = 2;
7211 }
7212
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007214 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 buffer, Py_ARRAY_LENGTH(buffer),
7216 NULL, pusedDefaultChar);
7217 if (outsize > 0) {
7218 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7219 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007220 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 memcpy(out, buffer, outsize);
7222 out += outsize;
7223 continue;
7224 }
7225 }
7226 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7227 PyErr_SetFromWindowsErr(0);
7228 goto error;
7229 }
7230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 rep = unicode_encode_call_errorhandler(
7232 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007233 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007234 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 if (rep == NULL)
7236 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007237 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007238
7239 if (PyBytes_Check(rep)) {
7240 outsize = PyBytes_GET_SIZE(rep);
7241 if (outsize != 1) {
7242 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7243 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7244 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7245 Py_DECREF(rep);
7246 goto error;
7247 }
7248 out = PyBytes_AS_STRING(*outbytes) + offset;
7249 }
7250 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7251 out += outsize;
7252 }
7253 else {
7254 Py_ssize_t i;
7255 enum PyUnicode_Kind kind;
7256 void *data;
7257
Benjamin Petersonbac79492012-01-14 13:34:47 -05007258 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 Py_DECREF(rep);
7260 goto error;
7261 }
7262
7263 outsize = PyUnicode_GET_LENGTH(rep);
7264 if (outsize != 1) {
7265 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7266 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7267 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7268 Py_DECREF(rep);
7269 goto error;
7270 }
7271 out = PyBytes_AS_STRING(*outbytes) + offset;
7272 }
7273 kind = PyUnicode_KIND(rep);
7274 data = PyUnicode_DATA(rep);
7275 for (i=0; i < outsize; i++) {
7276 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7277 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007278 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007279 encoding, unicode,
7280 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007281 "unable to encode error handler result to ASCII");
7282 Py_DECREF(rep);
7283 goto error;
7284 }
7285 *out = (unsigned char)ch;
7286 out++;
7287 }
7288 }
7289 Py_DECREF(rep);
7290 }
7291 /* write a NUL byte */
7292 *out = 0;
7293 outsize = out - PyBytes_AS_STRING(*outbytes);
7294 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7295 if (_PyBytes_Resize(outbytes, outsize) < 0)
7296 goto error;
7297 ret = 0;
7298
7299error:
7300 Py_XDECREF(encoding_obj);
7301 Py_XDECREF(errorHandler);
7302 Py_XDECREF(exc);
7303 return ret;
7304}
7305
Victor Stinner3a50e702011-10-18 21:21:00 +02007306static PyObject *
7307encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007308 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 const char *errors)
7310{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007311 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007313 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007314 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007315
Benjamin Petersonbac79492012-01-14 13:34:47 -05007316 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007317 return NULL;
7318 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007319
Victor Stinner3a50e702011-10-18 21:21:00 +02007320 if (code_page < 0) {
7321 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7322 return NULL;
7323 }
7324
Martin v. Löwis3d325192011-11-04 18:23:06 +01007325 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007326 return PyBytes_FromStringAndSize(NULL, 0);
7327
Victor Stinner7581cef2011-11-03 22:32:33 +01007328 offset = 0;
7329 do
7330 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007332 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007333 chunks. */
7334 if (len > INT_MAX/2) {
7335 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007336 done = 0;
7337 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007338 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007340 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007341 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007342 done = 1;
7343 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007344
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007346 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007347 errors);
7348 if (ret == -2)
7349 ret = encode_code_page_errors(code_page, &outbytes,
7350 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007352 if (ret < 0) {
7353 Py_XDECREF(outbytes);
7354 return NULL;
7355 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356
Victor Stinner7581cef2011-11-03 22:32:33 +01007357 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007358 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007359 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007360
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 return outbytes;
7362}
7363
7364PyObject *
7365PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7366 Py_ssize_t size,
7367 const char *errors)
7368{
Victor Stinner7581cef2011-11-03 22:32:33 +01007369 PyObject *unicode, *res;
7370 unicode = PyUnicode_FromUnicode(p, size);
7371 if (unicode == NULL)
7372 return NULL;
7373 res = encode_code_page(CP_ACP, unicode, errors);
7374 Py_DECREF(unicode);
7375 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007376}
7377
7378PyObject *
7379PyUnicode_EncodeCodePage(int code_page,
7380 PyObject *unicode,
7381 const char *errors)
7382{
Victor Stinner7581cef2011-11-03 22:32:33 +01007383 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007384}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007385
Alexander Belopolsky40018472011-02-26 01:02:56 +00007386PyObject *
7387PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007388{
7389 if (!PyUnicode_Check(unicode)) {
7390 PyErr_BadArgument();
7391 return NULL;
7392 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007393 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007394}
7395
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007396#undef NEED_RETRY
7397
Victor Stinner99b95382011-07-04 14:23:54 +02007398#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007399
Guido van Rossumd57fd912000-03-10 22:53:23 +00007400/* --- Character Mapping Codec -------------------------------------------- */
7401
Alexander Belopolsky40018472011-02-26 01:02:56 +00007402PyObject *
7403PyUnicode_DecodeCharmap(const char *s,
7404 Py_ssize_t size,
7405 PyObject *mapping,
7406 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007407{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007408 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007409 Py_ssize_t startinpos;
7410 Py_ssize_t endinpos;
7411 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007412 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007413 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007414 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007415 PyObject *errorHandler = NULL;
7416 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007417
Guido van Rossumd57fd912000-03-10 22:53:23 +00007418 /* Default to Latin-1 */
7419 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007421
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007422 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007423 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007425 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007426 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007427 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007428 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007429 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007430 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007431 enum PyUnicode_Kind mapkind;
7432 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007433 Py_UCS4 x;
7434
Benjamin Petersonbac79492012-01-14 13:34:47 -05007435 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007436 return NULL;
7437
7438 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007439 mapdata = PyUnicode_DATA(mapping);
7440 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007441 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007442 unsigned char ch;
7443 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7444 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7445 if (outkind == PyUnicode_1BYTE_KIND) {
7446 void *outdata = PyUnicode_DATA(v);
7447 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7448 while (s < e) {
7449 unsigned char ch = *s;
7450 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7451 if (x > maxchar)
7452 goto Error;
7453 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7454 ++s;
7455 }
7456 break;
7457 }
7458 else if (outkind == PyUnicode_2BYTE_KIND) {
7459 void *outdata = PyUnicode_DATA(v);
7460 while (s < e) {
7461 unsigned char ch = *s;
7462 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7463 if (x == 0xFFFE)
7464 goto Error;
7465 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7466 ++s;
7467 }
7468 break;
7469 }
7470 }
7471 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007472
Benjamin Peterson29060642009-01-31 22:14:21 +00007473 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007474 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007475 else
7476 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007477Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007478 if (x == 0xfffe)
7479 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007480 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 startinpos = s-starts;
7482 endinpos = startinpos+1;
7483 if (unicode_decode_call_errorhandler(
7484 errors, &errorHandler,
7485 "charmap", "character maps to <undefined>",
7486 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007487 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007488 goto onError;
7489 }
7490 continue;
7491 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007492
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007493 if (unicode_putchar(&v, &outpos, x) < 0)
7494 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007495 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007496 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007497 }
7498 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 while (s < e) {
7500 unsigned char ch = *s;
7501 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007502
Benjamin Peterson29060642009-01-31 22:14:21 +00007503 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7504 w = PyLong_FromLong((long)ch);
7505 if (w == NULL)
7506 goto onError;
7507 x = PyObject_GetItem(mapping, w);
7508 Py_DECREF(w);
7509 if (x == NULL) {
7510 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7511 /* No mapping found means: mapping is undefined. */
7512 PyErr_Clear();
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007513 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007514 } else
7515 goto onError;
7516 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007517
Benjamin Peterson29060642009-01-31 22:14:21 +00007518 /* Apply mapping */
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007519 if (x == Py_None)
7520 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 if (PyLong_Check(x)) {
7522 long value = PyLong_AS_LONG(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007523 if (value == 0xFFFE)
7524 goto Undefined;
Antoine Pitroua1f76552012-09-23 20:00:04 +02007525 if (value < 0 || value > MAX_UNICODE) {
7526 PyErr_Format(PyExc_TypeError,
7527 "character mapping must be in range(0x%lx)",
7528 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 Py_DECREF(x);
7530 goto onError;
7531 }
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007532 if (unicode_putchar(&v, &outpos, value) < 0) {
7533 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007534 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007535 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007536 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007538 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007539
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007540 if (PyUnicode_READY(x) == -1) {
7541 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007542 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007543 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007544 targetsize = PyUnicode_GET_LENGTH(x);
7545
7546 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007547 /* 1-1 mapping */
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007548 Py_UCS4 value = PyUnicode_READ_CHAR(x, 0);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007549 if (value == 0xFFFE)
7550 goto Undefined;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007551 if (unicode_putchar(&v, &outpos, value) < 0) {
7552 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007553 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007554 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007555 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007556 else if (targetsize > 1) {
7557 /* 1-n mapping */
7558 if (targetsize > extrachars) {
7559 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007560 Py_ssize_t needed = (targetsize - extrachars) + \
7561 (targetsize << 2);
7562 extrachars += needed;
7563 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007564 if (unicode_resize(&v,
7565 PyUnicode_GET_LENGTH(v) + needed) < 0)
7566 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 Py_DECREF(x);
7568 goto onError;
7569 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007570 }
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007571 if (unicode_widen(&v, outpos,
7572 PyUnicode_MAX_CHAR_VALUE(x)) < 0) {
7573 Py_DECREF(x);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007574 goto onError;
Serhiy Storchakaafb1cb52013-01-29 12:13:22 +02007575 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007576 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7577 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007578 extrachars -= targetsize;
7579 }
7580 /* 1-0 mapping: skip the character */
7581 }
7582 else {
7583 /* wrong return value */
7584 PyErr_SetString(PyExc_TypeError,
7585 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007586 Py_DECREF(x);
7587 goto onError;
7588 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007589 Py_DECREF(x);
7590 ++s;
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007591 continue;
7592Undefined:
7593 /* undefined mapping */
7594 Py_XDECREF(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007595 startinpos = s-starts;
7596 endinpos = startinpos+1;
7597 if (unicode_decode_call_errorhandler(
7598 errors, &errorHandler,
7599 "charmap", "character maps to <undefined>",
7600 &starts, &e, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007601 &v, &outpos)) {
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007602 goto onError;
7603 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007604 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007605 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007606 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007607 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007608 Py_XDECREF(errorHandler);
7609 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007610 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007611
Benjamin Peterson29060642009-01-31 22:14:21 +00007612 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007613 Py_XDECREF(errorHandler);
7614 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007615 Py_XDECREF(v);
7616 return NULL;
7617}
7618
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007619/* Charmap encoding: the lookup table */
7620
Alexander Belopolsky40018472011-02-26 01:02:56 +00007621struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007622 PyObject_HEAD
7623 unsigned char level1[32];
7624 int count2, count3;
7625 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007626};
7627
7628static PyObject*
7629encoding_map_size(PyObject *obj, PyObject* args)
7630{
7631 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007632 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007634}
7635
7636static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007637 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007638 PyDoc_STR("Return the size (in bytes) of this object") },
7639 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007640};
7641
7642static void
7643encoding_map_dealloc(PyObject* o)
7644{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007645 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007646}
7647
7648static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007649 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 "EncodingMap", /*tp_name*/
7651 sizeof(struct encoding_map), /*tp_basicsize*/
7652 0, /*tp_itemsize*/
7653 /* methods */
7654 encoding_map_dealloc, /*tp_dealloc*/
7655 0, /*tp_print*/
7656 0, /*tp_getattr*/
7657 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007658 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 0, /*tp_repr*/
7660 0, /*tp_as_number*/
7661 0, /*tp_as_sequence*/
7662 0, /*tp_as_mapping*/
7663 0, /*tp_hash*/
7664 0, /*tp_call*/
7665 0, /*tp_str*/
7666 0, /*tp_getattro*/
7667 0, /*tp_setattro*/
7668 0, /*tp_as_buffer*/
7669 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7670 0, /*tp_doc*/
7671 0, /*tp_traverse*/
7672 0, /*tp_clear*/
7673 0, /*tp_richcompare*/
7674 0, /*tp_weaklistoffset*/
7675 0, /*tp_iter*/
7676 0, /*tp_iternext*/
7677 encoding_map_methods, /*tp_methods*/
7678 0, /*tp_members*/
7679 0, /*tp_getset*/
7680 0, /*tp_base*/
7681 0, /*tp_dict*/
7682 0, /*tp_descr_get*/
7683 0, /*tp_descr_set*/
7684 0, /*tp_dictoffset*/
7685 0, /*tp_init*/
7686 0, /*tp_alloc*/
7687 0, /*tp_new*/
7688 0, /*tp_free*/
7689 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007690};
7691
7692PyObject*
7693PyUnicode_BuildEncodingMap(PyObject* string)
7694{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007695 PyObject *result;
7696 struct encoding_map *mresult;
7697 int i;
7698 int need_dict = 0;
7699 unsigned char level1[32];
7700 unsigned char level2[512];
7701 unsigned char *mlevel1, *mlevel2, *mlevel3;
7702 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007703 int kind;
7704 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007705 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007706 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007707
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007708 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007709 PyErr_BadArgument();
7710 return NULL;
7711 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007712 kind = PyUnicode_KIND(string);
7713 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007714 length = PyUnicode_GET_LENGTH(string);
7715 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007716 memset(level1, 0xFF, sizeof level1);
7717 memset(level2, 0xFF, sizeof level2);
7718
7719 /* If there isn't a one-to-one mapping of NULL to \0,
7720 or if there are non-BMP characters, we need to use
7721 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007722 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007723 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007724 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007725 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007726 ch = PyUnicode_READ(kind, data, i);
7727 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007728 need_dict = 1;
7729 break;
7730 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007731 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007732 /* unmapped character */
7733 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007734 l1 = ch >> 11;
7735 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007736 if (level1[l1] == 0xFF)
7737 level1[l1] = count2++;
7738 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007739 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007740 }
7741
7742 if (count2 >= 0xFF || count3 >= 0xFF)
7743 need_dict = 1;
7744
7745 if (need_dict) {
7746 PyObject *result = PyDict_New();
7747 PyObject *key, *value;
7748 if (!result)
7749 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007750 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007751 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007752 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007753 if (!key || !value)
7754 goto failed1;
7755 if (PyDict_SetItem(result, key, value) == -1)
7756 goto failed1;
7757 Py_DECREF(key);
7758 Py_DECREF(value);
7759 }
7760 return result;
7761 failed1:
7762 Py_XDECREF(key);
7763 Py_XDECREF(value);
7764 Py_DECREF(result);
7765 return NULL;
7766 }
7767
7768 /* Create a three-level trie */
7769 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7770 16*count2 + 128*count3 - 1);
7771 if (!result)
7772 return PyErr_NoMemory();
7773 PyObject_Init(result, &EncodingMapType);
7774 mresult = (struct encoding_map*)result;
7775 mresult->count2 = count2;
7776 mresult->count3 = count3;
7777 mlevel1 = mresult->level1;
7778 mlevel2 = mresult->level23;
7779 mlevel3 = mresult->level23 + 16*count2;
7780 memcpy(mlevel1, level1, 32);
7781 memset(mlevel2, 0xFF, 16*count2);
7782 memset(mlevel3, 0, 128*count3);
7783 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007784 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007785 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007786 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7787 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007788 /* unmapped character */
7789 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007790 o1 = ch>>11;
7791 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007792 i2 = 16*mlevel1[o1] + o2;
7793 if (mlevel2[i2] == 0xFF)
7794 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007795 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007796 i3 = 128*mlevel2[i2] + o3;
7797 mlevel3[i3] = i;
7798 }
7799 return result;
7800}
7801
7802static int
Victor Stinner22168992011-11-20 17:09:18 +01007803encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007804{
7805 struct encoding_map *map = (struct encoding_map*)mapping;
7806 int l1 = c>>11;
7807 int l2 = (c>>7) & 0xF;
7808 int l3 = c & 0x7F;
7809 int i;
7810
Victor Stinner22168992011-11-20 17:09:18 +01007811 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007813 if (c == 0)
7814 return 0;
7815 /* level 1*/
7816 i = map->level1[l1];
7817 if (i == 0xFF) {
7818 return -1;
7819 }
7820 /* level 2*/
7821 i = map->level23[16*i+l2];
7822 if (i == 0xFF) {
7823 return -1;
7824 }
7825 /* level 3 */
7826 i = map->level23[16*map->count2 + 128*i + l3];
7827 if (i == 0) {
7828 return -1;
7829 }
7830 return i;
7831}
7832
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007833/* Lookup the character ch in the mapping. If the character
7834 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007835 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007836static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007837charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007838{
Christian Heimes217cfd12007-12-02 14:31:20 +00007839 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007840 PyObject *x;
7841
7842 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007844 x = PyObject_GetItem(mapping, w);
7845 Py_DECREF(w);
7846 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7848 /* No mapping found means: mapping is undefined. */
7849 PyErr_Clear();
7850 x = Py_None;
7851 Py_INCREF(x);
7852 return x;
7853 } else
7854 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007855 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007856 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007858 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 long value = PyLong_AS_LONG(x);
7860 if (value < 0 || value > 255) {
7861 PyErr_SetString(PyExc_TypeError,
7862 "character mapping must be in range(256)");
7863 Py_DECREF(x);
7864 return NULL;
7865 }
7866 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007867 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007868 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007870 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 /* wrong return value */
7872 PyErr_Format(PyExc_TypeError,
7873 "character mapping must return integer, bytes or None, not %.400s",
7874 x->ob_type->tp_name);
7875 Py_DECREF(x);
7876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007877 }
7878}
7879
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007880static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007881charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007883 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7884 /* exponentially overallocate to minimize reallocations */
7885 if (requiredsize < 2*outsize)
7886 requiredsize = 2*outsize;
7887 if (_PyBytes_Resize(outobj, requiredsize))
7888 return -1;
7889 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007890}
7891
Benjamin Peterson14339b62009-01-31 16:36:08 +00007892typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007893 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007894} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007895/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007896 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007897 space is available. Return a new reference to the object that
7898 was put in the output buffer, or Py_None, if the mapping was undefined
7899 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007900 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007901static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007902charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007903 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007904{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 PyObject *rep;
7906 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007907 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007908
Christian Heimes90aa7642007-12-19 02:45:37 +00007909 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007910 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 if (res == -1)
7913 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 if (outsize<requiredsize)
7915 if (charmapencode_resize(outobj, outpos, requiredsize))
7916 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007917 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 outstart[(*outpos)++] = (char)res;
7919 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007920 }
7921
7922 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007923 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007924 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007925 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 Py_DECREF(rep);
7927 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007928 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007929 if (PyLong_Check(rep)) {
7930 Py_ssize_t requiredsize = *outpos+1;
7931 if (outsize<requiredsize)
7932 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7933 Py_DECREF(rep);
7934 return enc_EXCEPTION;
7935 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007936 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007938 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007939 else {
7940 const char *repchars = PyBytes_AS_STRING(rep);
7941 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7942 Py_ssize_t requiredsize = *outpos+repsize;
7943 if (outsize<requiredsize)
7944 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7945 Py_DECREF(rep);
7946 return enc_EXCEPTION;
7947 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007948 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007949 memcpy(outstart + *outpos, repchars, repsize);
7950 *outpos += repsize;
7951 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007952 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007953 Py_DECREF(rep);
7954 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007955}
7956
7957/* handle an error in PyUnicode_EncodeCharmap
7958 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007959static int
7960charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007961 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007962 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007963 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007964 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007965{
7966 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007967 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007968 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007969 enum PyUnicode_Kind kind;
7970 void *data;
7971 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007972 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007973 Py_ssize_t collstartpos = *inpos;
7974 Py_ssize_t collendpos = *inpos+1;
7975 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007976 char *encoding = "charmap";
7977 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007978 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007979 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007980 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007981
Benjamin Petersonbac79492012-01-14 13:34:47 -05007982 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007983 return -1;
7984 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985 /* find all unencodable characters */
7986 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007987 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007988 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007989 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007990 val = encoding_map_lookup(ch, mapping);
7991 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 break;
7993 ++collendpos;
7994 continue;
7995 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007996
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007997 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7998 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 if (rep==NULL)
8000 return -1;
8001 else if (rep!=Py_None) {
8002 Py_DECREF(rep);
8003 break;
8004 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008005 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008006 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008007 }
8008 /* cache callback name lookup
8009 * (if not done yet, i.e. it's the first error) */
8010 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 if ((errors==NULL) || (!strcmp(errors, "strict")))
8012 *known_errorHandler = 1;
8013 else if (!strcmp(errors, "replace"))
8014 *known_errorHandler = 2;
8015 else if (!strcmp(errors, "ignore"))
8016 *known_errorHandler = 3;
8017 else if (!strcmp(errors, "xmlcharrefreplace"))
8018 *known_errorHandler = 4;
8019 else
8020 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021 }
8022 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008023 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008024 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008025 return -1;
8026 case 2: /* replace */
8027 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 x = charmapencode_output('?', mapping, res, respos);
8029 if (x==enc_EXCEPTION) {
8030 return -1;
8031 }
8032 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008033 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008034 return -1;
8035 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008036 }
8037 /* fall through */
8038 case 3: /* ignore */
8039 *inpos = collendpos;
8040 break;
8041 case 4: /* xmlcharrefreplace */
8042 /* generate replacement (temporarily (mis)uses p) */
8043 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 char buffer[2+29+1+1];
8045 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008046 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 for (cp = buffer; *cp; ++cp) {
8048 x = charmapencode_output(*cp, mapping, res, respos);
8049 if (x==enc_EXCEPTION)
8050 return -1;
8051 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008052 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 return -1;
8054 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008055 }
8056 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057 *inpos = collendpos;
8058 break;
8059 default:
8060 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008061 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008063 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008064 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008065 if (PyBytes_Check(repunicode)) {
8066 /* Directly copy bytes result to output. */
8067 Py_ssize_t outsize = PyBytes_Size(*res);
8068 Py_ssize_t requiredsize;
8069 repsize = PyBytes_Size(repunicode);
8070 requiredsize = *respos + repsize;
8071 if (requiredsize > outsize)
8072 /* Make room for all additional bytes. */
8073 if (charmapencode_resize(res, respos, requiredsize)) {
8074 Py_DECREF(repunicode);
8075 return -1;
8076 }
8077 memcpy(PyBytes_AsString(*res) + *respos,
8078 PyBytes_AsString(repunicode), repsize);
8079 *respos += repsize;
8080 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008081 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008082 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008083 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008084 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008085 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008086 Py_DECREF(repunicode);
8087 return -1;
8088 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008089 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008090 data = PyUnicode_DATA(repunicode);
8091 kind = PyUnicode_KIND(repunicode);
8092 for (index = 0; index < repsize; index++) {
8093 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8094 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008096 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008097 return -1;
8098 }
8099 else if (x==enc_FAILED) {
8100 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008101 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 return -1;
8103 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008104 }
8105 *inpos = newpos;
8106 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107 }
8108 return 0;
8109}
8110
Alexander Belopolsky40018472011-02-26 01:02:56 +00008111PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112_PyUnicode_EncodeCharmap(PyObject *unicode,
8113 PyObject *mapping,
8114 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008115{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008116 /* output object */
8117 PyObject *res = NULL;
8118 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008119 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008120 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008122 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008123 PyObject *errorHandler = NULL;
8124 PyObject *exc = NULL;
8125 /* the following variable is used for caching string comparisons
8126 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8127 * 3=ignore, 4=xmlcharrefreplace */
8128 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008129
Benjamin Petersonbac79492012-01-14 13:34:47 -05008130 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008131 return NULL;
8132 size = PyUnicode_GET_LENGTH(unicode);
8133
Guido van Rossumd57fd912000-03-10 22:53:23 +00008134 /* Default to Latin-1 */
8135 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008136 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008137
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 /* allocate enough for a simple encoding without
8139 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008140 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141 if (res == NULL)
8142 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008143 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008145
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008147 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008149 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 if (x==enc_EXCEPTION) /* error */
8151 goto onError;
8152 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008153 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 &exc,
8155 &known_errorHandler, &errorHandler, errors,
8156 &res, &respos)) {
8157 goto onError;
8158 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008159 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 else
8161 /* done with this character => adjust input position */
8162 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008163 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008164
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008166 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008167 if (_PyBytes_Resize(&res, respos) < 0)
8168 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008169
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008170 Py_XDECREF(exc);
8171 Py_XDECREF(errorHandler);
8172 return res;
8173
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008175 Py_XDECREF(res);
8176 Py_XDECREF(exc);
8177 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178 return NULL;
8179}
8180
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008181/* Deprecated */
8182PyObject *
8183PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8184 Py_ssize_t size,
8185 PyObject *mapping,
8186 const char *errors)
8187{
8188 PyObject *result;
8189 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8190 if (unicode == NULL)
8191 return NULL;
8192 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8193 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008194 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008195}
8196
Alexander Belopolsky40018472011-02-26 01:02:56 +00008197PyObject *
8198PyUnicode_AsCharmapString(PyObject *unicode,
8199 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008200{
8201 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 PyErr_BadArgument();
8203 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008204 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008205 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008206}
8207
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008209static void
8210make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008211 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008212 Py_ssize_t startpos, Py_ssize_t endpos,
8213 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008214{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008215 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008216 *exceptionObject = _PyUnicodeTranslateError_Create(
8217 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008218 }
8219 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8221 goto onError;
8222 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8223 goto onError;
8224 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8225 goto onError;
8226 return;
8227 onError:
8228 Py_DECREF(*exceptionObject);
8229 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230 }
8231}
8232
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008234static void
8235raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008236 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008237 Py_ssize_t startpos, Py_ssize_t endpos,
8238 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008239{
8240 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008241 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244}
8245
8246/* error handling callback helper:
8247 build arguments, call the callback and check the arguments,
8248 put the result into newpos and return the replacement string, which
8249 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008250static PyObject *
8251unicode_translate_call_errorhandler(const char *errors,
8252 PyObject **errorHandler,
8253 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008254 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008255 Py_ssize_t startpos, Py_ssize_t endpos,
8256 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008257{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008258 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008260 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 PyObject *restuple;
8262 PyObject *resunicode;
8263
8264 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 }
8269
8270 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008271 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008274
8275 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008277 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008280 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 Py_DECREF(restuple);
8282 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283 }
8284 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 &resunicode, &i_newpos)) {
8286 Py_DECREF(restuple);
8287 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008289 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008290 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008291 else
8292 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008293 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8295 Py_DECREF(restuple);
8296 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008297 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298 Py_INCREF(resunicode);
8299 Py_DECREF(restuple);
8300 return resunicode;
8301}
8302
8303/* Lookup the character ch in the mapping and put the result in result,
8304 which must be decrefed by the caller.
8305 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008306static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008307charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308{
Christian Heimes217cfd12007-12-02 14:31:20 +00008309 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 PyObject *x;
8311
8312 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 x = PyObject_GetItem(mapping, w);
8315 Py_DECREF(w);
8316 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8318 /* No mapping found means: use 1:1 mapping. */
8319 PyErr_Clear();
8320 *result = NULL;
8321 return 0;
8322 } else
8323 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 }
8325 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 *result = x;
8327 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008329 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 long value = PyLong_AS_LONG(x);
8331 long max = PyUnicode_GetMax();
8332 if (value < 0 || value > max) {
8333 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008334 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 Py_DECREF(x);
8336 return -1;
8337 }
8338 *result = x;
8339 return 0;
8340 }
8341 else if (PyUnicode_Check(x)) {
8342 *result = x;
8343 return 0;
8344 }
8345 else {
8346 /* wrong return value */
8347 PyErr_SetString(PyExc_TypeError,
8348 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008349 Py_DECREF(x);
8350 return -1;
8351 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352}
8353/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 if not reallocate and adjust various state variables.
8355 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008356static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008357charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008360 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008361 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008362 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 /* exponentially overallocate to minimize reallocations */
8364 if (requiredsize < 2 * oldsize)
8365 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008366 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8367 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008369 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008370 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 }
8372 return 0;
8373}
8374/* lookup the character, put the result in the output string and adjust
8375 various state variables. Return a new reference to the object that
8376 was put in the output buffer in *result, or Py_None, if the mapping was
8377 undefined (in which case no character was written).
8378 The called must decref result.
8379 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008380static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008381charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8382 PyObject *mapping, Py_UCS4 **output,
8383 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008384 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008386 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8387 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008391 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 }
8393 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008395 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008397 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 }
8399 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008400 Py_ssize_t repsize;
8401 if (PyUnicode_READY(*res) == -1)
8402 return -1;
8403 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 if (repsize==1) {
8405 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008406 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 }
8408 else if (repsize!=0) {
8409 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008410 Py_ssize_t requiredsize = *opos +
8411 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008413 Py_ssize_t i;
8414 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008416 for(i = 0; i < repsize; i++)
8417 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 }
8420 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 return 0;
8423}
8424
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008426_PyUnicode_TranslateCharmap(PyObject *input,
8427 PyObject *mapping,
8428 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008429{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 /* input object */
8431 char *idata;
8432 Py_ssize_t size, i;
8433 int kind;
8434 /* output buffer */
8435 Py_UCS4 *output = NULL;
8436 Py_ssize_t osize;
8437 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 char *reason = "character maps to <undefined>";
8441 PyObject *errorHandler = NULL;
8442 PyObject *exc = NULL;
8443 /* the following variable is used for caching string comparisons
8444 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8445 * 3=ignore, 4=xmlcharrefreplace */
8446 int known_errorHandler = -1;
8447
Guido van Rossumd57fd912000-03-10 22:53:23 +00008448 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 PyErr_BadArgument();
8450 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008451 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008453 if (PyUnicode_READY(input) == -1)
8454 return NULL;
8455 idata = (char*)PyUnicode_DATA(input);
8456 kind = PyUnicode_KIND(input);
8457 size = PyUnicode_GET_LENGTH(input);
8458 i = 0;
8459
8460 if (size == 0) {
8461 Py_INCREF(input);
8462 return input;
8463 }
8464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 /* allocate enough for a simple 1:1 translation without
8466 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 osize = size;
8468 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8469 opos = 0;
8470 if (output == NULL) {
8471 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008473 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 /* try to encode it */
8477 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008478 if (charmaptranslate_output(input, i, mapping,
8479 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 Py_XDECREF(x);
8481 goto onError;
8482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008483 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 else { /* untranslatable character */
8487 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8488 Py_ssize_t repsize;
8489 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 Py_ssize_t collstart = i;
8493 Py_ssize_t collend = i+1;
8494 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 while (collend < size) {
8498 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 goto onError;
8500 Py_XDECREF(x);
8501 if (x!=Py_None)
8502 break;
8503 ++collend;
8504 }
8505 /* cache callback name lookup
8506 * (if not done yet, i.e. it's the first error) */
8507 if (known_errorHandler==-1) {
8508 if ((errors==NULL) || (!strcmp(errors, "strict")))
8509 known_errorHandler = 1;
8510 else if (!strcmp(errors, "replace"))
8511 known_errorHandler = 2;
8512 else if (!strcmp(errors, "ignore"))
8513 known_errorHandler = 3;
8514 else if (!strcmp(errors, "xmlcharrefreplace"))
8515 known_errorHandler = 4;
8516 else
8517 known_errorHandler = 0;
8518 }
8519 switch (known_errorHandler) {
8520 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008521 raise_translate_exception(&exc, input, collstart,
8522 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008523 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 case 2: /* replace */
8525 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 for (coll = collstart; coll<collend; coll++)
8527 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 /* fall through */
8529 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 break;
8532 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533 /* generate replacement (temporarily (mis)uses i) */
8534 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 char buffer[2+29+1+1];
8536 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8538 if (charmaptranslate_makespace(&output, &osize,
8539 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 goto onError;
8541 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 break;
8546 default:
8547 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548 reason, input, &exc,
8549 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008550 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008552 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008553 Py_DECREF(repunicode);
8554 goto onError;
8555 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008557 repsize = PyUnicode_GET_LENGTH(repunicode);
8558 if (charmaptranslate_makespace(&output, &osize,
8559 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 Py_DECREF(repunicode);
8561 goto onError;
8562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563 for (uni2 = 0; repsize-->0; ++uni2)
8564 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8565 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008567 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008568 }
8569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8571 if (!res)
8572 goto onError;
8573 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 Py_XDECREF(exc);
8575 Py_XDECREF(errorHandler);
8576 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008577
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 Py_XDECREF(exc);
8581 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582 return NULL;
8583}
8584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585/* Deprecated. Use PyUnicode_Translate instead. */
8586PyObject *
8587PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8588 Py_ssize_t size,
8589 PyObject *mapping,
8590 const char *errors)
8591{
Christian Heimes5f520f42012-09-11 14:03:25 +02008592 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8594 if (!unicode)
8595 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008596 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8597 Py_DECREF(unicode);
8598 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599}
8600
Alexander Belopolsky40018472011-02-26 01:02:56 +00008601PyObject *
8602PyUnicode_Translate(PyObject *str,
8603 PyObject *mapping,
8604 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605{
8606 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008607
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608 str = PyUnicode_FromObject(str);
8609 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008610 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008612 Py_DECREF(str);
8613 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008614}
Tim Petersced69f82003-09-16 20:30:58 +00008615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008617fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618{
8619 /* No need to call PyUnicode_READY(self) because this function is only
8620 called as a callback from fixup() which does it already. */
8621 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8622 const int kind = PyUnicode_KIND(self);
8623 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008624 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008625 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 Py_ssize_t i;
8627
8628 for (i = 0; i < len; ++i) {
8629 ch = PyUnicode_READ(kind, data, i);
8630 fixed = 0;
8631 if (ch > 127) {
8632 if (Py_UNICODE_ISSPACE(ch))
8633 fixed = ' ';
8634 else {
8635 const int decimal = Py_UNICODE_TODECIMAL(ch);
8636 if (decimal >= 0)
8637 fixed = '0' + decimal;
8638 }
8639 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008640 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008641 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 PyUnicode_WRITE(kind, data, i, fixed);
8643 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008644 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008645 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647 }
8648
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008649 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008650}
8651
8652PyObject *
8653_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8654{
8655 if (!PyUnicode_Check(unicode)) {
8656 PyErr_BadInternalCall();
8657 return NULL;
8658 }
8659 if (PyUnicode_READY(unicode) == -1)
8660 return NULL;
8661 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8662 /* If the string is already ASCII, just return the same string */
8663 Py_INCREF(unicode);
8664 return unicode;
8665 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008666 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667}
8668
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008669PyObject *
8670PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8671 Py_ssize_t length)
8672{
Victor Stinnerf0124502011-11-21 23:12:56 +01008673 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008674 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008675 Py_UCS4 maxchar;
8676 enum PyUnicode_Kind kind;
8677 void *data;
8678
Victor Stinner99d7ad02012-02-22 13:37:39 +01008679 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008680 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008681 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008682 if (ch > 127) {
8683 int decimal = Py_UNICODE_TODECIMAL(ch);
8684 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008685 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008686 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008687 }
8688 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008689
8690 /* Copy to a new string */
8691 decimal = PyUnicode_New(length, maxchar);
8692 if (decimal == NULL)
8693 return decimal;
8694 kind = PyUnicode_KIND(decimal);
8695 data = PyUnicode_DATA(decimal);
8696 /* Iterate over code points */
8697 for (i = 0; i < length; i++) {
8698 Py_UNICODE ch = s[i];
8699 if (ch > 127) {
8700 int decimal = Py_UNICODE_TODECIMAL(ch);
8701 if (decimal >= 0)
8702 ch = '0' + decimal;
8703 }
8704 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008705 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008706 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008707}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008708/* --- Decimal Encoder ---------------------------------------------------- */
8709
Alexander Belopolsky40018472011-02-26 01:02:56 +00008710int
8711PyUnicode_EncodeDecimal(Py_UNICODE *s,
8712 Py_ssize_t length,
8713 char *output,
8714 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008715{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008716 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008717 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008718 enum PyUnicode_Kind kind;
8719 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008720
8721 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 PyErr_BadArgument();
8723 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008724 }
8725
Victor Stinner42bf7752011-11-21 22:52:58 +01008726 unicode = PyUnicode_FromUnicode(s, length);
8727 if (unicode == NULL)
8728 return -1;
8729
Benjamin Petersonbac79492012-01-14 13:34:47 -05008730 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008731 Py_DECREF(unicode);
8732 return -1;
8733 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008734 kind = PyUnicode_KIND(unicode);
8735 data = PyUnicode_DATA(unicode);
8736
Victor Stinnerb84d7232011-11-22 01:50:07 +01008737 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008738 PyObject *exc;
8739 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008741 Py_ssize_t startpos;
8742
8743 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008744
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008746 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008747 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008749 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 decimal = Py_UNICODE_TODECIMAL(ch);
8751 if (decimal >= 0) {
8752 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008753 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 continue;
8755 }
8756 if (0 < ch && ch < 256) {
8757 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008758 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008759 continue;
8760 }
Victor Stinner6345be92011-11-25 20:09:01 +01008761
Victor Stinner42bf7752011-11-21 22:52:58 +01008762 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008763 exc = NULL;
8764 raise_encode_exception(&exc, "decimal", unicode,
8765 startpos, startpos+1,
8766 "invalid decimal Unicode string");
8767 Py_XDECREF(exc);
8768 Py_DECREF(unicode);
8769 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008770 }
8771 /* 0-terminate the output string */
8772 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008773 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008774 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008775}
8776
Guido van Rossumd57fd912000-03-10 22:53:23 +00008777/* --- Helpers ------------------------------------------------------------ */
8778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008780any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008781 Py_ssize_t start,
8782 Py_ssize_t end)
8783{
8784 int kind1, kind2, kind;
8785 void *buf1, *buf2;
8786 Py_ssize_t len1, len2, result;
8787
8788 kind1 = PyUnicode_KIND(s1);
8789 kind2 = PyUnicode_KIND(s2);
8790 kind = kind1 > kind2 ? kind1 : kind2;
8791 buf1 = PyUnicode_DATA(s1);
8792 buf2 = PyUnicode_DATA(s2);
8793 if (kind1 != kind)
8794 buf1 = _PyUnicode_AsKind(s1, kind);
8795 if (!buf1)
8796 return -2;
8797 if (kind2 != kind)
8798 buf2 = _PyUnicode_AsKind(s2, kind);
8799 if (!buf2) {
8800 if (kind1 != kind) PyMem_Free(buf1);
8801 return -2;
8802 }
8803 len1 = PyUnicode_GET_LENGTH(s1);
8804 len2 = PyUnicode_GET_LENGTH(s2);
8805
Victor Stinner794d5672011-10-10 03:21:36 +02008806 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008807 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008808 case PyUnicode_1BYTE_KIND:
8809 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8810 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8811 else
8812 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8813 break;
8814 case PyUnicode_2BYTE_KIND:
8815 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8816 break;
8817 case PyUnicode_4BYTE_KIND:
8818 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8819 break;
8820 default:
8821 assert(0); result = -2;
8822 }
8823 }
8824 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008825 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008826 case PyUnicode_1BYTE_KIND:
8827 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8828 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8829 else
8830 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8831 break;
8832 case PyUnicode_2BYTE_KIND:
8833 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8834 break;
8835 case PyUnicode_4BYTE_KIND:
8836 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8837 break;
8838 default:
8839 assert(0); result = -2;
8840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 }
8842
8843 if (kind1 != kind)
8844 PyMem_Free(buf1);
8845 if (kind2 != kind)
8846 PyMem_Free(buf2);
8847
8848 return result;
8849}
8850
8851Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008852_PyUnicode_InsertThousandsGrouping(
8853 PyObject *unicode, Py_ssize_t index,
8854 Py_ssize_t n_buffer,
8855 void *digits, Py_ssize_t n_digits,
8856 Py_ssize_t min_width,
8857 const char *grouping, PyObject *thousands_sep,
8858 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008859{
Victor Stinner41a863c2012-02-24 00:37:51 +01008860 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008861 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008862 Py_ssize_t thousands_sep_len;
8863 Py_ssize_t len;
8864
8865 if (unicode != NULL) {
8866 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008867 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008868 }
8869 else {
8870 kind = PyUnicode_1BYTE_KIND;
8871 data = NULL;
8872 }
8873 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8874 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8875 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8876 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008877 if (thousands_sep_kind < kind) {
8878 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8879 if (!thousands_sep_data)
8880 return -1;
8881 }
8882 else {
8883 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8884 if (!data)
8885 return -1;
8886 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008887 }
8888
Benjamin Petersonead6b532011-12-20 17:23:42 -06008889 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008891 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008892 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008893 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008894 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008895 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008896 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008897 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008898 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008899 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008900 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008901 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008902 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008903 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008904 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008905 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008906 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008907 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008909 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008910 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008911 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008912 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008913 break;
8914 default:
8915 assert(0);
8916 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008918 if (unicode != NULL && thousands_sep_kind != kind) {
8919 if (thousands_sep_kind < kind)
8920 PyMem_Free(thousands_sep_data);
8921 else
8922 PyMem_Free(data);
8923 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008924 if (unicode == NULL) {
8925 *maxchar = 127;
8926 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07008927 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02008928 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008929 }
8930 }
8931 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932}
8933
8934
Thomas Wouters477c8d52006-05-27 19:21:47 +00008935/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008936#define ADJUST_INDICES(start, end, len) \
8937 if (end > len) \
8938 end = len; \
8939 else if (end < 0) { \
8940 end += len; \
8941 if (end < 0) \
8942 end = 0; \
8943 } \
8944 if (start < 0) { \
8945 start += len; \
8946 if (start < 0) \
8947 start = 0; \
8948 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008949
Alexander Belopolsky40018472011-02-26 01:02:56 +00008950Py_ssize_t
8951PyUnicode_Count(PyObject *str,
8952 PyObject *substr,
8953 Py_ssize_t start,
8954 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008955{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008956 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008957 PyObject* str_obj;
8958 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008959 int kind1, kind2, kind;
8960 void *buf1 = NULL, *buf2 = NULL;
8961 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008962
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008963 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008964 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008965 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008966 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008967 if (!sub_obj) {
8968 Py_DECREF(str_obj);
8969 return -1;
8970 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008971 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008972 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008973 Py_DECREF(str_obj);
8974 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008975 }
Tim Petersced69f82003-09-16 20:30:58 +00008976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 kind1 = PyUnicode_KIND(str_obj);
8978 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008979 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008982 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008983 if (kind2 > kind) {
8984 Py_DECREF(sub_obj);
8985 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008986 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008987 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008988 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 if (!buf2)
8991 goto onError;
8992 len1 = PyUnicode_GET_LENGTH(str_obj);
8993 len2 = PyUnicode_GET_LENGTH(sub_obj);
8994
8995 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008996 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008998 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8999 result = asciilib_count(
9000 ((Py_UCS1*)buf1) + start, end - start,
9001 buf2, len2, PY_SSIZE_T_MAX
9002 );
9003 else
9004 result = ucs1lib_count(
9005 ((Py_UCS1*)buf1) + start, end - start,
9006 buf2, len2, PY_SSIZE_T_MAX
9007 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009008 break;
9009 case PyUnicode_2BYTE_KIND:
9010 result = ucs2lib_count(
9011 ((Py_UCS2*)buf1) + start, end - start,
9012 buf2, len2, PY_SSIZE_T_MAX
9013 );
9014 break;
9015 case PyUnicode_4BYTE_KIND:
9016 result = ucs4lib_count(
9017 ((Py_UCS4*)buf1) + start, end - start,
9018 buf2, len2, PY_SSIZE_T_MAX
9019 );
9020 break;
9021 default:
9022 assert(0); result = 0;
9023 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009024
9025 Py_DECREF(sub_obj);
9026 Py_DECREF(str_obj);
9027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028 if (kind2 != kind)
9029 PyMem_Free(buf2);
9030
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032 onError:
9033 Py_DECREF(sub_obj);
9034 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035 if (kind2 != kind && buf2)
9036 PyMem_Free(buf2);
9037 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038}
9039
Alexander Belopolsky40018472011-02-26 01:02:56 +00009040Py_ssize_t
9041PyUnicode_Find(PyObject *str,
9042 PyObject *sub,
9043 Py_ssize_t start,
9044 Py_ssize_t end,
9045 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009046{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009047 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009048
Guido van Rossumd57fd912000-03-10 22:53:23 +00009049 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009050 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009051 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009052 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009053 if (!sub) {
9054 Py_DECREF(str);
9055 return -2;
9056 }
9057 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9058 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009059 Py_DECREF(str);
9060 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061 }
Tim Petersced69f82003-09-16 20:30:58 +00009062
Victor Stinner794d5672011-10-10 03:21:36 +02009063 result = any_find_slice(direction,
9064 str, sub, start, end
9065 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009066
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009068 Py_DECREF(sub);
9069
Guido van Rossumd57fd912000-03-10 22:53:23 +00009070 return result;
9071}
9072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073Py_ssize_t
9074PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9075 Py_ssize_t start, Py_ssize_t end,
9076 int direction)
9077{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009079 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 if (PyUnicode_READY(str) == -1)
9081 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009082 if (start < 0 || end < 0) {
9083 PyErr_SetString(PyExc_IndexError, "string index out of range");
9084 return -2;
9085 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 if (end > PyUnicode_GET_LENGTH(str))
9087 end = PyUnicode_GET_LENGTH(str);
9088 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009089 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9090 kind, end-start, ch, direction);
9091 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009093 else
9094 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095}
9096
Alexander Belopolsky40018472011-02-26 01:02:56 +00009097static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009098tailmatch(PyObject *self,
9099 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009100 Py_ssize_t start,
9101 Py_ssize_t end,
9102 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009103{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104 int kind_self;
9105 int kind_sub;
9106 void *data_self;
9107 void *data_sub;
9108 Py_ssize_t offset;
9109 Py_ssize_t i;
9110 Py_ssize_t end_sub;
9111
9112 if (PyUnicode_READY(self) == -1 ||
9113 PyUnicode_READY(substring) == -1)
9114 return 0;
9115
9116 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009117 return 1;
9118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9120 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009121 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009122 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124 kind_self = PyUnicode_KIND(self);
9125 data_self = PyUnicode_DATA(self);
9126 kind_sub = PyUnicode_KIND(substring);
9127 data_sub = PyUnicode_DATA(substring);
9128 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9129
9130 if (direction > 0)
9131 offset = end;
9132 else
9133 offset = start;
9134
9135 if (PyUnicode_READ(kind_self, data_self, offset) ==
9136 PyUnicode_READ(kind_sub, data_sub, 0) &&
9137 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9138 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9139 /* If both are of the same kind, memcmp is sufficient */
9140 if (kind_self == kind_sub) {
9141 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009142 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 data_sub,
9144 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009145 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 }
9147 /* otherwise we have to compare each character by first accesing it */
9148 else {
9149 /* We do not need to compare 0 and len(substring)-1 because
9150 the if statement above ensured already that they are equal
9151 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009152 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009153 for (i = 1; i < end_sub; ++i) {
9154 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9155 PyUnicode_READ(kind_sub, data_sub, i))
9156 return 0;
9157 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160 }
9161
9162 return 0;
9163}
9164
Alexander Belopolsky40018472011-02-26 01:02:56 +00009165Py_ssize_t
9166PyUnicode_Tailmatch(PyObject *str,
9167 PyObject *substr,
9168 Py_ssize_t start,
9169 Py_ssize_t end,
9170 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009172 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009173
Guido van Rossumd57fd912000-03-10 22:53:23 +00009174 str = PyUnicode_FromObject(str);
9175 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177 substr = PyUnicode_FromObject(substr);
9178 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009179 Py_DECREF(str);
9180 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181 }
Tim Petersced69f82003-09-16 20:30:58 +00009182
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009183 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009184 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185 Py_DECREF(str);
9186 Py_DECREF(substr);
9187 return result;
9188}
9189
Guido van Rossumd57fd912000-03-10 22:53:23 +00009190/* Apply fixfct filter to the Unicode object self and return a
9191 reference to the modified object */
9192
Alexander Belopolsky40018472011-02-26 01:02:56 +00009193static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009194fixup(PyObject *self,
9195 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009196{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 PyObject *u;
9198 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009199 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009200
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009201 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009202 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009203 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009204 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 /* fix functions return the new maximum character in a string,
9207 if the kind of the resulting unicode object does not change,
9208 everything is fine. Otherwise we need to change the string kind
9209 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009210 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009211
9212 if (maxchar_new == 0) {
9213 /* no changes */;
9214 if (PyUnicode_CheckExact(self)) {
9215 Py_DECREF(u);
9216 Py_INCREF(self);
9217 return self;
9218 }
9219 else
9220 return u;
9221 }
9222
Victor Stinnere6abb482012-05-02 01:15:40 +02009223 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224
Victor Stinnereaab6042011-12-11 22:22:39 +01009225 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009226 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009227
9228 /* In case the maximum character changed, we need to
9229 convert the string to the new category. */
9230 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9231 if (v == NULL) {
9232 Py_DECREF(u);
9233 return NULL;
9234 }
9235 if (maxchar_new > maxchar_old) {
9236 /* If the maxchar increased so that the kind changed, not all
9237 characters are representable anymore and we need to fix the
9238 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009239 _PyUnicode_FastCopyCharacters(v, 0,
9240 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009241 maxchar_old = fixfct(v);
9242 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243 }
9244 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009245 _PyUnicode_FastCopyCharacters(v, 0,
9246 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009248 Py_DECREF(u);
9249 assert(_PyUnicode_CheckConsistency(v, 1));
9250 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251}
9252
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009253static PyObject *
9254ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009256 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9257 char *resdata, *data = PyUnicode_DATA(self);
9258 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009259
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009260 res = PyUnicode_New(len, 127);
9261 if (res == NULL)
9262 return NULL;
9263 resdata = PyUnicode_DATA(res);
9264 if (lower)
9265 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009266 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009267 _Py_bytes_upper(resdata, data, len);
9268 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269}
9270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009271static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009272handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009273{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009274 Py_ssize_t j;
9275 int final_sigma;
9276 Py_UCS4 c;
9277 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009278
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009279 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9280
9281 where ! is a negation and \p{xxx} is a character with property xxx.
9282 */
9283 for (j = i - 1; j >= 0; j--) {
9284 c = PyUnicode_READ(kind, data, j);
9285 if (!_PyUnicode_IsCaseIgnorable(c))
9286 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009287 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009288 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9289 if (final_sigma) {
9290 for (j = i + 1; j < length; j++) {
9291 c = PyUnicode_READ(kind, data, j);
9292 if (!_PyUnicode_IsCaseIgnorable(c))
9293 break;
9294 }
9295 final_sigma = j == length || !_PyUnicode_IsCased(c);
9296 }
9297 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298}
9299
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009300static int
9301lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9302 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009303{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009304 /* Obscure special case. */
9305 if (c == 0x3A3) {
9306 mapped[0] = handle_capital_sigma(kind, data, length, i);
9307 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009308 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009309 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009310}
9311
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009312static Py_ssize_t
9313do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009314{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009315 Py_ssize_t i, k = 0;
9316 int n_res, j;
9317 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009318
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009319 c = PyUnicode_READ(kind, data, 0);
9320 n_res = _PyUnicode_ToUpperFull(c, mapped);
9321 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009322 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009323 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009325 for (i = 1; i < length; i++) {
9326 c = PyUnicode_READ(kind, data, i);
9327 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9328 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009329 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009330 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009331 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009332 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009333 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009334}
9335
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009336static Py_ssize_t
9337do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9338 Py_ssize_t i, k = 0;
9339
9340 for (i = 0; i < length; i++) {
9341 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9342 int n_res, j;
9343 if (Py_UNICODE_ISUPPER(c)) {
9344 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9345 }
9346 else if (Py_UNICODE_ISLOWER(c)) {
9347 n_res = _PyUnicode_ToUpperFull(c, mapped);
9348 }
9349 else {
9350 n_res = 1;
9351 mapped[0] = c;
9352 }
9353 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009354 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009355 res[k++] = mapped[j];
9356 }
9357 }
9358 return k;
9359}
9360
9361static Py_ssize_t
9362do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9363 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009365 Py_ssize_t i, k = 0;
9366
9367 for (i = 0; i < length; i++) {
9368 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9369 int n_res, j;
9370 if (lower)
9371 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9372 else
9373 n_res = _PyUnicode_ToUpperFull(c, mapped);
9374 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009375 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009376 res[k++] = mapped[j];
9377 }
9378 }
9379 return k;
9380}
9381
9382static Py_ssize_t
9383do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9384{
9385 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9386}
9387
9388static Py_ssize_t
9389do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9390{
9391 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9392}
9393
Benjamin Petersone51757f2012-01-12 21:10:29 -05009394static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009395do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9396{
9397 Py_ssize_t i, k = 0;
9398
9399 for (i = 0; i < length; i++) {
9400 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9401 Py_UCS4 mapped[3];
9402 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9403 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009404 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009405 res[k++] = mapped[j];
9406 }
9407 }
9408 return k;
9409}
9410
9411static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009412do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9413{
9414 Py_ssize_t i, k = 0;
9415 int previous_is_cased;
9416
9417 previous_is_cased = 0;
9418 for (i = 0; i < length; i++) {
9419 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9420 Py_UCS4 mapped[3];
9421 int n_res, j;
9422
9423 if (previous_is_cased)
9424 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9425 else
9426 n_res = _PyUnicode_ToTitleFull(c, mapped);
9427
9428 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009429 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009430 res[k++] = mapped[j];
9431 }
9432
9433 previous_is_cased = _PyUnicode_IsCased(c);
9434 }
9435 return k;
9436}
9437
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009438static PyObject *
9439case_operation(PyObject *self,
9440 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9441{
9442 PyObject *res = NULL;
9443 Py_ssize_t length, newlength = 0;
9444 int kind, outkind;
9445 void *data, *outdata;
9446 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9447
Benjamin Petersoneea48462012-01-16 14:28:50 -05009448 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009449
9450 kind = PyUnicode_KIND(self);
9451 data = PyUnicode_DATA(self);
9452 length = PyUnicode_GET_LENGTH(self);
9453 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9454 if (tmp == NULL)
9455 return PyErr_NoMemory();
9456 newlength = perform(kind, data, length, tmp, &maxchar);
9457 res = PyUnicode_New(newlength, maxchar);
9458 if (res == NULL)
9459 goto leave;
9460 tmpend = tmp + newlength;
9461 outdata = PyUnicode_DATA(res);
9462 outkind = PyUnicode_KIND(res);
9463 switch (outkind) {
9464 case PyUnicode_1BYTE_KIND:
9465 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9466 break;
9467 case PyUnicode_2BYTE_KIND:
9468 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9469 break;
9470 case PyUnicode_4BYTE_KIND:
9471 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9472 break;
9473 default:
9474 assert(0);
9475 break;
9476 }
9477 leave:
9478 PyMem_FREE(tmp);
9479 return res;
9480}
9481
Tim Peters8ce9f162004-08-27 01:49:32 +00009482PyObject *
9483PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009486 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009488 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009489 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9490 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009491 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009493 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009494 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009495 int use_memcpy;
9496 unsigned char *res_data = NULL, *sep_data = NULL;
9497 PyObject *last_obj;
9498 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499
Tim Peters05eba1f2004-08-27 21:32:02 +00009500 fseq = PySequence_Fast(seq, "");
9501 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009502 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009503 }
9504
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009505 /* NOTE: the following code can't call back into Python code,
9506 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009507 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009508
Tim Peters05eba1f2004-08-27 21:32:02 +00009509 seqlen = PySequence_Fast_GET_SIZE(fseq);
9510 /* If empty sequence, return u"". */
9511 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009512 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009513 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009514 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009515
Tim Peters05eba1f2004-08-27 21:32:02 +00009516 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009517 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009518 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009519 if (seqlen == 1) {
9520 if (PyUnicode_CheckExact(items[0])) {
9521 res = items[0];
9522 Py_INCREF(res);
9523 Py_DECREF(fseq);
9524 return res;
9525 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009526 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009527 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009528 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009529 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009530 /* Set up sep and seplen */
9531 if (separator == NULL) {
9532 /* fall back to a blank space separator */
9533 sep = PyUnicode_FromOrdinal(' ');
9534 if (!sep)
9535 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009536 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009537 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009538 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009539 else {
9540 if (!PyUnicode_Check(separator)) {
9541 PyErr_Format(PyExc_TypeError,
9542 "separator: expected str instance,"
9543 " %.80s found",
9544 Py_TYPE(separator)->tp_name);
9545 goto onError;
9546 }
9547 if (PyUnicode_READY(separator))
9548 goto onError;
9549 sep = separator;
9550 seplen = PyUnicode_GET_LENGTH(separator);
9551 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9552 /* inc refcount to keep this code path symmetric with the
9553 above case of a blank separator */
9554 Py_INCREF(sep);
9555 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009556 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009557 }
9558
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009559 /* There are at least two things to join, or else we have a subclass
9560 * of str in the sequence.
9561 * Do a pre-pass to figure out the total amount of space we'll
9562 * need (sz), and see whether all argument are strings.
9563 */
9564 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009565#ifdef Py_DEBUG
9566 use_memcpy = 0;
9567#else
9568 use_memcpy = 1;
9569#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009570 for (i = 0; i < seqlen; i++) {
9571 const Py_ssize_t old_sz = sz;
9572 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009573 if (!PyUnicode_Check(item)) {
9574 PyErr_Format(PyExc_TypeError,
9575 "sequence item %zd: expected str instance,"
9576 " %.80s found",
9577 i, Py_TYPE(item)->tp_name);
9578 goto onError;
9579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 if (PyUnicode_READY(item) == -1)
9581 goto onError;
9582 sz += PyUnicode_GET_LENGTH(item);
9583 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009584 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009585 if (i != 0)
9586 sz += seplen;
9587 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9588 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009589 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009590 goto onError;
9591 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009592 if (use_memcpy && last_obj != NULL) {
9593 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9594 use_memcpy = 0;
9595 }
9596 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009597 }
Tim Petersced69f82003-09-16 20:30:58 +00009598
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009599 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009600 if (res == NULL)
9601 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009602
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009603 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009604#ifdef Py_DEBUG
9605 use_memcpy = 0;
9606#else
9607 if (use_memcpy) {
9608 res_data = PyUnicode_1BYTE_DATA(res);
9609 kind = PyUnicode_KIND(res);
9610 if (seplen != 0)
9611 sep_data = PyUnicode_1BYTE_DATA(sep);
9612 }
9613#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009614 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009615 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009616 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009617 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009618 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 if (use_memcpy) {
9620 Py_MEMCPY(res_data,
9621 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009622 kind * seplen);
9623 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009624 }
9625 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009626 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009627 res_offset += seplen;
9628 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009629 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009630 itemlen = PyUnicode_GET_LENGTH(item);
9631 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009632 if (use_memcpy) {
9633 Py_MEMCPY(res_data,
9634 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009635 kind * itemlen);
9636 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009637 }
9638 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009639 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009640 res_offset += itemlen;
9641 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009642 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009643 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009644 if (use_memcpy)
9645 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009646 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009647 else
9648 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009649
Tim Peters05eba1f2004-08-27 21:32:02 +00009650 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009652 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654
Benjamin Peterson29060642009-01-31 22:14:21 +00009655 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009656 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009657 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009658 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659 return NULL;
9660}
9661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662#define FILL(kind, data, value, start, length) \
9663 do { \
9664 Py_ssize_t i_ = 0; \
9665 assert(kind != PyUnicode_WCHAR_KIND); \
9666 switch ((kind)) { \
9667 case PyUnicode_1BYTE_KIND: { \
9668 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009669 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670 break; \
9671 } \
9672 case PyUnicode_2BYTE_KIND: { \
9673 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9674 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9675 break; \
9676 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009677 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9679 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9680 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009681 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 } \
9683 } \
9684 } while (0)
9685
Victor Stinnerd3f08822012-05-29 12:57:52 +02009686void
9687_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9688 Py_UCS4 fill_char)
9689{
9690 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9691 const void *data = PyUnicode_DATA(unicode);
9692 assert(PyUnicode_IS_READY(unicode));
9693 assert(unicode_modifiable(unicode));
9694 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9695 assert(start >= 0);
9696 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9697 FILL(kind, data, fill_char, start, length);
9698}
9699
Victor Stinner3fe55312012-01-04 00:33:50 +01009700Py_ssize_t
9701PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9702 Py_UCS4 fill_char)
9703{
9704 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009705
9706 if (!PyUnicode_Check(unicode)) {
9707 PyErr_BadInternalCall();
9708 return -1;
9709 }
9710 if (PyUnicode_READY(unicode) == -1)
9711 return -1;
9712 if (unicode_check_modifiable(unicode))
9713 return -1;
9714
Victor Stinnerd3f08822012-05-29 12:57:52 +02009715 if (start < 0) {
9716 PyErr_SetString(PyExc_IndexError, "string index out of range");
9717 return -1;
9718 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009719 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9720 PyErr_SetString(PyExc_ValueError,
9721 "fill character is bigger than "
9722 "the string maximum character");
9723 return -1;
9724 }
9725
9726 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9727 length = Py_MIN(maxlen, length);
9728 if (length <= 0)
9729 return 0;
9730
Victor Stinnerd3f08822012-05-29 12:57:52 +02009731 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009732 return length;
9733}
9734
Victor Stinner9310abb2011-10-05 00:59:23 +02009735static PyObject *
9736pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009737 Py_ssize_t left,
9738 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009739 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009740{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009741 PyObject *u;
9742 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009743 int kind;
9744 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745
9746 if (left < 0)
9747 left = 0;
9748 if (right < 0)
9749 right = 0;
9750
Victor Stinnerc4b49542011-12-11 22:44:26 +01009751 if (left == 0 && right == 0)
9752 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009754 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9755 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009756 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9757 return NULL;
9758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009760 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009761 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009762 if (!u)
9763 return NULL;
9764
9765 kind = PyUnicode_KIND(u);
9766 data = PyUnicode_DATA(u);
9767 if (left)
9768 FILL(kind, data, fill, 0, left);
9769 if (right)
9770 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009771 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009772 assert(_PyUnicode_CheckConsistency(u, 1));
9773 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774}
9775
Alexander Belopolsky40018472011-02-26 01:02:56 +00009776PyObject *
9777PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009778{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009779 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780
9781 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009782 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009783 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009784 if (PyUnicode_READY(string) == -1) {
9785 Py_DECREF(string);
9786 return NULL;
9787 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788
Benjamin Petersonead6b532011-12-20 17:23:42 -06009789 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009791 if (PyUnicode_IS_ASCII(string))
9792 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009793 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009794 PyUnicode_GET_LENGTH(string), keepends);
9795 else
9796 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009797 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009798 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009799 break;
9800 case PyUnicode_2BYTE_KIND:
9801 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009802 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 PyUnicode_GET_LENGTH(string), keepends);
9804 break;
9805 case PyUnicode_4BYTE_KIND:
9806 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009807 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009808 PyUnicode_GET_LENGTH(string), keepends);
9809 break;
9810 default:
9811 assert(0);
9812 list = 0;
9813 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009814 Py_DECREF(string);
9815 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009816}
9817
Alexander Belopolsky40018472011-02-26 01:02:56 +00009818static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009819split(PyObject *self,
9820 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009821 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009822{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009823 int kind1, kind2, kind;
9824 void *buf1, *buf2;
9825 Py_ssize_t len1, len2;
9826 PyObject* out;
9827
Guido van Rossumd57fd912000-03-10 22:53:23 +00009828 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009829 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 if (PyUnicode_READY(self) == -1)
9832 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009834 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009835 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009837 if (PyUnicode_IS_ASCII(self))
9838 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009839 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009840 PyUnicode_GET_LENGTH(self), maxcount
9841 );
9842 else
9843 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009844 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009845 PyUnicode_GET_LENGTH(self), maxcount
9846 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 case PyUnicode_2BYTE_KIND:
9848 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009849 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 PyUnicode_GET_LENGTH(self), maxcount
9851 );
9852 case PyUnicode_4BYTE_KIND:
9853 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009854 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 PyUnicode_GET_LENGTH(self), maxcount
9856 );
9857 default:
9858 assert(0);
9859 return NULL;
9860 }
9861
9862 if (PyUnicode_READY(substring) == -1)
9863 return NULL;
9864
9865 kind1 = PyUnicode_KIND(self);
9866 kind2 = PyUnicode_KIND(substring);
9867 kind = kind1 > kind2 ? kind1 : kind2;
9868 buf1 = PyUnicode_DATA(self);
9869 buf2 = PyUnicode_DATA(substring);
9870 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009871 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 if (!buf1)
9873 return NULL;
9874 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009875 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 if (!buf2) {
9877 if (kind1 != kind) PyMem_Free(buf1);
9878 return NULL;
9879 }
9880 len1 = PyUnicode_GET_LENGTH(self);
9881 len2 = PyUnicode_GET_LENGTH(substring);
9882
Benjamin Petersonead6b532011-12-20 17:23:42 -06009883 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009885 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9886 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009887 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009888 else
9889 out = ucs1lib_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 case PyUnicode_2BYTE_KIND:
9893 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009894 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 break;
9896 case PyUnicode_4BYTE_KIND:
9897 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009898 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 break;
9900 default:
9901 out = NULL;
9902 }
9903 if (kind1 != kind)
9904 PyMem_Free(buf1);
9905 if (kind2 != kind)
9906 PyMem_Free(buf2);
9907 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009908}
9909
Alexander Belopolsky40018472011-02-26 01:02:56 +00009910static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009911rsplit(PyObject *self,
9912 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009913 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009914{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 int kind1, kind2, kind;
9916 void *buf1, *buf2;
9917 Py_ssize_t len1, len2;
9918 PyObject* out;
9919
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009920 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009921 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 if (PyUnicode_READY(self) == -1)
9924 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009927 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009929 if (PyUnicode_IS_ASCII(self))
9930 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009931 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009932 PyUnicode_GET_LENGTH(self), maxcount
9933 );
9934 else
9935 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009936 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009937 PyUnicode_GET_LENGTH(self), maxcount
9938 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 case PyUnicode_2BYTE_KIND:
9940 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009941 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 PyUnicode_GET_LENGTH(self), maxcount
9943 );
9944 case PyUnicode_4BYTE_KIND:
9945 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009946 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 PyUnicode_GET_LENGTH(self), maxcount
9948 );
9949 default:
9950 assert(0);
9951 return NULL;
9952 }
9953
9954 if (PyUnicode_READY(substring) == -1)
9955 return NULL;
9956
9957 kind1 = PyUnicode_KIND(self);
9958 kind2 = PyUnicode_KIND(substring);
9959 kind = kind1 > kind2 ? kind1 : kind2;
9960 buf1 = PyUnicode_DATA(self);
9961 buf2 = PyUnicode_DATA(substring);
9962 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009963 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 if (!buf1)
9965 return NULL;
9966 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009967 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 if (!buf2) {
9969 if (kind1 != kind) PyMem_Free(buf1);
9970 return NULL;
9971 }
9972 len1 = PyUnicode_GET_LENGTH(self);
9973 len2 = PyUnicode_GET_LENGTH(substring);
9974
Benjamin Petersonead6b532011-12-20 17:23:42 -06009975 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9978 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009979 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009980 else
9981 out = ucs1lib_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 case PyUnicode_2BYTE_KIND:
9985 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009986 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 break;
9988 case PyUnicode_4BYTE_KIND:
9989 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009990 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 break;
9992 default:
9993 out = NULL;
9994 }
9995 if (kind1 != kind)
9996 PyMem_Free(buf1);
9997 if (kind2 != kind)
9998 PyMem_Free(buf2);
9999 return out;
10000}
10001
10002static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010003anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10004 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010006 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010008 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10009 return asciilib_find(buf1, len1, buf2, len2, offset);
10010 else
10011 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 case PyUnicode_2BYTE_KIND:
10013 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10014 case PyUnicode_4BYTE_KIND:
10015 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10016 }
10017 assert(0);
10018 return -1;
10019}
10020
10021static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010022anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10023 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010025 switch (kind) {
10026 case PyUnicode_1BYTE_KIND:
10027 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10028 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10029 else
10030 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10031 case PyUnicode_2BYTE_KIND:
10032 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10033 case PyUnicode_4BYTE_KIND:
10034 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10035 }
10036 assert(0);
10037 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010038}
10039
Alexander Belopolsky40018472011-02-26 01:02:56 +000010040static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041replace(PyObject *self, PyObject *str1,
10042 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 PyObject *u;
10045 char *sbuf = PyUnicode_DATA(self);
10046 char *buf1 = PyUnicode_DATA(str1);
10047 char *buf2 = PyUnicode_DATA(str2);
10048 int srelease = 0, release1 = 0, release2 = 0;
10049 int skind = PyUnicode_KIND(self);
10050 int kind1 = PyUnicode_KIND(str1);
10051 int kind2 = PyUnicode_KIND(str2);
10052 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10053 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10054 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010055 int mayshrink;
10056 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010057
10058 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010059 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010061 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010062
Victor Stinner59de0ee2011-10-07 10:01:28 +020010063 if (str1 == str2)
10064 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 if (skind < kind1)
10066 /* substring too wide to be present */
10067 goto nothing;
10068
Victor Stinner49a0a212011-10-12 23:46:10 +020010069 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10070 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10071 /* Replacing str1 with str2 may cause a maxchar reduction in the
10072 result string. */
10073 mayshrink = (maxchar_str2 < maxchar);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010074 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010077 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010079 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010081 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010082 Py_UCS4 u1, u2;
10083 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010084 Py_ssize_t index, pos;
10085 char *src;
10086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010088 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10089 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010090 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010093 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010095 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010097
10098 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10099 index = 0;
10100 src = sbuf;
10101 while (--maxcount)
10102 {
10103 pos++;
10104 src += pos * PyUnicode_KIND(self);
10105 slen -= pos;
10106 index += pos;
10107 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10108 if (pos < 0)
10109 break;
10110 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10111 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010112 }
10113 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 int rkind = skind;
10115 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010116 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 if (kind1 < rkind) {
10119 /* widen substring */
10120 buf1 = _PyUnicode_AsKind(str1, rkind);
10121 if (!buf1) goto error;
10122 release1 = 1;
10123 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010125 if (i < 0)
10126 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 if (rkind > kind2) {
10128 /* widen replacement */
10129 buf2 = _PyUnicode_AsKind(str2, rkind);
10130 if (!buf2) goto error;
10131 release2 = 1;
10132 }
10133 else if (rkind < kind2) {
10134 /* widen self and buf1 */
10135 rkind = kind2;
10136 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010137 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 sbuf = _PyUnicode_AsKind(self, rkind);
10139 if (!sbuf) goto error;
10140 srelease = 1;
10141 buf1 = _PyUnicode_AsKind(str1, rkind);
10142 if (!buf1) goto error;
10143 release1 = 1;
10144 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010145 u = PyUnicode_New(slen, maxchar);
10146 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010148 assert(PyUnicode_KIND(u) == rkind);
10149 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010150
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010151 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010152 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010153 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010155 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010157
10158 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010159 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010160 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010161 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010162 if (i == -1)
10163 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010164 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010166 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010168 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010170 }
10171 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010173 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 int rkind = skind;
10175 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 buf1 = _PyUnicode_AsKind(str1, rkind);
10180 if (!buf1) goto error;
10181 release1 = 1;
10182 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010184 if (n == 0)
10185 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010187 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 buf2 = _PyUnicode_AsKind(str2, rkind);
10189 if (!buf2) goto error;
10190 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010193 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 rkind = kind2;
10195 sbuf = _PyUnicode_AsKind(self, rkind);
10196 if (!sbuf) goto error;
10197 srelease = 1;
10198 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010199 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 buf1 = _PyUnicode_AsKind(str1, rkind);
10201 if (!buf1) goto error;
10202 release1 = 1;
10203 }
10204 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10205 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010206 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 PyErr_SetString(PyExc_OverflowError,
10208 "replace string is too long");
10209 goto error;
10210 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010211 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010212 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010213 _Py_INCREF_UNICODE_EMPTY();
10214 if (!unicode_empty)
10215 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 u = unicode_empty;
10217 goto done;
10218 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010219 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 PyErr_SetString(PyExc_OverflowError,
10221 "replace string is too long");
10222 goto error;
10223 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010224 u = PyUnicode_New(new_size, maxchar);
10225 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010227 assert(PyUnicode_KIND(u) == rkind);
10228 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 ires = i = 0;
10230 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010231 while (n-- > 0) {
10232 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010234 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010236 if (j == -1)
10237 break;
10238 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010239 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010240 memcpy(res + rkind * ires,
10241 sbuf + rkind * i,
10242 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010244 }
10245 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010247 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010249 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010255 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010256 memcpy(res + rkind * ires,
10257 sbuf + rkind * i,
10258 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010259 }
10260 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 /* interleave */
10262 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010263 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010265 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010267 if (--n <= 0)
10268 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010269 memcpy(res + rkind * ires,
10270 sbuf + rkind * i,
10271 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 ires++;
10273 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010274 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010275 memcpy(res + rkind * ires,
10276 sbuf + rkind * i,
10277 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010278 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010279 }
10280
10281 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010282 unicode_adjust_maxchar(&u);
10283 if (u == NULL)
10284 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010285 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010286
10287 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 if (srelease)
10289 PyMem_FREE(sbuf);
10290 if (release1)
10291 PyMem_FREE(buf1);
10292 if (release2)
10293 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010294 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010296
Benjamin Peterson29060642009-01-31 22:14:21 +000010297 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010298 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 if (srelease)
10300 PyMem_FREE(sbuf);
10301 if (release1)
10302 PyMem_FREE(buf1);
10303 if (release2)
10304 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010305 return unicode_result_unchanged(self);
10306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 error:
10308 if (srelease && sbuf)
10309 PyMem_FREE(sbuf);
10310 if (release1 && buf1)
10311 PyMem_FREE(buf1);
10312 if (release2 && buf2)
10313 PyMem_FREE(buf2);
10314 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010315}
10316
10317/* --- Unicode Object Methods --------------------------------------------- */
10318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010319PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010320 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321\n\
10322Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010323characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010324
10325static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010326unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010328 if (PyUnicode_READY(self) == -1)
10329 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010330 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010331}
10332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010333PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010334 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010335\n\
10336Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010337have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010338
10339static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010340unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010342 if (PyUnicode_READY(self) == -1)
10343 return NULL;
10344 if (PyUnicode_GET_LENGTH(self) == 0)
10345 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010346 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010347}
10348
Benjamin Petersond5890c82012-01-14 13:23:30 -050010349PyDoc_STRVAR(casefold__doc__,
10350 "S.casefold() -> str\n\
10351\n\
10352Return a version of S suitable for caseless comparisons.");
10353
10354static PyObject *
10355unicode_casefold(PyObject *self)
10356{
10357 if (PyUnicode_READY(self) == -1)
10358 return NULL;
10359 if (PyUnicode_IS_ASCII(self))
10360 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010361 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010362}
10363
10364
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010365/* Argument converter. Coerces to a single unicode character */
10366
10367static int
10368convert_uc(PyObject *obj, void *addr)
10369{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010371 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010372
Benjamin Peterson14339b62009-01-31 16:36:08 +000010373 uniobj = PyUnicode_FromObject(obj);
10374 if (uniobj == NULL) {
10375 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010376 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010377 return 0;
10378 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010380 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010381 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010382 Py_DECREF(uniobj);
10383 return 0;
10384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010386 Py_DECREF(uniobj);
10387 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010388}
10389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010390PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010391 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010393Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010394done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395
10396static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010397unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010399 Py_ssize_t marg, left;
10400 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 Py_UCS4 fillchar = ' ';
10402
Victor Stinnere9a29352011-10-01 02:14:59 +020010403 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010405
Benjamin Petersonbac79492012-01-14 13:34:47 -050010406 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010407 return NULL;
10408
Victor Stinnerc4b49542011-12-11 22:44:26 +010010409 if (PyUnicode_GET_LENGTH(self) >= width)
10410 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411
Victor Stinnerc4b49542011-12-11 22:44:26 +010010412 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413 left = marg / 2 + (marg & width & 1);
10414
Victor Stinner9310abb2011-10-05 00:59:23 +020010415 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010416}
10417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418/* This function assumes that str1 and str2 are readied by the caller. */
10419
Marc-André Lemburge5034372000-08-08 08:04:29 +000010420static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010421unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010422{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 int kind1, kind2;
10424 void *data1, *data2;
10425 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 kind1 = PyUnicode_KIND(str1);
10428 kind2 = PyUnicode_KIND(str2);
10429 data1 = PyUnicode_DATA(str1);
10430 data2 = PyUnicode_DATA(str2);
10431 len1 = PyUnicode_GET_LENGTH(str1);
10432 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 for (i = 0; i < len1 && i < len2; ++i) {
10435 Py_UCS4 c1, c2;
10436 c1 = PyUnicode_READ(kind1, data1, i);
10437 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010438
10439 if (c1 != c2)
10440 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010441 }
10442
10443 return (len1 < len2) ? -1 : (len1 != len2);
10444}
10445
Alexander Belopolsky40018472011-02-26 01:02:56 +000010446int
10447PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010449 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10450 if (PyUnicode_READY(left) == -1 ||
10451 PyUnicode_READY(right) == -1)
10452 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010453 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010455 PyErr_Format(PyExc_TypeError,
10456 "Can't compare %.100s and %.100s",
10457 left->ob_type->tp_name,
10458 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010459 return -1;
10460}
10461
Martin v. Löwis5b222132007-06-10 09:51:05 +000010462int
10463PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 Py_ssize_t i;
10466 int kind;
10467 void *data;
10468 Py_UCS4 chr;
10469
Victor Stinner910337b2011-10-03 03:20:16 +020010470 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 if (PyUnicode_READY(uni) == -1)
10472 return -1;
10473 kind = PyUnicode_KIND(uni);
10474 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010475 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10477 if (chr != str[i])
10478 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010479 /* This check keeps Python strings that end in '\0' from comparing equal
10480 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010482 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010483 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010484 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010485 return 0;
10486}
10487
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010488
Benjamin Peterson29060642009-01-31 22:14:21 +000010489#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010490 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010491
Alexander Belopolsky40018472011-02-26 01:02:56 +000010492PyObject *
10493PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010494{
10495 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010496
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010497 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10498 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (PyUnicode_READY(left) == -1 ||
10500 PyUnicode_READY(right) == -1)
10501 return NULL;
10502 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10503 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010504 if (op == Py_EQ) {
10505 Py_INCREF(Py_False);
10506 return Py_False;
10507 }
10508 if (op == Py_NE) {
10509 Py_INCREF(Py_True);
10510 return Py_True;
10511 }
10512 }
10513 if (left == right)
10514 result = 0;
10515 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010516 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010517
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010518 /* Convert the return value to a Boolean */
10519 switch (op) {
10520 case Py_EQ:
10521 v = TEST_COND(result == 0);
10522 break;
10523 case Py_NE:
10524 v = TEST_COND(result != 0);
10525 break;
10526 case Py_LE:
10527 v = TEST_COND(result <= 0);
10528 break;
10529 case Py_GE:
10530 v = TEST_COND(result >= 0);
10531 break;
10532 case Py_LT:
10533 v = TEST_COND(result == -1);
10534 break;
10535 case Py_GT:
10536 v = TEST_COND(result == 1);
10537 break;
10538 default:
10539 PyErr_BadArgument();
10540 return NULL;
10541 }
10542 Py_INCREF(v);
10543 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010544 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010545
Brian Curtindfc80e32011-08-10 20:28:54 -050010546 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010547}
10548
Alexander Belopolsky40018472011-02-26 01:02:56 +000010549int
10550PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010551{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010552 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 int kind1, kind2, kind;
10554 void *buf1, *buf2;
10555 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010556 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010557
10558 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010559 sub = PyUnicode_FromObject(element);
10560 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 PyErr_Format(PyExc_TypeError,
10562 "'in <string>' requires string as left operand, not %s",
10563 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010564 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010565 }
10566
Thomas Wouters477c8d52006-05-27 19:21:47 +000010567 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010568 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569 Py_DECREF(sub);
10570 return -1;
10571 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010572 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10573 Py_DECREF(sub);
10574 Py_DECREF(str);
10575 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 kind1 = PyUnicode_KIND(str);
10578 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010579 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 buf1 = PyUnicode_DATA(str);
10581 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010582 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010583 if (kind2 > kind) {
10584 Py_DECREF(sub);
10585 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010586 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010587 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010588 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (!buf2) {
10591 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010592 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 return -1;
10594 }
10595 len1 = PyUnicode_GET_LENGTH(str);
10596 len2 = PyUnicode_GET_LENGTH(sub);
10597
Benjamin Petersonead6b532011-12-20 17:23:42 -060010598 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 case PyUnicode_1BYTE_KIND:
10600 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10601 break;
10602 case PyUnicode_2BYTE_KIND:
10603 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10604 break;
10605 case PyUnicode_4BYTE_KIND:
10606 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10607 break;
10608 default:
10609 result = -1;
10610 assert(0);
10611 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612
10613 Py_DECREF(str);
10614 Py_DECREF(sub);
10615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 if (kind2 != kind)
10617 PyMem_Free(buf2);
10618
Guido van Rossum403d68b2000-03-13 15:55:09 +000010619 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010620}
10621
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622/* Concat to string or Unicode object giving a new Unicode object. */
10623
Alexander Belopolsky40018472011-02-26 01:02:56 +000010624PyObject *
10625PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010628 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010629 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630
10631 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010634 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010637 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638
10639 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010640 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010641 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010644 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010645 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647 }
10648
Victor Stinner488fa492011-12-12 00:01:39 +010010649 u_len = PyUnicode_GET_LENGTH(u);
10650 v_len = PyUnicode_GET_LENGTH(v);
10651 if (u_len > PY_SSIZE_T_MAX - v_len) {
10652 PyErr_SetString(PyExc_OverflowError,
10653 "strings are too large to concat");
10654 goto onError;
10655 }
10656 new_len = u_len + v_len;
10657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010659 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010660 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010663 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010665 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010666 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10667 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668 Py_DECREF(u);
10669 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010670 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672
Benjamin Peterson29060642009-01-31 22:14:21 +000010673 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674 Py_XDECREF(u);
10675 Py_XDECREF(v);
10676 return NULL;
10677}
10678
Walter Dörwald1ab83302007-05-18 17:15:44 +000010679void
Victor Stinner23e56682011-10-03 03:54:37 +020010680PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010681{
Victor Stinner23e56682011-10-03 03:54:37 +020010682 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010683 Py_UCS4 maxchar, maxchar2;
10684 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010685
10686 if (p_left == NULL) {
10687 if (!PyErr_Occurred())
10688 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010689 return;
10690 }
Victor Stinner23e56682011-10-03 03:54:37 +020010691 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010692 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010693 if (!PyErr_Occurred())
10694 PyErr_BadInternalCall();
10695 goto error;
10696 }
10697
Benjamin Petersonbac79492012-01-14 13:34:47 -050010698 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010699 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010700 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010701 goto error;
10702
Victor Stinner488fa492011-12-12 00:01:39 +010010703 /* Shortcuts */
10704 if (left == unicode_empty) {
10705 Py_DECREF(left);
10706 Py_INCREF(right);
10707 *p_left = right;
10708 return;
10709 }
10710 if (right == unicode_empty)
10711 return;
10712
10713 left_len = PyUnicode_GET_LENGTH(left);
10714 right_len = PyUnicode_GET_LENGTH(right);
10715 if (left_len > PY_SSIZE_T_MAX - right_len) {
10716 PyErr_SetString(PyExc_OverflowError,
10717 "strings are too large to concat");
10718 goto error;
10719 }
10720 new_len = left_len + right_len;
10721
10722 if (unicode_modifiable(left)
10723 && PyUnicode_CheckExact(right)
10724 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010725 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10726 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010727 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010728 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010729 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10730 {
10731 /* append inplace */
10732 if (unicode_resize(p_left, new_len) != 0) {
10733 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10734 * deallocated so it cannot be put back into
10735 * 'variable'. The MemoryError is raised when there
10736 * is no value in 'variable', which might (very
10737 * remotely) be a cause of incompatibilities.
10738 */
10739 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010740 }
Victor Stinner488fa492011-12-12 00:01:39 +010010741 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010742 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010743 }
Victor Stinner488fa492011-12-12 00:01:39 +010010744 else {
10745 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10746 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010747 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010748
Victor Stinner488fa492011-12-12 00:01:39 +010010749 /* Concat the two Unicode strings */
10750 res = PyUnicode_New(new_len, maxchar);
10751 if (res == NULL)
10752 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010753 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10754 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010755 Py_DECREF(left);
10756 *p_left = res;
10757 }
10758 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010759 return;
10760
10761error:
Victor Stinner488fa492011-12-12 00:01:39 +010010762 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010763}
10764
10765void
10766PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10767{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010768 PyUnicode_Append(pleft, right);
10769 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010770}
10771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010772PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010773 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010775Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010776string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010777interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778
10779static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010780unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010782 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010783 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010784 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 int kind1, kind2, kind;
10787 void *buf1, *buf2;
10788 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789
Jesus Ceaac451502011-04-20 17:09:23 +020010790 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10791 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010792 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 kind1 = PyUnicode_KIND(self);
10795 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010796 if (kind2 > kind1)
10797 return PyLong_FromLong(0);
10798 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 buf1 = PyUnicode_DATA(self);
10800 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010802 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010803 if (!buf2) {
10804 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010805 return NULL;
10806 }
10807 len1 = PyUnicode_GET_LENGTH(self);
10808 len2 = PyUnicode_GET_LENGTH(substring);
10809
10810 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010811 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 case PyUnicode_1BYTE_KIND:
10813 iresult = ucs1lib_count(
10814 ((Py_UCS1*)buf1) + start, end - start,
10815 buf2, len2, PY_SSIZE_T_MAX
10816 );
10817 break;
10818 case PyUnicode_2BYTE_KIND:
10819 iresult = ucs2lib_count(
10820 ((Py_UCS2*)buf1) + start, end - start,
10821 buf2, len2, PY_SSIZE_T_MAX
10822 );
10823 break;
10824 case PyUnicode_4BYTE_KIND:
10825 iresult = ucs4lib_count(
10826 ((Py_UCS4*)buf1) + start, end - start,
10827 buf2, len2, PY_SSIZE_T_MAX
10828 );
10829 break;
10830 default:
10831 assert(0); iresult = 0;
10832 }
10833
10834 result = PyLong_FromSsize_t(iresult);
10835
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 if (kind2 != kind)
10837 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838
10839 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010840
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841 return result;
10842}
10843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010844PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010845 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010847Encode S using the codec registered for encoding. Default encoding\n\
10848is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010849handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010850a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10851'xmlcharrefreplace' as well as any other name registered with\n\
10852codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853
10854static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010855unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010857 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858 char *encoding = NULL;
10859 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010860
Benjamin Peterson308d6372009-09-18 21:42:35 +000010861 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10862 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010864 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010865}
10866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010867PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010868 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869\n\
10870Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010871If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872
10873static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010874unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010876 Py_ssize_t i, j, line_pos, src_len, incr;
10877 Py_UCS4 ch;
10878 PyObject *u;
10879 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010881 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010882 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010883
10884 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886
Antoine Pitrou22425222011-10-04 19:10:51 +020010887 if (PyUnicode_READY(self) == -1)
10888 return NULL;
10889
Thomas Wouters7e474022000-07-16 12:04:32 +000010890 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010891 src_len = PyUnicode_GET_LENGTH(self);
10892 i = j = line_pos = 0;
10893 kind = PyUnicode_KIND(self);
10894 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010895 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 for (; i < src_len; i++) {
10897 ch = PyUnicode_READ(kind, src_data, i);
10898 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010899 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010900 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010901 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010903 goto overflow;
10904 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010905 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010906 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010907 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010909 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010910 goto overflow;
10911 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010913 if (ch == '\n' || ch == '\r')
10914 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010917 if (!found)
10918 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010919
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922 if (!u)
10923 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010924 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925
Antoine Pitroue71d5742011-10-04 15:55:09 +020010926 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927
Antoine Pitroue71d5742011-10-04 15:55:09 +020010928 for (; i < src_len; i++) {
10929 ch = PyUnicode_READ(kind, src_data, i);
10930 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010931 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010932 incr = tabsize - (line_pos % tabsize);
10933 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010934 FILL(kind, dest_data, ' ', j, incr);
10935 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010936 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010937 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010938 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010939 line_pos++;
10940 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010941 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010942 if (ch == '\n' || ch == '\r')
10943 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 }
10946 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010947 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010948
Antoine Pitroue71d5742011-10-04 15:55:09 +020010949 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010950 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10951 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952}
10953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010954PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956\n\
10957Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010958such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959arguments start and end are interpreted as in slice notation.\n\
10960\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010961Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962
10963static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010966 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010967 Py_ssize_t start;
10968 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010969 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
Jesus Ceaac451502011-04-20 17:09:23 +020010971 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10972 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 if (PyUnicode_READY(self) == -1)
10976 return NULL;
10977 if (PyUnicode_READY(substring) == -1)
10978 return NULL;
10979
Victor Stinner7931d9a2011-11-04 00:22:48 +010010980 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981
10982 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 if (result == -2)
10985 return NULL;
10986
Christian Heimes217cfd12007-12-02 14:31:20 +000010987 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988}
10989
10990static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010991unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010993 void *data;
10994 enum PyUnicode_Kind kind;
10995 Py_UCS4 ch;
10996 PyObject *res;
10997
10998 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10999 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011001 }
11002 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11003 PyErr_SetString(PyExc_IndexError, "string index out of range");
11004 return NULL;
11005 }
11006 kind = PyUnicode_KIND(self);
11007 data = PyUnicode_DATA(self);
11008 ch = PyUnicode_READ(kind, data, index);
11009 if (ch < 256)
11010 return get_latin1_char(ch);
11011
11012 res = PyUnicode_New(1, ch);
11013 if (res == NULL)
11014 return NULL;
11015 kind = PyUnicode_KIND(res);
11016 data = PyUnicode_DATA(res);
11017 PyUnicode_WRITE(kind, data, 0, ch);
11018 assert(_PyUnicode_CheckConsistency(res, 1));
11019 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020}
11021
Guido van Rossumc2504932007-09-18 19:42:40 +000011022/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011023 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011024static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011025unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026{
Guido van Rossumc2504932007-09-18 19:42:40 +000011027 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011028 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011029
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011030#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011031 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011032#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033 if (_PyUnicode_HASH(self) != -1)
11034 return _PyUnicode_HASH(self);
11035 if (PyUnicode_READY(self) == -1)
11036 return -1;
11037 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011038 /*
11039 We make the hash of the empty string be 0, rather than using
11040 (prefix ^ suffix), since this slightly obfuscates the hash secret
11041 */
11042 if (len == 0) {
11043 _PyUnicode_HASH(self) = 0;
11044 return 0;
11045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046
11047 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011048#define HASH(P) \
11049 x ^= (Py_uhash_t) *P << 7; \
11050 while (--len >= 0) \
11051 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011052
Georg Brandl2fb477c2012-02-21 00:33:36 +010011053 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 switch (PyUnicode_KIND(self)) {
11055 case PyUnicode_1BYTE_KIND: {
11056 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11057 HASH(c);
11058 break;
11059 }
11060 case PyUnicode_2BYTE_KIND: {
11061 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11062 HASH(s);
11063 break;
11064 }
11065 default: {
11066 Py_UCS4 *l;
11067 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11068 "Impossible switch case in unicode_hash");
11069 l = PyUnicode_4BYTE_DATA(self);
11070 HASH(l);
11071 break;
11072 }
11073 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011074 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11075 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011076
Guido van Rossumc2504932007-09-18 19:42:40 +000011077 if (x == -1)
11078 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011080 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011084PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011087Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
11089static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011092 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011093 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011094 Py_ssize_t start;
11095 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
Jesus Ceaac451502011-04-20 17:09:23 +020011097 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11098 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011101 if (PyUnicode_READY(self) == -1)
11102 return NULL;
11103 if (PyUnicode_READY(substring) == -1)
11104 return NULL;
11105
Victor Stinner7931d9a2011-11-04 00:22:48 +010011106 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107
11108 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 if (result == -2)
11111 return NULL;
11112
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113 if (result < 0) {
11114 PyErr_SetString(PyExc_ValueError, "substring not found");
11115 return NULL;
11116 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011117
Christian Heimes217cfd12007-12-02 14:31:20 +000011118 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011119}
11120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011121PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011122 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011124Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011126
11127static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011128unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011130 Py_ssize_t i, length;
11131 int kind;
11132 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133 int cased;
11134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 if (PyUnicode_READY(self) == -1)
11136 return NULL;
11137 length = PyUnicode_GET_LENGTH(self);
11138 kind = PyUnicode_KIND(self);
11139 data = PyUnicode_DATA(self);
11140
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 if (length == 1)
11143 return PyBool_FromLong(
11144 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011146 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011148 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011149
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 for (i = 0; i < length; i++) {
11152 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011153
Benjamin Peterson29060642009-01-31 22:14:21 +000011154 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11155 return PyBool_FromLong(0);
11156 else if (!cased && Py_UNICODE_ISLOWER(ch))
11157 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011159 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160}
11161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011162PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011163 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011165Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011166at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167
11168static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011169unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 Py_ssize_t i, length;
11172 int kind;
11173 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174 int cased;
11175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 if (PyUnicode_READY(self) == -1)
11177 return NULL;
11178 length = PyUnicode_GET_LENGTH(self);
11179 kind = PyUnicode_KIND(self);
11180 data = PyUnicode_DATA(self);
11181
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (length == 1)
11184 return PyBool_FromLong(
11185 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011187 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011189 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011190
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 for (i = 0; i < length; i++) {
11193 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011194
Benjamin Peterson29060642009-01-31 22:14:21 +000011195 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11196 return PyBool_FromLong(0);
11197 else if (!cased && Py_UNICODE_ISUPPER(ch))
11198 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011200 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201}
11202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011203PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011206Return True if S is a titlecased string and there is at least one\n\
11207character in S, i.e. upper- and titlecase characters may only\n\
11208follow uncased characters and lowercase characters only cased ones.\n\
11209Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
11211static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011212unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 Py_ssize_t i, length;
11215 int kind;
11216 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 int cased, previous_is_cased;
11218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011219 if (PyUnicode_READY(self) == -1)
11220 return NULL;
11221 length = PyUnicode_GET_LENGTH(self);
11222 kind = PyUnicode_KIND(self);
11223 data = PyUnicode_DATA(self);
11224
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 if (length == 1) {
11227 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11228 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11229 (Py_UNICODE_ISUPPER(ch) != 0));
11230 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011232 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011233 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011234 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011235
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 cased = 0;
11237 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011238 for (i = 0; i < length; i++) {
11239 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011240
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11242 if (previous_is_cased)
11243 return PyBool_FromLong(0);
11244 previous_is_cased = 1;
11245 cased = 1;
11246 }
11247 else if (Py_UNICODE_ISLOWER(ch)) {
11248 if (!previous_is_cased)
11249 return PyBool_FromLong(0);
11250 previous_is_cased = 1;
11251 cased = 1;
11252 }
11253 else
11254 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011256 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257}
11258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011259PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011262Return True if all characters in S are whitespace\n\
11263and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
11265static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011266unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 Py_ssize_t i, length;
11269 int kind;
11270 void *data;
11271
11272 if (PyUnicode_READY(self) == -1)
11273 return NULL;
11274 length = PyUnicode_GET_LENGTH(self);
11275 kind = PyUnicode_KIND(self);
11276 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 if (length == 1)
11280 return PyBool_FromLong(
11281 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011283 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 for (i = 0; i < length; i++) {
11288 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011289 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011292 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293}
11294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011295PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011296 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011297\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011298Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011299and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011300
11301static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011302unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011303{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 Py_ssize_t i, length;
11305 int kind;
11306 void *data;
11307
11308 if (PyUnicode_READY(self) == -1)
11309 return NULL;
11310 length = PyUnicode_GET_LENGTH(self);
11311 kind = PyUnicode_KIND(self);
11312 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011314 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 if (length == 1)
11316 return PyBool_FromLong(
11317 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318
11319 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 for (i = 0; i < length; i++) {
11324 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011325 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011326 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011327 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328}
11329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011330PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011331 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011332\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011333Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011334and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335
11336static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011337unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011338{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 int kind;
11340 void *data;
11341 Py_ssize_t len, i;
11342
11343 if (PyUnicode_READY(self) == -1)
11344 return NULL;
11345
11346 kind = PyUnicode_KIND(self);
11347 data = PyUnicode_DATA(self);
11348 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011349
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011350 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 if (len == 1) {
11352 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11353 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11354 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011355
11356 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 for (i = 0; i < len; i++) {
11361 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011362 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011365 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366}
11367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011368PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011369 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011371Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011372False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373
11374static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011375unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 Py_ssize_t i, length;
11378 int kind;
11379 void *data;
11380
11381 if (PyUnicode_READY(self) == -1)
11382 return NULL;
11383 length = PyUnicode_GET_LENGTH(self);
11384 kind = PyUnicode_KIND(self);
11385 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388 if (length == 1)
11389 return PyBool_FromLong(
11390 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011392 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 for (i = 0; i < length; i++) {
11397 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011400 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401}
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011406Return True if all characters in S are digits\n\
11407and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
11409static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011410unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 Py_ssize_t i, length;
11413 int kind;
11414 void *data;
11415
11416 if (PyUnicode_READY(self) == -1)
11417 return NULL;
11418 length = PyUnicode_GET_LENGTH(self);
11419 kind = PyUnicode_KIND(self);
11420 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 if (length == 1) {
11424 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11425 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11426 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011428 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011430 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 for (i = 0; i < length; i++) {
11433 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011436 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437}
11438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011439PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011440 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011442Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011443False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
11445static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011446unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 Py_ssize_t i, length;
11449 int kind;
11450 void *data;
11451
11452 if (PyUnicode_READY(self) == -1)
11453 return NULL;
11454 length = PyUnicode_GET_LENGTH(self);
11455 kind = PyUnicode_KIND(self);
11456 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (length == 1)
11460 return PyBool_FromLong(
11461 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011463 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011465 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 for (i = 0; i < length; i++) {
11468 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011471 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472}
11473
Martin v. Löwis47383402007-08-15 07:32:56 +000011474int
11475PyUnicode_IsIdentifier(PyObject *self)
11476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 int kind;
11478 void *data;
11479 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011480 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 if (PyUnicode_READY(self) == -1) {
11483 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 }
11486
11487 /* Special case for empty strings */
11488 if (PyUnicode_GET_LENGTH(self) == 0)
11489 return 0;
11490 kind = PyUnicode_KIND(self);
11491 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011492
11493 /* PEP 3131 says that the first character must be in
11494 XID_Start and subsequent characters in XID_Continue,
11495 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011496 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011497 letters, digits, underscore). However, given the current
11498 definition of XID_Start and XID_Continue, it is sufficient
11499 to check just for these, except that _ must be allowed
11500 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011502 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011503 return 0;
11504
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011505 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011508 return 1;
11509}
11510
11511PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011513\n\
11514Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011515to the language definition.\n\
11516\n\
11517Use keyword.iskeyword() to test for reserved identifiers\n\
11518such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011519
11520static PyObject*
11521unicode_isidentifier(PyObject *self)
11522{
11523 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11524}
11525
Georg Brandl559e5d72008-06-11 18:37:52 +000011526PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011528\n\
11529Return True if all characters in S are considered\n\
11530printable in repr() or S is empty, False otherwise.");
11531
11532static PyObject*
11533unicode_isprintable(PyObject *self)
11534{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 Py_ssize_t i, length;
11536 int kind;
11537 void *data;
11538
11539 if (PyUnicode_READY(self) == -1)
11540 return NULL;
11541 length = PyUnicode_GET_LENGTH(self);
11542 kind = PyUnicode_KIND(self);
11543 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011544
11545 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011546 if (length == 1)
11547 return PyBool_FromLong(
11548 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 for (i = 0; i < length; i++) {
11551 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011552 Py_RETURN_FALSE;
11553 }
11554 }
11555 Py_RETURN_TRUE;
11556}
11557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011558PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011559 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560\n\
11561Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011562iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563
11564static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011565unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011567 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568}
11569
Martin v. Löwis18e16552006-02-15 17:27:45 +000011570static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011571unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 if (PyUnicode_READY(self) == -1)
11574 return -1;
11575 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576}
11577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011578PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011581Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011582done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583
11584static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011585unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011587 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 Py_UCS4 fillchar = ' ';
11589
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011590 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591 return NULL;
11592
Benjamin Petersonbac79492012-01-14 13:34:47 -050011593 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011594 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
Victor Stinnerc4b49542011-12-11 22:44:26 +010011596 if (PyUnicode_GET_LENGTH(self) >= width)
11597 return unicode_result_unchanged(self);
11598
11599 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600}
11601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011602PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011603 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011605Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
11607static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011608unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011610 if (PyUnicode_READY(self) == -1)
11611 return NULL;
11612 if (PyUnicode_IS_ASCII(self))
11613 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011614 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615}
11616
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011617#define LEFTSTRIP 0
11618#define RIGHTSTRIP 1
11619#define BOTHSTRIP 2
11620
11621/* Arrays indexed by above */
11622static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11623
11624#define STRIPNAME(i) (stripformat[i]+3)
11625
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011626/* externally visible for str.strip(unicode) */
11627PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011628_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 void *data;
11631 int kind;
11632 Py_ssize_t i, j, len;
11633 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011635 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11636 return NULL;
11637
11638 kind = PyUnicode_KIND(self);
11639 data = PyUnicode_DATA(self);
11640 len = PyUnicode_GET_LENGTH(self);
11641 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11642 PyUnicode_DATA(sepobj),
11643 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011644
Benjamin Peterson14339b62009-01-31 16:36:08 +000011645 i = 0;
11646 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 while (i < len &&
11648 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 i++;
11650 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011651 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011652
Benjamin Peterson14339b62009-01-31 16:36:08 +000011653 j = len;
11654 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 do {
11656 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 } while (j >= i &&
11658 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011660 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011661
Victor Stinner7931d9a2011-11-04 00:22:48 +010011662 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663}
11664
11665PyObject*
11666PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11667{
11668 unsigned char *data;
11669 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011670 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671
Victor Stinnerde636f32011-10-01 03:55:54 +020011672 if (PyUnicode_READY(self) == -1)
11673 return NULL;
11674
Victor Stinner684d5fd2012-05-03 02:32:34 +020011675 length = PyUnicode_GET_LENGTH(self);
11676 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011677
Victor Stinner684d5fd2012-05-03 02:32:34 +020011678 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011679 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680
Victor Stinnerde636f32011-10-01 03:55:54 +020011681 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011682 PyErr_SetString(PyExc_IndexError, "string index out of range");
11683 return NULL;
11684 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011685 if (start >= length || end < start)
11686 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011687
Victor Stinner684d5fd2012-05-03 02:32:34 +020011688 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011689 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011690 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011691 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011692 }
11693 else {
11694 kind = PyUnicode_KIND(self);
11695 data = PyUnicode_1BYTE_DATA(self);
11696 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011697 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011698 length);
11699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
11702static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011703do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 int kind;
11706 void *data;
11707 Py_ssize_t len, i, j;
11708
11709 if (PyUnicode_READY(self) == -1)
11710 return NULL;
11711
11712 kind = PyUnicode_KIND(self);
11713 data = PyUnicode_DATA(self);
11714 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011715
Benjamin Peterson14339b62009-01-31 16:36:08 +000011716 i = 0;
11717 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011719 i++;
11720 }
11721 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722
Benjamin Peterson14339b62009-01-31 16:36:08 +000011723 j = len;
11724 if (striptype != LEFTSTRIP) {
11725 do {
11726 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011727 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011728 j++;
11729 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
Victor Stinner7931d9a2011-11-04 00:22:48 +010011731 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732}
11733
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011734
11735static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011736do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011737{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011738 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739
Benjamin Peterson14339b62009-01-31 16:36:08 +000011740 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11741 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011742
Benjamin Peterson14339b62009-01-31 16:36:08 +000011743 if (sep != NULL && sep != Py_None) {
11744 if (PyUnicode_Check(sep))
11745 return _PyUnicode_XStrip(self, striptype, sep);
11746 else {
11747 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011748 "%s arg must be None or str",
11749 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 return NULL;
11751 }
11752 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011753
Benjamin Peterson14339b62009-01-31 16:36:08 +000011754 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755}
11756
11757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011758PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011759 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760\n\
11761Return a copy of the string S with leading and trailing\n\
11762whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011763If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011764
11765static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011766unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011768 if (PyTuple_GET_SIZE(args) == 0)
11769 return do_strip(self, BOTHSTRIP); /* Common case */
11770 else
11771 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011772}
11773
11774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011775PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011776 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011777\n\
11778Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011779If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011780
11781static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011782unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011784 if (PyTuple_GET_SIZE(args) == 0)
11785 return do_strip(self, LEFTSTRIP); /* Common case */
11786 else
11787 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788}
11789
11790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011791PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011793\n\
11794Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011795If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796
11797static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011798unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011799{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011800 if (PyTuple_GET_SIZE(args) == 0)
11801 return do_strip(self, RIGHTSTRIP); /* Common case */
11802 else
11803 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011804}
11805
11806
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011808unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011810 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812
Serhiy Storchaka05997252013-01-26 12:14:02 +020011813 if (len < 1)
11814 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815
Victor Stinnerc4b49542011-12-11 22:44:26 +010011816 /* no repeat, return original string */
11817 if (len == 1)
11818 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011819
Benjamin Petersonbac79492012-01-14 13:34:47 -050011820 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 return NULL;
11822
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011823 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011824 PyErr_SetString(PyExc_OverflowError,
11825 "repeated string is too long");
11826 return NULL;
11827 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011828 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011829
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011830 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831 if (!u)
11832 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011833 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 if (PyUnicode_GET_LENGTH(str) == 1) {
11836 const int kind = PyUnicode_KIND(str);
11837 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011838 if (kind == PyUnicode_1BYTE_KIND) {
11839 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011840 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011841 }
11842 else if (kind == PyUnicode_2BYTE_KIND) {
11843 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011844 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011845 ucs2[n] = fill_char;
11846 } else {
11847 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11848 assert(kind == PyUnicode_4BYTE_KIND);
11849 for (n = 0; n < len; ++n)
11850 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011851 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 }
11853 else {
11854 /* number of characters copied this far */
11855 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011856 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 char *to = (char *) PyUnicode_DATA(u);
11858 Py_MEMCPY(to, PyUnicode_DATA(str),
11859 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 n = (done <= nchars-done) ? done : nchars-done;
11862 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011863 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865 }
11866
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011867 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011868 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869}
11870
Alexander Belopolsky40018472011-02-26 01:02:56 +000011871PyObject *
11872PyUnicode_Replace(PyObject *obj,
11873 PyObject *subobj,
11874 PyObject *replobj,
11875 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876{
11877 PyObject *self;
11878 PyObject *str1;
11879 PyObject *str2;
11880 PyObject *result;
11881
11882 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011883 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011886 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011887 Py_DECREF(self);
11888 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889 }
11890 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011891 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011892 Py_DECREF(self);
11893 Py_DECREF(str1);
11894 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011896 if (PyUnicode_READY(self) == -1 ||
11897 PyUnicode_READY(str1) == -1 ||
11898 PyUnicode_READY(str2) == -1)
11899 result = NULL;
11900 else
11901 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902 Py_DECREF(self);
11903 Py_DECREF(str1);
11904 Py_DECREF(str2);
11905 return result;
11906}
11907
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011908PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011909 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910\n\
11911Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011912old replaced by new. If the optional argument count is\n\
11913given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914
11915static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 PyObject *str1;
11919 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011920 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921 PyObject *result;
11922
Martin v. Löwis18e16552006-02-15 17:27:45 +000011923 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011925 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011928 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 return NULL;
11930 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011931 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 Py_DECREF(str1);
11933 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011934 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011935 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11936 result = NULL;
11937 else
11938 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
11940 Py_DECREF(str1);
11941 Py_DECREF(str2);
11942 return result;
11943}
11944
Alexander Belopolsky40018472011-02-26 01:02:56 +000011945static PyObject *
11946unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011948 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 Py_ssize_t isize;
11950 Py_ssize_t osize, squote, dquote, i, o;
11951 Py_UCS4 max, quote;
11952 int ikind, okind;
11953 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011956 return NULL;
11957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011958 isize = PyUnicode_GET_LENGTH(unicode);
11959 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 /* Compute length of output, quote characters, and
11962 maximum character */
11963 osize = 2; /* quotes */
11964 max = 127;
11965 squote = dquote = 0;
11966 ikind = PyUnicode_KIND(unicode);
11967 for (i = 0; i < isize; i++) {
11968 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11969 switch (ch) {
11970 case '\'': squote++; osize++; break;
11971 case '"': dquote++; osize++; break;
11972 case '\\': case '\t': case '\r': case '\n':
11973 osize += 2; break;
11974 default:
11975 /* Fast-path ASCII */
11976 if (ch < ' ' || ch == 0x7f)
11977 osize += 4; /* \xHH */
11978 else if (ch < 0x7f)
11979 osize++;
11980 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11981 osize++;
11982 max = ch > max ? ch : max;
11983 }
11984 else if (ch < 0x100)
11985 osize += 4; /* \xHH */
11986 else if (ch < 0x10000)
11987 osize += 6; /* \uHHHH */
11988 else
11989 osize += 10; /* \uHHHHHHHH */
11990 }
11991 }
11992
11993 quote = '\'';
11994 if (squote) {
11995 if (dquote)
11996 /* Both squote and dquote present. Use squote,
11997 and escape them */
11998 osize += squote;
11999 else
12000 quote = '"';
12001 }
12002
12003 repr = PyUnicode_New(osize, max);
12004 if (repr == NULL)
12005 return NULL;
12006 okind = PyUnicode_KIND(repr);
12007 odata = PyUnicode_DATA(repr);
12008
12009 PyUnicode_WRITE(okind, odata, 0, quote);
12010 PyUnicode_WRITE(okind, odata, osize-1, quote);
12011
12012 for (i = 0, o = 1; i < isize; i++) {
12013 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012014
12015 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 if ((ch == quote) || (ch == '\\')) {
12017 PyUnicode_WRITE(okind, odata, o++, '\\');
12018 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012019 continue;
12020 }
12021
Benjamin Peterson29060642009-01-31 22:14:21 +000012022 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012023 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 PyUnicode_WRITE(okind, odata, o++, '\\');
12025 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012026 }
12027 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 PyUnicode_WRITE(okind, odata, o++, '\\');
12029 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012030 }
12031 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 PyUnicode_WRITE(okind, odata, o++, '\\');
12033 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012034 }
12035
12036 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012037 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 PyUnicode_WRITE(okind, odata, o++, '\\');
12039 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012040 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12041 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012042 }
12043
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 /* Copy ASCII characters as-is */
12045 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012047 }
12048
Benjamin Peterson29060642009-01-31 22:14:21 +000012049 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012050 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012051 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012052 (categories Z* and C* except ASCII space)
12053 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012055 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012056 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012059 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12060 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012061 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012062 /* Map 16-bit characters to '\uxxxx' */
12063 else if (ch <= 0xffff) {
12064 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012069 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012070 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012071 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012072 PyUnicode_WRITE(okind, odata, o++, 'U');
12073 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12074 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12075 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12076 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012077 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12078 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12079 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12080 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012081 }
12082 }
12083 /* Copy characters as-is */
12084 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012086 }
12087 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012090 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012091 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092}
12093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012094PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012095 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096\n\
12097Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012098such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099arguments start and end are interpreted as in slice notation.\n\
12100\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012101Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
12103static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012106 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012107 Py_ssize_t start;
12108 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012109 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110
Jesus Ceaac451502011-04-20 17:09:23 +020012111 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12112 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 if (PyUnicode_READY(self) == -1)
12116 return NULL;
12117 if (PyUnicode_READY(substring) == -1)
12118 return NULL;
12119
Victor Stinner7931d9a2011-11-04 00:22:48 +010012120 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121
12122 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012124 if (result == -2)
12125 return NULL;
12126
Christian Heimes217cfd12007-12-02 14:31:20 +000012127 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128}
12129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012130PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012131 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012133Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134
12135static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012138 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012139 Py_ssize_t start;
12140 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012141 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142
Jesus Ceaac451502011-04-20 17:09:23 +020012143 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12144 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012145 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 if (PyUnicode_READY(self) == -1)
12148 return NULL;
12149 if (PyUnicode_READY(substring) == -1)
12150 return NULL;
12151
Victor Stinner7931d9a2011-11-04 00:22:48 +010012152 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153
12154 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 if (result == -2)
12157 return NULL;
12158
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159 if (result < 0) {
12160 PyErr_SetString(PyExc_ValueError, "substring not found");
12161 return NULL;
12162 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163
Christian Heimes217cfd12007-12-02 14:31:20 +000012164 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165}
12166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012167PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012168 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012170Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012171done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
12173static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012174unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012176 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012177 Py_UCS4 fillchar = ' ';
12178
Victor Stinnere9a29352011-10-01 02:14:59 +020012179 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012181
Benjamin Petersonbac79492012-01-14 13:34:47 -050012182 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183 return NULL;
12184
Victor Stinnerc4b49542011-12-11 22:44:26 +010012185 if (PyUnicode_GET_LENGTH(self) >= width)
12186 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
Victor Stinnerc4b49542011-12-11 22:44:26 +010012188 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189}
12190
Alexander Belopolsky40018472011-02-26 01:02:56 +000012191PyObject *
12192PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193{
12194 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012195
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 s = PyUnicode_FromObject(s);
12197 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012198 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012199 if (sep != NULL) {
12200 sep = PyUnicode_FromObject(sep);
12201 if (sep == NULL) {
12202 Py_DECREF(s);
12203 return NULL;
12204 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205 }
12206
Victor Stinner9310abb2011-10-05 00:59:23 +020012207 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208
12209 Py_DECREF(s);
12210 Py_XDECREF(sep);
12211 return result;
12212}
12213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012214PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012215 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216\n\
12217Return a list of the words in S, using sep as the\n\
12218delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012219splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012220whitespace string is a separator and empty strings are\n\
12221removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222
12223static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012224unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012226 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012228 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012230 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12231 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 return NULL;
12233
12234 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012237 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012239 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240}
12241
Thomas Wouters477c8d52006-05-27 19:21:47 +000012242PyObject *
12243PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12244{
12245 PyObject* str_obj;
12246 PyObject* sep_obj;
12247 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 int kind1, kind2, kind;
12249 void *buf1 = NULL, *buf2 = NULL;
12250 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012251
12252 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012253 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012255 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012256 if (!sep_obj) {
12257 Py_DECREF(str_obj);
12258 return NULL;
12259 }
12260 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12261 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012262 Py_DECREF(str_obj);
12263 return NULL;
12264 }
12265
Victor Stinner14f8f022011-10-05 20:58:25 +020012266 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012268 kind = Py_MAX(kind1, kind2);
12269 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012271 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 if (!buf1)
12273 goto onError;
12274 buf2 = PyUnicode_DATA(sep_obj);
12275 if (kind2 != kind)
12276 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12277 if (!buf2)
12278 goto onError;
12279 len1 = PyUnicode_GET_LENGTH(str_obj);
12280 len2 = PyUnicode_GET_LENGTH(sep_obj);
12281
Benjamin Petersonead6b532011-12-20 17:23:42 -060012282 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012284 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12285 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12286 else
12287 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 break;
12289 case PyUnicode_2BYTE_KIND:
12290 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12291 break;
12292 case PyUnicode_4BYTE_KIND:
12293 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12294 break;
12295 default:
12296 assert(0);
12297 out = 0;
12298 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012299
12300 Py_DECREF(sep_obj);
12301 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 if (kind1 != kind)
12303 PyMem_Free(buf1);
12304 if (kind2 != kind)
12305 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012306
12307 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 onError:
12309 Py_DECREF(sep_obj);
12310 Py_DECREF(str_obj);
12311 if (kind1 != kind && buf1)
12312 PyMem_Free(buf1);
12313 if (kind2 != kind && buf2)
12314 PyMem_Free(buf2);
12315 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012316}
12317
12318
12319PyObject *
12320PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12321{
12322 PyObject* str_obj;
12323 PyObject* sep_obj;
12324 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 int kind1, kind2, kind;
12326 void *buf1 = NULL, *buf2 = NULL;
12327 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012328
12329 str_obj = PyUnicode_FromObject(str_in);
12330 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012331 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012332 sep_obj = PyUnicode_FromObject(sep_in);
12333 if (!sep_obj) {
12334 Py_DECREF(str_obj);
12335 return NULL;
12336 }
12337
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 kind1 = PyUnicode_KIND(str_in);
12339 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012340 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 buf1 = PyUnicode_DATA(str_in);
12342 if (kind1 != kind)
12343 buf1 = _PyUnicode_AsKind(str_in, kind);
12344 if (!buf1)
12345 goto onError;
12346 buf2 = PyUnicode_DATA(sep_obj);
12347 if (kind2 != kind)
12348 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12349 if (!buf2)
12350 goto onError;
12351 len1 = PyUnicode_GET_LENGTH(str_obj);
12352 len2 = PyUnicode_GET_LENGTH(sep_obj);
12353
Benjamin Petersonead6b532011-12-20 17:23:42 -060012354 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012356 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12357 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12358 else
12359 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012360 break;
12361 case PyUnicode_2BYTE_KIND:
12362 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12363 break;
12364 case PyUnicode_4BYTE_KIND:
12365 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12366 break;
12367 default:
12368 assert(0);
12369 out = 0;
12370 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012371
12372 Py_DECREF(sep_obj);
12373 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 if (kind1 != kind)
12375 PyMem_Free(buf1);
12376 if (kind2 != kind)
12377 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012378
12379 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 onError:
12381 Py_DECREF(sep_obj);
12382 Py_DECREF(str_obj);
12383 if (kind1 != kind && buf1)
12384 PyMem_Free(buf1);
12385 if (kind2 != kind && buf2)
12386 PyMem_Free(buf2);
12387 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012388}
12389
12390PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012391 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012392\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012393Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012394the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012395found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012396
12397static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012398unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399{
Victor Stinner9310abb2011-10-05 00:59:23 +020012400 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012401}
12402
12403PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012404 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012405\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012406Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012407the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012408separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012409
12410static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012411unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012412{
Victor Stinner9310abb2011-10-05 00:59:23 +020012413 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012414}
12415
Alexander Belopolsky40018472011-02-26 01:02:56 +000012416PyObject *
12417PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012418{
12419 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012420
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012421 s = PyUnicode_FromObject(s);
12422 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012423 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012424 if (sep != NULL) {
12425 sep = PyUnicode_FromObject(sep);
12426 if (sep == NULL) {
12427 Py_DECREF(s);
12428 return NULL;
12429 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012430 }
12431
Victor Stinner9310abb2011-10-05 00:59:23 +020012432 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012433
12434 Py_DECREF(s);
12435 Py_XDECREF(sep);
12436 return result;
12437}
12438
12439PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012440 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012441\n\
12442Return a list of the words in S, using sep as the\n\
12443delimiter string, starting at the end of the string and\n\
12444working to the front. If maxsplit is given, at most maxsplit\n\
12445splits are done. If sep is not specified, any whitespace string\n\
12446is a separator.");
12447
12448static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012449unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012450{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012451 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012452 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012453 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012454
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012455 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12456 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012457 return NULL;
12458
12459 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012460 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012461 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012462 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012463 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012464 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012465}
12466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012467PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012468 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469\n\
12470Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012471Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012472is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473
12474static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012475unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012477 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012478 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012480 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12481 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482 return NULL;
12483
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012484 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485}
12486
12487static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012488PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012490 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491}
12492
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012493PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012494 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495\n\
12496Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012497and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498
12499static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012500unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012502 if (PyUnicode_READY(self) == -1)
12503 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012504 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505}
12506
Georg Brandlceee0772007-11-27 23:48:05 +000012507PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012508 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012509\n\
12510Return a translation table usable for str.translate().\n\
12511If there is only one argument, it must be a dictionary mapping Unicode\n\
12512ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012513Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012514If there are two arguments, they must be strings of equal length, and\n\
12515in the resulting dictionary, each character in x will be mapped to the\n\
12516character at the same position in y. If there is a third argument, it\n\
12517must be a string, whose characters will be mapped to None in the result.");
12518
12519static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012520unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012521{
12522 PyObject *x, *y = NULL, *z = NULL;
12523 PyObject *new = NULL, *key, *value;
12524 Py_ssize_t i = 0;
12525 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012526
Georg Brandlceee0772007-11-27 23:48:05 +000012527 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12528 return NULL;
12529 new = PyDict_New();
12530 if (!new)
12531 return NULL;
12532 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533 int x_kind, y_kind, z_kind;
12534 void *x_data, *y_data, *z_data;
12535
Georg Brandlceee0772007-11-27 23:48:05 +000012536 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012537 if (!PyUnicode_Check(x)) {
12538 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12539 "be a string if there is a second argument");
12540 goto err;
12541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012543 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12544 "arguments must have equal length");
12545 goto err;
12546 }
12547 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 x_kind = PyUnicode_KIND(x);
12549 y_kind = PyUnicode_KIND(y);
12550 x_data = PyUnicode_DATA(x);
12551 y_data = PyUnicode_DATA(y);
12552 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12553 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012554 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012555 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012556 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012557 if (!value) {
12558 Py_DECREF(key);
12559 goto err;
12560 }
Georg Brandlceee0772007-11-27 23:48:05 +000012561 res = PyDict_SetItem(new, key, value);
12562 Py_DECREF(key);
12563 Py_DECREF(value);
12564 if (res < 0)
12565 goto err;
12566 }
12567 /* create entries for deleting chars in z */
12568 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 z_kind = PyUnicode_KIND(z);
12570 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012571 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012573 if (!key)
12574 goto err;
12575 res = PyDict_SetItem(new, key, Py_None);
12576 Py_DECREF(key);
12577 if (res < 0)
12578 goto err;
12579 }
12580 }
12581 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 int kind;
12583 void *data;
12584
Georg Brandlceee0772007-11-27 23:48:05 +000012585 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012586 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012587 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12588 "to maketrans it must be a dict");
12589 goto err;
12590 }
12591 /* copy entries into the new dict, converting string keys to int keys */
12592 while (PyDict_Next(x, &i, &key, &value)) {
12593 if (PyUnicode_Check(key)) {
12594 /* convert string keys to integer keys */
12595 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012596 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012597 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12598 "table must be of length 1");
12599 goto err;
12600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 kind = PyUnicode_KIND(key);
12602 data = PyUnicode_DATA(key);
12603 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012604 if (!newkey)
12605 goto err;
12606 res = PyDict_SetItem(new, newkey, value);
12607 Py_DECREF(newkey);
12608 if (res < 0)
12609 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012610 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012611 /* just keep integer keys */
12612 if (PyDict_SetItem(new, key, value) < 0)
12613 goto err;
12614 } else {
12615 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12616 "be strings or integers");
12617 goto err;
12618 }
12619 }
12620 }
12621 return new;
12622 err:
12623 Py_DECREF(new);
12624 return NULL;
12625}
12626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012627PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012628 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629\n\
12630Return a copy of the string S, where all characters have been mapped\n\
12631through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012632Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012633Unmapped characters are left untouched. Characters mapped to None\n\
12634are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635
12636static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640}
12641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012642PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012643 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012645Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646
12647static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012648unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012650 if (PyUnicode_READY(self) == -1)
12651 return NULL;
12652 if (PyUnicode_IS_ASCII(self))
12653 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012654 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655}
12656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012657PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012658 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012660Pad a numeric string S with zeros on the left, to fill a field\n\
12661of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662
12663static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012664unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012666 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012667 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012668 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669 int kind;
12670 void *data;
12671 Py_UCS4 chr;
12672
Martin v. Löwis18e16552006-02-15 17:27:45 +000012673 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674 return NULL;
12675
Benjamin Petersonbac79492012-01-14 13:34:47 -050012676 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012677 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678
Victor Stinnerc4b49542011-12-11 22:44:26 +010012679 if (PyUnicode_GET_LENGTH(self) >= width)
12680 return unicode_result_unchanged(self);
12681
12682 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683
12684 u = pad(self, fill, 0, '0');
12685
Walter Dörwald068325e2002-04-15 13:36:47 +000012686 if (u == NULL)
12687 return NULL;
12688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 kind = PyUnicode_KIND(u);
12690 data = PyUnicode_DATA(u);
12691 chr = PyUnicode_READ(kind, data, fill);
12692
12693 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 PyUnicode_WRITE(kind, data, 0, chr);
12696 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697 }
12698
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012699 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012700 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702
12703#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012704static PyObject *
12705unicode__decimal2ascii(PyObject *self)
12706{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012708}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709#endif
12710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012711PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012712 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012714Return True if S starts with the specified prefix, False otherwise.\n\
12715With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012716With optional end, stop comparing S at that position.\n\
12717prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718
12719static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012720unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012721 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012723 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012724 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012725 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012726 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012727 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728
Jesus Ceaac451502011-04-20 17:09:23 +020012729 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012730 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012731 if (PyTuple_Check(subobj)) {
12732 Py_ssize_t i;
12733 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012734 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012735 if (substring == NULL)
12736 return NULL;
12737 result = tailmatch(self, substring, start, end, -1);
12738 Py_DECREF(substring);
12739 if (result) {
12740 Py_RETURN_TRUE;
12741 }
12742 }
12743 /* nothing matched */
12744 Py_RETURN_FALSE;
12745 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012746 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012747 if (substring == NULL) {
12748 if (PyErr_ExceptionMatches(PyExc_TypeError))
12749 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12750 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012752 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012753 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012755 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012756}
12757
12758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012759PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012760 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012762Return True if S ends with the specified suffix, False otherwise.\n\
12763With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012764With optional end, stop comparing S at that position.\n\
12765suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766
12767static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012768unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012769 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012771 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012772 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012773 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012774 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776
Jesus Ceaac451502011-04-20 17:09:23 +020012777 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012779 if (PyTuple_Check(subobj)) {
12780 Py_ssize_t i;
12781 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012782 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012783 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012784 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012785 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012786 result = tailmatch(self, substring, start, end, +1);
12787 Py_DECREF(substring);
12788 if (result) {
12789 Py_RETURN_TRUE;
12790 }
12791 }
12792 Py_RETURN_FALSE;
12793 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012794 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012795 if (substring == NULL) {
12796 if (PyErr_ExceptionMatches(PyExc_TypeError))
12797 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12798 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012799 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012800 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012801 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012803 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804}
12805
Victor Stinner202fdca2012-05-07 12:47:02 +020012806Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012807_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012808{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012809 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012810 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12811 writer->data = PyUnicode_DATA(writer->buffer);
12812 writer->kind = PyUnicode_KIND(writer->buffer);
12813}
12814
Victor Stinnerd3f08822012-05-29 12:57:52 +020012815void
12816_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012817{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012818 memset(writer, 0, sizeof(*writer));
12819#ifdef Py_DEBUG
12820 writer->kind = 5; /* invalid kind */
12821#endif
12822 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012823 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012824}
12825
Victor Stinnerd3f08822012-05-29 12:57:52 +020012826int
12827_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12828 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012829{
12830 Py_ssize_t newlen;
12831 PyObject *newbuffer;
12832
Victor Stinnerd3f08822012-05-29 12:57:52 +020012833 assert(length > 0);
12834
Victor Stinner202fdca2012-05-07 12:47:02 +020012835 if (length > PY_SSIZE_T_MAX - writer->pos) {
12836 PyErr_NoMemory();
12837 return -1;
12838 }
12839 newlen = writer->pos + length;
12840
Victor Stinnerd3f08822012-05-29 12:57:52 +020012841 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012842 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012843 /* overallocate 25% to limit the number of resize */
12844 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12845 newlen += newlen / 4;
12846 if (newlen < writer->min_length)
12847 newlen = writer->min_length;
12848 }
12849 writer->buffer = PyUnicode_New(newlen, maxchar);
12850 if (writer->buffer == NULL)
12851 return -1;
12852 _PyUnicodeWriter_Update(writer);
12853 return 0;
12854 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012855
Victor Stinnerd3f08822012-05-29 12:57:52 +020012856 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012857 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012858 /* overallocate 25% to limit the number of resize */
12859 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12860 newlen += newlen / 4;
12861 if (newlen < writer->min_length)
12862 newlen = writer->min_length;
12863 }
12864
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012865 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012866 /* resize + widen */
12867 newbuffer = PyUnicode_New(newlen, maxchar);
12868 if (newbuffer == NULL)
12869 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012870 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12871 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012872 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012873 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012874 }
12875 else {
12876 newbuffer = resize_compact(writer->buffer, newlen);
12877 if (newbuffer == NULL)
12878 return -1;
12879 }
12880 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012881 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012882 }
12883 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012884 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012885 newbuffer = PyUnicode_New(writer->size, maxchar);
12886 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012887 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012888 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12889 writer->buffer, 0, writer->pos);
12890 Py_DECREF(writer->buffer);
12891 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012892 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012893 }
12894 return 0;
12895}
12896
Victor Stinnerd3f08822012-05-29 12:57:52 +020012897int
12898_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12899{
12900 Py_UCS4 maxchar;
12901 Py_ssize_t len;
12902
12903 if (PyUnicode_READY(str) == -1)
12904 return -1;
12905 len = PyUnicode_GET_LENGTH(str);
12906 if (len == 0)
12907 return 0;
12908 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12909 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012910 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012911 Py_INCREF(str);
12912 writer->buffer = str;
12913 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012914 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012915 writer->size = 0;
12916 writer->pos += len;
12917 return 0;
12918 }
12919 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12920 return -1;
12921 }
12922 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12923 str, 0, len);
12924 writer->pos += len;
12925 return 0;
12926}
12927
12928PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012929_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012930{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012931 if (writer->pos == 0) {
12932 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020012933 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020012934 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012935 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012936 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12937 return writer->buffer;
12938 }
12939 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12940 PyObject *newbuffer;
12941 newbuffer = resize_compact(writer->buffer, writer->pos);
12942 if (newbuffer == NULL) {
12943 Py_DECREF(writer->buffer);
12944 return NULL;
12945 }
12946 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012947 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012948 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner2cb16aa2013-03-06 19:28:37 +010012949 return unicode_result_ready(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012950}
12951
Victor Stinnerd3f08822012-05-29 12:57:52 +020012952void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012953_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012954{
12955 Py_CLEAR(writer->buffer);
12956}
12957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012958#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012959
12960PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012961 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012962\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012963Return a formatted version of S, using substitutions from args and kwargs.\n\
12964The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012965
Eric Smith27bbca62010-11-04 17:06:58 +000012966PyDoc_STRVAR(format_map__doc__,
12967 "S.format_map(mapping) -> str\n\
12968\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012969Return a formatted version of S, using substitutions from mapping.\n\
12970The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012971
Eric Smith4a7d76d2008-05-30 18:10:19 +000012972static PyObject *
12973unicode__format__(PyObject* self, PyObject* args)
12974{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012975 PyObject *format_spec;
12976 _PyUnicodeWriter writer;
12977 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012978
12979 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12980 return NULL;
12981
Victor Stinnerd3f08822012-05-29 12:57:52 +020012982 if (PyUnicode_READY(self) == -1)
12983 return NULL;
12984 _PyUnicodeWriter_Init(&writer, 0);
12985 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12986 self, format_spec, 0,
12987 PyUnicode_GET_LENGTH(format_spec));
12988 if (ret == -1) {
12989 _PyUnicodeWriter_Dealloc(&writer);
12990 return NULL;
12991 }
12992 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012993}
12994
Eric Smith8c663262007-08-25 02:26:07 +000012995PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012996 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012997\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012998Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012999
13000static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013001unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013002{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 Py_ssize_t size;
13004
13005 /* If it's a compact object, account for base structure +
13006 character data. */
13007 if (PyUnicode_IS_COMPACT_ASCII(v))
13008 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13009 else if (PyUnicode_IS_COMPACT(v))
13010 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013011 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 else {
13013 /* If it is a two-block object, account for base object, and
13014 for character block if present. */
13015 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013016 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013018 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 }
13020 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013021 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013022 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013024 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013025 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026
13027 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013028}
13029
13030PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013031 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013032
13033static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013034unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013035{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013036 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037 if (!copy)
13038 return NULL;
13039 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013040}
13041
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013043 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013044 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013045 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13046 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013047 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13048 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013049 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013050 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13051 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13052 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13053 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13054 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013055 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013056 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13057 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13058 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013059 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013060 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13061 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13062 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013063 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013064 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013065 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013066 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013067 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13068 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13069 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13070 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13071 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13072 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13073 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13074 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13075 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13076 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13077 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13078 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13079 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13080 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013081 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013082 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013083 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013084 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013085 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013086 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013087 {"maketrans", (PyCFunction) unicode_maketrans,
13088 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013089 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013090#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013091 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013092 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093#endif
13094
Benjamin Peterson14339b62009-01-31 16:36:08 +000013095 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096 {NULL, NULL}
13097};
13098
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013099static PyObject *
13100unicode_mod(PyObject *v, PyObject *w)
13101{
Brian Curtindfc80e32011-08-10 20:28:54 -050013102 if (!PyUnicode_Check(v))
13103 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013104 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013105}
13106
13107static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013108 0, /*nb_add*/
13109 0, /*nb_subtract*/
13110 0, /*nb_multiply*/
13111 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013112};
13113
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013115 (lenfunc) unicode_length, /* sq_length */
13116 PyUnicode_Concat, /* sq_concat */
13117 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13118 (ssizeargfunc) unicode_getitem, /* sq_item */
13119 0, /* sq_slice */
13120 0, /* sq_ass_item */
13121 0, /* sq_ass_slice */
13122 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123};
13124
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013125static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013126unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013127{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 if (PyUnicode_READY(self) == -1)
13129 return NULL;
13130
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013131 if (PyIndex_Check(item)) {
13132 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013133 if (i == -1 && PyErr_Occurred())
13134 return NULL;
13135 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013137 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013138 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013139 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013140 PyObject *result;
13141 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013142 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013143 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013146 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013147 return NULL;
13148 }
13149
13150 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013151 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013153 slicelength == PyUnicode_GET_LENGTH(self)) {
13154 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013155 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013156 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013157 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013158 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013159 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013160 src_kind = PyUnicode_KIND(self);
13161 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013162 if (!PyUnicode_IS_ASCII(self)) {
13163 kind_limit = kind_maxchar_limit(src_kind);
13164 max_char = 0;
13165 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13166 ch = PyUnicode_READ(src_kind, src_data, cur);
13167 if (ch > max_char) {
13168 max_char = ch;
13169 if (max_char >= kind_limit)
13170 break;
13171 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013172 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013173 }
Victor Stinner55c99112011-10-13 01:17:06 +020013174 else
13175 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013176 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013177 if (result == NULL)
13178 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013179 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013180 dest_data = PyUnicode_DATA(result);
13181
13182 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013183 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13184 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013185 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013186 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013187 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013188 } else {
13189 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13190 return NULL;
13191 }
13192}
13193
13194static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013195 (lenfunc)unicode_length, /* mp_length */
13196 (binaryfunc)unicode_subscript, /* mp_subscript */
13197 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013198};
13199
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201/* Helpers for PyUnicode_Format() */
13202
13203static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013204getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013206 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 (*p_argidx)++;
13209 if (arglen < 0)
13210 return args;
13211 else
13212 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213 }
13214 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013215 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216 return NULL;
13217}
13218
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013219/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220
Victor Stinnerd3f08822012-05-29 12:57:52 +020013221static int
13222formatfloat(PyObject *v, int flags, int prec, int type,
13223 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013225 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013227 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013228
Guido van Rossumd57fd912000-03-10 22:53:23 +000013229 x = PyFloat_AsDouble(v);
13230 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013231 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013232
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013234 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013235
Eric Smith0923d1d2009-04-16 20:16:10 +000013236 p = PyOS_double_to_string(x, type, prec,
13237 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013238 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013239 return -1;
13240 len = strlen(p);
13241 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013242 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13243 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013244 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013245 }
Victor Stinner184252a2012-06-16 02:57:41 +020013246 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013247 writer->pos += len;
13248 }
13249 else
13250 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013251 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013252 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253}
13254
Victor Stinnerd0880d52012-04-27 23:40:13 +020013255/* formatlong() emulates the format codes d, u, o, x and X, and
13256 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13257 * Python's regular ints.
13258 * Return value: a new PyUnicodeObject*, or NULL if error.
13259 * The output string is of the form
13260 * "-"? ("0x" | "0X")? digit+
13261 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13262 * set in flags. The case of hex digits will be correct,
13263 * There will be at least prec digits, zero-filled on the left if
13264 * necessary to get that many.
13265 * val object to be converted
13266 * flags bitmask of format flags; only F_ALT is looked at
13267 * prec minimum number of digits; 0-fill on left if needed
13268 * type a character in [duoxX]; u acts the same as d
13269 *
13270 * CAUTION: o, x and X conversions on regular ints can never
13271 * produce a '-' sign, but can for Python's unbounded ints.
13272 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013273static PyObject*
13274formatlong(PyObject *val, int flags, int prec, int type)
13275{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013276 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013277 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013278 Py_ssize_t i;
13279 int sign; /* 1 if '-', else 0 */
13280 int len; /* number of characters */
13281 Py_ssize_t llen;
13282 int numdigits; /* len == numnondigits + numdigits */
13283 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013284
Victor Stinnerd0880d52012-04-27 23:40:13 +020013285 /* Avoid exceeding SSIZE_T_MAX */
13286 if (prec > INT_MAX-3) {
13287 PyErr_SetString(PyExc_OverflowError,
13288 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013289 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013290 }
13291
13292 assert(PyLong_Check(val));
13293
13294 switch (type) {
13295 case 'd':
13296 case 'u':
13297 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013298 if (PyBool_Check(val))
13299 result = PyNumber_ToBase(val, 10);
13300 else
13301 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013302 break;
13303 case 'o':
13304 numnondigits = 2;
13305 result = PyNumber_ToBase(val, 8);
13306 break;
13307 case 'x':
13308 case 'X':
13309 numnondigits = 2;
13310 result = PyNumber_ToBase(val, 16);
13311 break;
13312 default:
13313 assert(!"'type' not in [duoxX]");
13314 }
13315 if (!result)
13316 return NULL;
13317
13318 assert(unicode_modifiable(result));
13319 assert(PyUnicode_IS_READY(result));
13320 assert(PyUnicode_IS_ASCII(result));
13321
13322 /* To modify the string in-place, there can only be one reference. */
13323 if (Py_REFCNT(result) != 1) {
13324 PyErr_BadInternalCall();
13325 return NULL;
13326 }
13327 buf = PyUnicode_DATA(result);
13328 llen = PyUnicode_GET_LENGTH(result);
13329 if (llen > INT_MAX) {
13330 PyErr_SetString(PyExc_ValueError,
13331 "string too large in _PyBytes_FormatLong");
13332 return NULL;
13333 }
13334 len = (int)llen;
13335 sign = buf[0] == '-';
13336 numnondigits += sign;
13337 numdigits = len - numnondigits;
13338 assert(numdigits > 0);
13339
13340 /* Get rid of base marker unless F_ALT */
13341 if (((flags & F_ALT) == 0 &&
13342 (type == 'o' || type == 'x' || type == 'X'))) {
13343 assert(buf[sign] == '0');
13344 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13345 buf[sign+1] == 'o');
13346 numnondigits -= 2;
13347 buf += 2;
13348 len -= 2;
13349 if (sign)
13350 buf[0] = '-';
13351 assert(len == numnondigits + numdigits);
13352 assert(numdigits > 0);
13353 }
13354
13355 /* Fill with leading zeroes to meet minimum width. */
13356 if (prec > numdigits) {
13357 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13358 numnondigits + prec);
13359 char *b1;
13360 if (!r1) {
13361 Py_DECREF(result);
13362 return NULL;
13363 }
13364 b1 = PyBytes_AS_STRING(r1);
13365 for (i = 0; i < numnondigits; ++i)
13366 *b1++ = *buf++;
13367 for (i = 0; i < prec - numdigits; i++)
13368 *b1++ = '0';
13369 for (i = 0; i < numdigits; i++)
13370 *b1++ = *buf++;
13371 *b1 = '\0';
13372 Py_DECREF(result);
13373 result = r1;
13374 buf = PyBytes_AS_STRING(result);
13375 len = numnondigits + prec;
13376 }
13377
13378 /* Fix up case for hex conversions. */
13379 if (type == 'X') {
13380 /* Need to convert all lower case letters to upper case.
13381 and need to convert 0x to 0X (and -0x to -0X). */
13382 for (i = 0; i < len; i++)
13383 if (buf[i] >= 'a' && buf[i] <= 'x')
13384 buf[i] -= 'a'-'A';
13385 }
13386 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13387 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013388 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013389 Py_DECREF(result);
13390 result = unicode;
13391 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013392 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013393}
13394
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013395static Py_UCS4
13396formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013397{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013398 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013399 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013400 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013401 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 goto onError;
13404 }
13405 else {
13406 /* Integer input truncated to a character */
13407 long x;
13408 x = PyLong_AsLong(v);
13409 if (x == -1 && PyErr_Occurred())
13410 goto onError;
13411
Victor Stinner8faf8212011-12-08 22:14:11 +010013412 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 PyErr_SetString(PyExc_OverflowError,
13414 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013415 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 }
13417
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013418 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013419 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013420
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013422 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013424 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013425}
13426
Alexander Belopolsky40018472011-02-26 01:02:56 +000013427PyObject *
13428PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013429{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013430 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013431 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013433 PyObject *temp = NULL;
13434 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013435 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013436 void *fmt;
13437 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013438 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013439 Py_ssize_t sublen;
13440 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013441
Guido van Rossumd57fd912000-03-10 22:53:23 +000013442 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 PyErr_BadInternalCall();
13444 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013445 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013446 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013447 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013448 return NULL;
Victor Stinner19294072012-10-05 00:09:33 +020013449 if (PyUnicode_READY(uformat) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013450 Py_DECREF(uformat);
Victor Stinner19294072012-10-05 00:09:33 +020013451 return NULL;
13452 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013454 fmt = PyUnicode_DATA(uformat);
13455 fmtkind = PyUnicode_KIND(uformat);
13456 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13457 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013458
Victor Stinnerd3f08822012-05-29 12:57:52 +020013459 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013460
Guido van Rossumd57fd912000-03-10 22:53:23 +000013461 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 arglen = PyTuple_Size(args);
13463 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013464 }
13465 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 arglen = -1;
13467 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013468 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013469 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013471
13472 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013473 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013474 Py_ssize_t nonfmtpos;
13475 nonfmtpos = fmtpos++;
13476 while (fmtcnt >= 0 &&
13477 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13478 fmtpos++;
13479 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013480 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013481 if (fmtcnt < 0)
13482 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013483 sublen = fmtpos - nonfmtpos;
13484 maxchar = _PyUnicode_FindMaxChar(uformat,
13485 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013486 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013487 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013488
Victor Stinnerd3f08822012-05-29 12:57:52 +020013489 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13490 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013491 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013492 }
13493 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 /* Got a format specifier */
13495 int flags = 0;
13496 Py_ssize_t width = -1;
13497 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013498 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013499 Py_UCS4 fill;
13500 int sign;
13501 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 int isnumok;
13503 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013504 void *pbuf = NULL;
13505 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013506 Py_UCS4 bufmaxchar;
13507 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013509 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013510 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13511 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013512 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013513 Py_ssize_t keylen;
13514 PyObject *key;
13515 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013516
Benjamin Peterson29060642009-01-31 22:14:21 +000013517 if (dict == NULL) {
13518 PyErr_SetString(PyExc_TypeError,
13519 "format requires a mapping");
13520 goto onError;
13521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013522 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 /* Skip over balanced parentheses */
13526 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013527 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13528 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013529 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013530 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013532 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013533 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013534 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 if (fmtcnt < 0 || pcount > 0) {
13536 PyErr_SetString(PyExc_ValueError,
13537 "incomplete format key");
13538 goto onError;
13539 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013540 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013541 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013542 if (key == NULL)
13543 goto onError;
13544 if (args_owned) {
13545 Py_DECREF(args);
13546 args_owned = 0;
13547 }
13548 args = PyObject_GetItem(dict, key);
13549 Py_DECREF(key);
13550 if (args == NULL) {
13551 goto onError;
13552 }
13553 args_owned = 1;
13554 arglen = -1;
13555 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013556 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013557 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013558 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13559 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 case '-': flags |= F_LJUST; continue;
13561 case '+': flags |= F_SIGN; continue;
13562 case ' ': flags |= F_BLANK; continue;
13563 case '#': flags |= F_ALT; continue;
13564 case '0': flags |= F_ZERO; continue;
13565 }
13566 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013567 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013568 if (c == '*') {
13569 v = getnextarg(args, arglen, &argidx);
13570 if (v == NULL)
13571 goto onError;
13572 if (!PyLong_Check(v)) {
13573 PyErr_SetString(PyExc_TypeError,
13574 "* wants int");
13575 goto onError;
13576 }
Serhiy Storchaka441d30f2013-01-19 12:26:26 +020013577 width = PyLong_AsSsize_t(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 if (width == -1 && PyErr_Occurred())
13579 goto onError;
13580 if (width < 0) {
13581 flags |= F_LJUST;
13582 width = -width;
13583 }
13584 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013585 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 }
13587 else if (c >= '0' && c <= '9') {
13588 width = c - '0';
13589 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013590 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 if (c < '0' || c > '9')
13592 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013593 /* Since c is unsigned, the RHS would end up as unsigned,
13594 mixing signed and unsigned comparison. Since c is between
13595 '0' and '9', casting to int is safe. */
13596 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 PyErr_SetString(PyExc_ValueError,
13598 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013599 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 }
13601 width = width*10 + (c - '0');
13602 }
13603 }
13604 if (c == '.') {
13605 prec = 0;
13606 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013607 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013608 if (c == '*') {
13609 v = getnextarg(args, arglen, &argidx);
13610 if (v == NULL)
13611 goto onError;
13612 if (!PyLong_Check(v)) {
13613 PyErr_SetString(PyExc_TypeError,
13614 "* wants int");
13615 goto onError;
13616 }
Serhiy Storchaka441d30f2013-01-19 12:26:26 +020013617 prec = _PyLong_AsInt(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013618 if (prec == -1 && PyErr_Occurred())
13619 goto onError;
13620 if (prec < 0)
13621 prec = 0;
13622 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013623 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 }
13625 else if (c >= '0' && c <= '9') {
13626 prec = c - '0';
13627 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013628 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013629 if (c < '0' || c > '9')
13630 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013631 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 PyErr_SetString(PyExc_ValueError,
13633 "prec too big");
13634 goto onError;
13635 }
13636 prec = prec*10 + (c - '0');
13637 }
13638 }
13639 } /* prec */
13640 if (fmtcnt >= 0) {
13641 if (c == 'h' || c == 'l' || c == 'L') {
13642 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013643 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013644 }
13645 }
13646 if (fmtcnt < 0) {
13647 PyErr_SetString(PyExc_ValueError,
13648 "incomplete format");
13649 goto onError;
13650 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013651 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013652 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013653
13654 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013655 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013656 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013657 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13658 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013659 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013660 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013661
Victor Stinneraff3cc62012-04-30 05:19:21 +020013662 v = getnextarg(args, arglen, &argidx);
13663 if (v == NULL)
13664 goto onError;
13665
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013667 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 fill = ' ';
13669 switch (c) {
13670
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 case 's':
13672 case 'r':
13673 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013674 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13675 /* Fast path */
13676 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13677 goto onError;
13678 goto nextarg;
13679 }
13680
Victor Stinner808fc0a2010-03-22 12:50:40 +000013681 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013682 temp = v;
13683 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013684 }
13685 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013686 if (c == 's')
13687 temp = PyObject_Str(v);
13688 else if (c == 'r')
13689 temp = PyObject_Repr(v);
13690 else
13691 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013692 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 break;
13694
13695 case 'i':
13696 case 'd':
13697 case 'u':
13698 case 'o':
13699 case 'x':
13700 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013701 if (PyLong_CheckExact(v)
13702 && width == -1 && prec == -1
13703 && !(flags & (F_SIGN | F_BLANK)))
13704 {
13705 /* Fast path */
13706 switch(c)
13707 {
13708 case 'd':
13709 case 'i':
13710 case 'u':
13711 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13712 goto onError;
13713 goto nextarg;
13714 case 'x':
13715 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13716 goto onError;
13717 goto nextarg;
13718 case 'o':
13719 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13720 goto onError;
13721 goto nextarg;
13722 default:
13723 break;
13724 }
13725 }
13726
Benjamin Peterson29060642009-01-31 22:14:21 +000013727 isnumok = 0;
13728 if (PyNumber_Check(v)) {
13729 PyObject *iobj=NULL;
13730
13731 if (PyLong_Check(v)) {
13732 iobj = v;
13733 Py_INCREF(iobj);
13734 }
13735 else {
13736 iobj = PyNumber_Long(v);
13737 }
13738 if (iobj!=NULL) {
13739 if (PyLong_Check(iobj)) {
13740 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013741 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013742 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013743 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013744 }
13745 else {
13746 Py_DECREF(iobj);
13747 }
13748 }
13749 }
13750 if (!isnumok) {
13751 PyErr_Format(PyExc_TypeError,
13752 "%%%c format: a number is required, "
13753 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13754 goto onError;
13755 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013756 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013757 fill = '0';
13758 break;
13759
13760 case 'e':
13761 case 'E':
13762 case 'f':
13763 case 'F':
13764 case 'g':
13765 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013766 if (width == -1 && prec == -1
13767 && !(flags & (F_SIGN | F_BLANK)))
13768 {
13769 /* Fast path */
13770 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13771 goto onError;
13772 goto nextarg;
13773 }
13774
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013776 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013777 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013778 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13779 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013780 break;
13781
13782 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013783 {
13784 Py_UCS4 ch = formatchar(v);
13785 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013787 if (width == -1 && prec == -1) {
13788 /* Fast path */
13789 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13790 goto onError;
13791 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13792 writer.pos += 1;
13793 goto nextarg;
13794 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013795 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013796 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013797 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013798
13799 default:
13800 PyErr_Format(PyExc_ValueError,
13801 "unsupported format character '%c' (0x%x) "
13802 "at index %zd",
13803 (31<=c && c<=126) ? (char)c : '?',
13804 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013805 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013806 goto onError;
13807 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013808 if (temp == NULL)
13809 goto onError;
13810 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013811
13812 if (width == -1 && prec == -1
13813 && !(flags & (F_SIGN | F_BLANK)))
13814 {
13815 /* Fast path */
13816 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13817 goto onError;
13818 goto nextarg;
13819 }
13820
Victor Stinneraff3cc62012-04-30 05:19:21 +020013821 if (PyUnicode_READY(temp) == -1) {
13822 Py_CLEAR(temp);
13823 goto onError;
13824 }
13825 kind = PyUnicode_KIND(temp);
13826 pbuf = PyUnicode_DATA(temp);
13827 len = PyUnicode_GET_LENGTH(temp);
13828
13829 if (c == 's' || c == 'r' || c == 'a') {
13830 if (prec >= 0 && len > prec)
13831 len = prec;
13832 }
13833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013834 /* pbuf is initialized here. */
13835 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013837 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13838 if (ch == '-' || ch == '+') {
13839 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013840 len--;
13841 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013842 }
13843 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013844 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013845 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013846 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013847 else
13848 sign = 0;
13849 }
13850 if (width < len)
13851 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013852
13853 /* Compute the length and maximum character of the
13854 written characters */
13855 bufmaxchar = 127;
13856 if (!(flags & F_LJUST)) {
13857 if (sign) {
13858 if ((width-1) > len)
Benjamin Peterson7e303732013-06-10 09:19:46 -070013859 bufmaxchar = Py_MAX(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013860 }
13861 else {
13862 if (width > len)
Benjamin Peterson7e303732013-06-10 09:19:46 -070013863 bufmaxchar = Py_MAX(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013864 }
13865 }
13866 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Benjamin Peterson7e303732013-06-10 09:19:46 -070013867 bufmaxchar = Py_MAX(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013868
13869 buflen = width;
13870 if (sign && len == width)
13871 buflen++;
13872
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013873 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013874 goto onError;
13875
13876 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013877 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013879 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13880 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013881 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013882 if (width > len)
13883 width--;
13884 }
13885 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013886 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013887 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013888 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013889 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13890 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13891 writer.pos += 2;
13892 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013893 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013894 width -= 2;
13895 if (width < 0)
13896 width = 0;
13897 len -= 2;
13898 }
13899 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013900 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013901 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13902 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013903 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013904 }
13905 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013906 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013907 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13908 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013909 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013910 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013911 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13912 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013913 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13914 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13915 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013916 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013917 }
13918 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013919
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013920 if (len) {
13921 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13922 temp, pindex, len);
13923 writer.pos += len;
13924 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013925 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013926 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013927 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13928 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013929 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013930
Victor Stinnerd3f08822012-05-29 12:57:52 +020013931nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013932 if (dict && (argidx < arglen) && c != '%') {
13933 PyErr_SetString(PyExc_TypeError,
13934 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013935 goto onError;
13936 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013937 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013938 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939 } /* until end */
13940 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013941 PyErr_SetString(PyExc_TypeError,
13942 "not all arguments converted during string formatting");
13943 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013944 }
13945
13946 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013947 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013948 }
13949 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013950 Py_XDECREF(temp);
13951 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013952 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953
Benjamin Peterson29060642009-01-31 22:14:21 +000013954 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013955 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013956 Py_XDECREF(temp);
13957 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013958 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013959 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013960 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013961 }
13962 return NULL;
13963}
13964
Jeremy Hylton938ace62002-07-17 16:30:39 +000013965static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013966unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13967
Tim Peters6d6c1a32001-08-02 04:15:00 +000013968static PyObject *
13969unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13970{
Benjamin Peterson29060642009-01-31 22:14:21 +000013971 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013972 static char *kwlist[] = {"object", "encoding", "errors", 0};
13973 char *encoding = NULL;
13974 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013975
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 if (type != &PyUnicode_Type)
13977 return unicode_subtype_new(type, args, kwds);
13978 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013979 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013980 return NULL;
13981 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020013982 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000013983 if (encoding == NULL && errors == NULL)
13984 return PyObject_Str(x);
13985 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013986 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013987}
13988
Guido van Rossume023fe02001-08-30 03:12:59 +000013989static PyObject *
13990unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13991{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013992 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993 Py_ssize_t length, char_size;
13994 int share_wstr, share_utf8;
13995 unsigned int kind;
13996 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013997
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013999
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014000 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014001 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014002 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014003 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014004 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014005 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014006 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014007 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014008
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014009 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014010 if (self == NULL) {
14011 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014012 return NULL;
14013 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014014 kind = PyUnicode_KIND(unicode);
14015 length = PyUnicode_GET_LENGTH(unicode);
14016
14017 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014018#ifdef Py_DEBUG
14019 _PyUnicode_HASH(self) = -1;
14020#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014021 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014022#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014023 _PyUnicode_STATE(self).interned = 0;
14024 _PyUnicode_STATE(self).kind = kind;
14025 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014026 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014027 _PyUnicode_STATE(self).ready = 1;
14028 _PyUnicode_WSTR(self) = NULL;
14029 _PyUnicode_UTF8_LENGTH(self) = 0;
14030 _PyUnicode_UTF8(self) = NULL;
14031 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014032 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014033
14034 share_utf8 = 0;
14035 share_wstr = 0;
14036 if (kind == PyUnicode_1BYTE_KIND) {
14037 char_size = 1;
14038 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14039 share_utf8 = 1;
14040 }
14041 else if (kind == PyUnicode_2BYTE_KIND) {
14042 char_size = 2;
14043 if (sizeof(wchar_t) == 2)
14044 share_wstr = 1;
14045 }
14046 else {
14047 assert(kind == PyUnicode_4BYTE_KIND);
14048 char_size = 4;
14049 if (sizeof(wchar_t) == 4)
14050 share_wstr = 1;
14051 }
14052
14053 /* Ensure we won't overflow the length. */
14054 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14055 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014056 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014058 data = PyObject_MALLOC((length + 1) * char_size);
14059 if (data == NULL) {
14060 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014061 goto onError;
14062 }
14063
Victor Stinnerc3c74152011-10-02 20:39:55 +020014064 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014065 if (share_utf8) {
14066 _PyUnicode_UTF8_LENGTH(self) = length;
14067 _PyUnicode_UTF8(self) = data;
14068 }
14069 if (share_wstr) {
14070 _PyUnicode_WSTR_LENGTH(self) = length;
14071 _PyUnicode_WSTR(self) = (wchar_t *)data;
14072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014073
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014074 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014075 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014076 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014077#ifdef Py_DEBUG
14078 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14079#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014080 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014081 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014082
14083onError:
14084 Py_DECREF(unicode);
14085 Py_DECREF(self);
14086 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014087}
14088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014089PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014090"str(object='') -> str\n\
14091str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014092\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014093Create a new string object from the given object. If encoding or\n\
14094errors is specified, then the object must expose a data buffer\n\
14095that will be decoded using the given encoding and error handler.\n\
14096Otherwise, returns the result of object.__str__() (if defined)\n\
14097or repr(object).\n\
14098encoding defaults to sys.getdefaultencoding().\n\
14099errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014100
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014101static PyObject *unicode_iter(PyObject *seq);
14102
Guido van Rossumd57fd912000-03-10 22:53:23 +000014103PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014104 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014105 "str", /* tp_name */
14106 sizeof(PyUnicodeObject), /* tp_size */
14107 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014108 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014109 (destructor)unicode_dealloc, /* tp_dealloc */
14110 0, /* tp_print */
14111 0, /* tp_getattr */
14112 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014113 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014114 unicode_repr, /* tp_repr */
14115 &unicode_as_number, /* tp_as_number */
14116 &unicode_as_sequence, /* tp_as_sequence */
14117 &unicode_as_mapping, /* tp_as_mapping */
14118 (hashfunc) unicode_hash, /* tp_hash*/
14119 0, /* tp_call*/
14120 (reprfunc) unicode_str, /* tp_str */
14121 PyObject_GenericGetAttr, /* tp_getattro */
14122 0, /* tp_setattro */
14123 0, /* tp_as_buffer */
14124 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014125 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014126 unicode_doc, /* tp_doc */
14127 0, /* tp_traverse */
14128 0, /* tp_clear */
14129 PyUnicode_RichCompare, /* tp_richcompare */
14130 0, /* tp_weaklistoffset */
14131 unicode_iter, /* tp_iter */
14132 0, /* tp_iternext */
14133 unicode_methods, /* tp_methods */
14134 0, /* tp_members */
14135 0, /* tp_getset */
14136 &PyBaseObject_Type, /* tp_base */
14137 0, /* tp_dict */
14138 0, /* tp_descr_get */
14139 0, /* tp_descr_set */
14140 0, /* tp_dictoffset */
14141 0, /* tp_init */
14142 0, /* tp_alloc */
14143 unicode_new, /* tp_new */
14144 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014145};
14146
14147/* Initialize the Unicode implementation */
14148
Victor Stinner3a50e702011-10-18 21:21:00 +020014149int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014150{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014151 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014152 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014153 0x000A, /* LINE FEED */
14154 0x000D, /* CARRIAGE RETURN */
14155 0x001C, /* FILE SEPARATOR */
14156 0x001D, /* GROUP SEPARATOR */
14157 0x001E, /* RECORD SEPARATOR */
14158 0x0085, /* NEXT LINE */
14159 0x2028, /* LINE SEPARATOR */
14160 0x2029, /* PARAGRAPH SEPARATOR */
14161 };
14162
Fred Drakee4315f52000-05-09 19:53:39 +000014163 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014164 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014165 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014166 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014167 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014168
Guido van Rossumcacfc072002-05-24 19:01:59 +000014169 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014170 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014171
14172 /* initialize the linebreak bloom filter */
14173 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014174 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014175 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014176
Christian Heimes26532f72013-07-20 14:57:16 +020014177 if (PyType_Ready(&EncodingMapType) < 0)
14178 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014179
Benjamin Petersonc4311282012-10-30 23:21:10 -040014180 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14181 Py_FatalError("Can't initialize field name iterator type");
14182
14183 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14184 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014185
Victor Stinner3a50e702011-10-18 21:21:00 +020014186#ifdef HAVE_MBCS
14187 winver.dwOSVersionInfoSize = sizeof(winver);
14188 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14189 PyErr_SetFromWindowsErr(0);
14190 return -1;
14191 }
14192#endif
14193 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014194}
14195
14196/* Finalize the Unicode implementation */
14197
Christian Heimesa156e092008-02-16 07:38:31 +000014198int
14199PyUnicode_ClearFreeList(void)
14200{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014201 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014202}
14203
Guido van Rossumd57fd912000-03-10 22:53:23 +000014204void
Thomas Wouters78890102000-07-22 19:25:51 +000014205_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014206{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014207 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014208
Serhiy Storchaka05997252013-01-26 12:14:02 +020014209 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014210
Serhiy Storchaka05997252013-01-26 12:14:02 +020014211 for (i = 0; i < 256; i++)
14212 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014213 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014214 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014215}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014216
Walter Dörwald16807132007-05-25 13:52:07 +000014217void
14218PyUnicode_InternInPlace(PyObject **p)
14219{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014220 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014221 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014222#ifdef Py_DEBUG
14223 assert(s != NULL);
14224 assert(_PyUnicode_CHECK(s));
14225#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014226 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014227 return;
14228#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014229 /* If it's a subclass, we don't really know what putting
14230 it in the interned dict might do. */
14231 if (!PyUnicode_CheckExact(s))
14232 return;
14233 if (PyUnicode_CHECK_INTERNED(s))
14234 return;
14235 if (interned == NULL) {
14236 interned = PyDict_New();
14237 if (interned == NULL) {
14238 PyErr_Clear(); /* Don't leave an exception */
14239 return;
14240 }
14241 }
14242 /* It might be that the GetItem call fails even
14243 though the key is present in the dictionary,
14244 namely when this happens during a stack overflow. */
14245 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014246 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014247 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014248
Benjamin Peterson29060642009-01-31 22:14:21 +000014249 if (t) {
14250 Py_INCREF(t);
14251 Py_DECREF(*p);
14252 *p = t;
14253 return;
14254 }
Walter Dörwald16807132007-05-25 13:52:07 +000014255
Benjamin Peterson14339b62009-01-31 16:36:08 +000014256 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014257 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 PyErr_Clear();
14259 PyThreadState_GET()->recursion_critical = 0;
14260 return;
14261 }
14262 PyThreadState_GET()->recursion_critical = 0;
14263 /* The two references in interned are not counted by refcnt.
14264 The deallocator will take care of this */
14265 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014266 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014267}
14268
14269void
14270PyUnicode_InternImmortal(PyObject **p)
14271{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014272 PyUnicode_InternInPlace(p);
14273 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014274 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 Py_INCREF(*p);
14276 }
Walter Dörwald16807132007-05-25 13:52:07 +000014277}
14278
14279PyObject *
14280PyUnicode_InternFromString(const char *cp)
14281{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 PyObject *s = PyUnicode_FromString(cp);
14283 if (s == NULL)
14284 return NULL;
14285 PyUnicode_InternInPlace(&s);
14286 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014287}
14288
Alexander Belopolsky40018472011-02-26 01:02:56 +000014289void
14290_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014291{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014292 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014293 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014294 Py_ssize_t i, n;
14295 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014296
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 if (interned == NULL || !PyDict_Check(interned))
14298 return;
14299 keys = PyDict_Keys(interned);
14300 if (keys == NULL || !PyList_Check(keys)) {
14301 PyErr_Clear();
14302 return;
14303 }
Walter Dörwald16807132007-05-25 13:52:07 +000014304
Benjamin Peterson14339b62009-01-31 16:36:08 +000014305 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14306 detector, interned unicode strings are not forcibly deallocated;
14307 rather, we give them their stolen references back, and then clear
14308 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014309
Benjamin Peterson14339b62009-01-31 16:36:08 +000014310 n = PyList_GET_SIZE(keys);
14311 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014312 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014314 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014315 if (PyUnicode_READY(s) == -1) {
14316 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014317 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014318 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014319 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 case SSTATE_NOT_INTERNED:
14321 /* XXX Shouldn't happen */
14322 break;
14323 case SSTATE_INTERNED_IMMORTAL:
14324 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014325 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014326 break;
14327 case SSTATE_INTERNED_MORTAL:
14328 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014329 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014330 break;
14331 default:
14332 Py_FatalError("Inconsistent interned string state.");
14333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014334 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014335 }
14336 fprintf(stderr, "total size of all interned strings: "
14337 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14338 "mortal/immortal\n", mortal_size, immortal_size);
14339 Py_DECREF(keys);
14340 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014341 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014342}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014343
14344
14345/********************* Unicode Iterator **************************/
14346
14347typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014348 PyObject_HEAD
14349 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014350 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014351} unicodeiterobject;
14352
14353static void
14354unicodeiter_dealloc(unicodeiterobject *it)
14355{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014356 _PyObject_GC_UNTRACK(it);
14357 Py_XDECREF(it->it_seq);
14358 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014359}
14360
14361static int
14362unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14363{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014364 Py_VISIT(it->it_seq);
14365 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014366}
14367
14368static PyObject *
14369unicodeiter_next(unicodeiterobject *it)
14370{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014371 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014372
Benjamin Peterson14339b62009-01-31 16:36:08 +000014373 assert(it != NULL);
14374 seq = it->it_seq;
14375 if (seq == NULL)
14376 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014377 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014379 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14380 int kind = PyUnicode_KIND(seq);
14381 void *data = PyUnicode_DATA(seq);
14382 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14383 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014384 if (item != NULL)
14385 ++it->it_index;
14386 return item;
14387 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014388
Benjamin Peterson14339b62009-01-31 16:36:08 +000014389 Py_DECREF(seq);
14390 it->it_seq = NULL;
14391 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014392}
14393
14394static PyObject *
14395unicodeiter_len(unicodeiterobject *it)
14396{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014397 Py_ssize_t len = 0;
14398 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014399 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014400 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014401}
14402
14403PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14404
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014405static PyObject *
14406unicodeiter_reduce(unicodeiterobject *it)
14407{
14408 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014409 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014410 it->it_seq, it->it_index);
14411 } else {
14412 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14413 if (u == NULL)
14414 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014415 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014416 }
14417}
14418
14419PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14420
14421static PyObject *
14422unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14423{
14424 Py_ssize_t index = PyLong_AsSsize_t(state);
14425 if (index == -1 && PyErr_Occurred())
14426 return NULL;
14427 if (index < 0)
14428 index = 0;
14429 it->it_index = index;
14430 Py_RETURN_NONE;
14431}
14432
14433PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14434
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014435static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014436 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014437 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014438 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14439 reduce_doc},
14440 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14441 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014442 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014443};
14444
14445PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014446 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14447 "str_iterator", /* tp_name */
14448 sizeof(unicodeiterobject), /* tp_basicsize */
14449 0, /* tp_itemsize */
14450 /* methods */
14451 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14452 0, /* tp_print */
14453 0, /* tp_getattr */
14454 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014455 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014456 0, /* tp_repr */
14457 0, /* tp_as_number */
14458 0, /* tp_as_sequence */
14459 0, /* tp_as_mapping */
14460 0, /* tp_hash */
14461 0, /* tp_call */
14462 0, /* tp_str */
14463 PyObject_GenericGetAttr, /* tp_getattro */
14464 0, /* tp_setattro */
14465 0, /* tp_as_buffer */
14466 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14467 0, /* tp_doc */
14468 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14469 0, /* tp_clear */
14470 0, /* tp_richcompare */
14471 0, /* tp_weaklistoffset */
14472 PyObject_SelfIter, /* tp_iter */
14473 (iternextfunc)unicodeiter_next, /* tp_iternext */
14474 unicodeiter_methods, /* tp_methods */
14475 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014476};
14477
14478static PyObject *
14479unicode_iter(PyObject *seq)
14480{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014481 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014482
Benjamin Peterson14339b62009-01-31 16:36:08 +000014483 if (!PyUnicode_Check(seq)) {
14484 PyErr_BadInternalCall();
14485 return NULL;
14486 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014487 if (PyUnicode_READY(seq) == -1)
14488 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014489 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14490 if (it == NULL)
14491 return NULL;
14492 it->it_index = 0;
14493 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014494 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014495 _PyObject_GC_TRACK(it);
14496 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014497}
14498
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014499
14500size_t
14501Py_UNICODE_strlen(const Py_UNICODE *u)
14502{
14503 int res = 0;
14504 while(*u++)
14505 res++;
14506 return res;
14507}
14508
14509Py_UNICODE*
14510Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14511{
14512 Py_UNICODE *u = s1;
14513 while ((*u++ = *s2++));
14514 return s1;
14515}
14516
14517Py_UNICODE*
14518Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14519{
14520 Py_UNICODE *u = s1;
14521 while ((*u++ = *s2++))
14522 if (n-- == 0)
14523 break;
14524 return s1;
14525}
14526
14527Py_UNICODE*
14528Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14529{
14530 Py_UNICODE *u1 = s1;
14531 u1 += Py_UNICODE_strlen(u1);
14532 Py_UNICODE_strcpy(u1, s2);
14533 return s1;
14534}
14535
14536int
14537Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14538{
14539 while (*s1 && *s2 && *s1 == *s2)
14540 s1++, s2++;
14541 if (*s1 && *s2)
14542 return (*s1 < *s2) ? -1 : +1;
14543 if (*s1)
14544 return 1;
14545 if (*s2)
14546 return -1;
14547 return 0;
14548}
14549
14550int
14551Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14552{
14553 register Py_UNICODE u1, u2;
14554 for (; n != 0; n--) {
14555 u1 = *s1;
14556 u2 = *s2;
14557 if (u1 != u2)
14558 return (u1 < u2) ? -1 : +1;
14559 if (u1 == '\0')
14560 return 0;
14561 s1++;
14562 s2++;
14563 }
14564 return 0;
14565}
14566
14567Py_UNICODE*
14568Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14569{
14570 const Py_UNICODE *p;
14571 for (p = s; *p; p++)
14572 if (*p == c)
14573 return (Py_UNICODE*)p;
14574 return NULL;
14575}
14576
14577Py_UNICODE*
14578Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14579{
14580 const Py_UNICODE *p;
14581 p = s + Py_UNICODE_strlen(s);
14582 while (p != s) {
14583 p--;
14584 if (*p == c)
14585 return (Py_UNICODE*)p;
14586 }
14587 return NULL;
14588}
Victor Stinner331ea922010-08-10 16:37:20 +000014589
Victor Stinner71133ff2010-09-01 23:43:53 +000014590Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014591PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014592{
Victor Stinner577db2c2011-10-11 22:12:48 +020014593 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014594 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014596 if (!PyUnicode_Check(unicode)) {
14597 PyErr_BadArgument();
14598 return NULL;
14599 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014600 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014601 if (u == NULL)
14602 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014603 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014604 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014605 PyErr_NoMemory();
14606 return NULL;
14607 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014608 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014609 size *= sizeof(Py_UNICODE);
14610 copy = PyMem_Malloc(size);
14611 if (copy == NULL) {
14612 PyErr_NoMemory();
14613 return NULL;
14614 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014615 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014616 return copy;
14617}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014618
Georg Brandl66c221e2010-10-14 07:04:07 +000014619/* A _string module, to export formatter_parser and formatter_field_name_split
14620 to the string.Formatter class implemented in Python. */
14621
14622static PyMethodDef _string_methods[] = {
14623 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14624 METH_O, PyDoc_STR("split the argument as a field name")},
14625 {"formatter_parser", (PyCFunction) formatter_parser,
14626 METH_O, PyDoc_STR("parse the argument as a format string")},
14627 {NULL, NULL}
14628};
14629
14630static struct PyModuleDef _string_module = {
14631 PyModuleDef_HEAD_INIT,
14632 "_string",
14633 PyDoc_STR("string helper module"),
14634 0,
14635 _string_methods,
14636 NULL,
14637 NULL,
14638 NULL,
14639 NULL
14640};
14641
14642PyMODINIT_FUNC
14643PyInit__string(void)
14644{
14645 return PyModule_Create(&_string_module);
14646}
14647
14648
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014649#ifdef __cplusplus
14650}
14651#endif