blob: c96a91c3973218b3a30000e31e714eb725b1f1bb [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 Stinnere6abb482012-05-02 01:15:40 +0200115/* Optimized version of Py_MAX() to compute the maximum character:
116 use it when your are computing the second argument of PyUnicode_New() */
117#define MAX_MAXCHAR(maxchar1, maxchar2) \
118 ((maxchar1) | (maxchar2))
119
Victor Stinner910337b2011-10-03 03:20:16 +0200120#undef PyUnicode_READY
121#define PyUnicode_READY(op) \
122 (assert(_PyUnicode_CHECK(op)), \
123 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200124 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100125 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200126
Victor Stinnerc379ead2011-10-03 12:52:27 +0200127#define _PyUnicode_SHARE_UTF8(op) \
128 (assert(_PyUnicode_CHECK(op)), \
129 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
130 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
131#define _PyUnicode_SHARE_WSTR(op) \
132 (assert(_PyUnicode_CHECK(op)), \
133 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
134
Victor Stinner829c0ad2011-10-03 01:08:02 +0200135/* true if the Unicode object has an allocated UTF-8 memory block
136 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200137#define _PyUnicode_HAS_UTF8_MEMORY(op) \
138 (assert(_PyUnicode_CHECK(op)), \
139 (!PyUnicode_IS_COMPACT_ASCII(op) \
140 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200141 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
142
Victor Stinner03490912011-10-03 23:45:12 +0200143/* true if the Unicode object has an allocated wstr memory block
144 (not shared with other data) */
145#define _PyUnicode_HAS_WSTR_MEMORY(op) \
146 (assert(_PyUnicode_CHECK(op)), \
147 (_PyUnicode_WSTR(op) && \
148 (!PyUnicode_IS_READY(op) || \
149 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
150
Victor Stinner910337b2011-10-03 03:20:16 +0200151/* Generic helper macro to convert characters of different types.
152 from_type and to_type have to be valid type names, begin and end
153 are pointers to the source characters which should be of type
154 "from_type *". to is a pointer of type "to_type *" and points to the
155 buffer where the result characters are written to. */
156#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
157 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200158 to_type *_to = (to_type *) to; \
159 const from_type *_iter = (begin); \
160 const from_type *_end = (end); \
161 Py_ssize_t n = (_end) - (_iter); \
162 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200163 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200164 while (_iter < (_unrolled_end)) { \
165 _to[0] = (to_type) _iter[0]; \
166 _to[1] = (to_type) _iter[1]; \
167 _to[2] = (to_type) _iter[2]; \
168 _to[3] = (to_type) _iter[3]; \
169 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200170 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200171 while (_iter < (_end)) \
172 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200173 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200174
Walter Dörwald16807132007-05-25 13:52:07 +0000175/* This dictionary holds all interned unicode strings. Note that references
176 to strings in this dictionary are *not* counted in the string's ob_refcnt.
177 When the interned string reaches a refcnt of 0 the string deallocation
178 function will delete the reference from this dictionary.
179
180 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000181 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000182*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200183static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000184
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000185/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200187
Serhiy Storchaka678db842013-01-26 12:16:36 +0200188#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 do { \
190 if (unicode_empty != NULL) \
191 Py_INCREF(unicode_empty); \
192 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200193 unicode_empty = PyUnicode_New(0, 0); \
194 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200195 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200196 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200199 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000200
Serhiy Storchaka678db842013-01-26 12:16:36 +0200201#define _Py_RETURN_UNICODE_EMPTY() \
202 do { \
203 _Py_INCREF_UNICODE_EMPTY(); \
204 return unicode_empty; \
205 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000206
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200207/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200208static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200209
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000210/* Single character Unicode strings in the Latin-1 range are being
211 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200212static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213
Christian Heimes190d79e2008-01-30 11:58:22 +0000214/* Fast detection of the most frequent whitespace characters */
215const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000217/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000219/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000220/* case 0x000C: * FORM FEED */
221/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 1, 1, 1, 1, 1, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000224/* case 0x001C: * FILE SEPARATOR */
225/* case 0x001D: * GROUP SEPARATOR */
226/* case 0x001E: * RECORD SEPARATOR */
227/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000228 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000229/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000230 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000234
Benjamin Peterson14339b62009-01-31 16:36:08 +0000235 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,
238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000243};
244
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200245/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200246static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200247static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100248static int unicode_modifiable(PyObject *unicode);
249
Victor Stinnerfe226c02011-10-03 03:52:20 +0200250
Alexander Belopolsky40018472011-02-26 01:02:56 +0000251static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200252_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
253static PyObject *
254_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
255static PyObject *
256_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
257
258static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000259unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000260 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100261 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000262 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
263
Alexander Belopolsky40018472011-02-26 01:02:56 +0000264static void
265raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300266 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100267 PyObject *unicode,
268 Py_ssize_t startpos, Py_ssize_t endpos,
269 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000270
Christian Heimes190d79e2008-01-30 11:58:22 +0000271/* Same for linebreaks */
272static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000275/* 0x000B, * LINE TABULATION */
276/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x001C, * FILE SEPARATOR */
281/* 0x001D, * GROUP SEPARATOR */
282/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 1, 1, 1, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000288
Benjamin Peterson14339b62009-01-31 16:36:08 +0000289 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,
292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000297};
298
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300299/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
300 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000301Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000302PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000303{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000304#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000305 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000306#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000307 /* This is actually an illegal character, so it should
308 not be passed to unichr. */
309 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000310#endif
311}
312
Victor Stinner910337b2011-10-03 03:20:16 +0200313#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200314int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100315_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200316{
317 PyASCIIObject *ascii;
318 unsigned int kind;
319
320 assert(PyUnicode_Check(op));
321
322 ascii = (PyASCIIObject *)op;
323 kind = ascii->state.kind;
324
Victor Stinnera3b334d2011-10-03 13:53:37 +0200325 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200326 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200327 assert(ascii->state.ready == 1);
328 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200330 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200331 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200332
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 if (ascii->state.compact == 1) {
334 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200335 assert(kind == PyUnicode_1BYTE_KIND
336 || kind == PyUnicode_2BYTE_KIND
337 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200338 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200339 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200340 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 }
342 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
344
345 data = unicode->data.any;
346 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100347 assert(ascii->length == 0);
348 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200349 assert(ascii->state.compact == 0);
350 assert(ascii->state.ascii == 0);
351 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100352 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200353 assert(ascii->wstr != NULL);
354 assert(data == NULL);
355 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200356 }
357 else {
358 assert(kind == PyUnicode_1BYTE_KIND
359 || kind == PyUnicode_2BYTE_KIND
360 || kind == PyUnicode_4BYTE_KIND);
361 assert(ascii->state.compact == 0);
362 assert(ascii->state.ready == 1);
363 assert(data != NULL);
364 if (ascii->state.ascii) {
365 assert (compact->utf8 == data);
366 assert (compact->utf8_length == ascii->length);
367 }
368 else
369 assert (compact->utf8 != data);
370 }
371 }
372 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200373 if (
374#if SIZEOF_WCHAR_T == 2
375 kind == PyUnicode_2BYTE_KIND
376#else
377 kind == PyUnicode_4BYTE_KIND
378#endif
379 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200380 {
381 assert(ascii->wstr == data);
382 assert(compact->wstr_length == ascii->length);
383 } else
384 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200386
387 if (compact->utf8 == NULL)
388 assert(compact->utf8_length == 0);
389 if (ascii->wstr == NULL)
390 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200391 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200392 /* check that the best kind is used */
393 if (check_content && kind != PyUnicode_WCHAR_KIND)
394 {
395 Py_ssize_t i;
396 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 void *data;
398 Py_UCS4 ch;
399
400 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 for (i=0; i < ascii->length; i++)
402 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200403 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 if (ch > maxchar)
405 maxchar = ch;
406 }
407 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100408 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200409 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100410 assert(maxchar <= 255);
411 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200412 else
413 assert(maxchar < 128);
414 }
Victor Stinner77faf692011-11-20 18:56:05 +0100415 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200416 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100417 assert(maxchar <= 0xFFFF);
418 }
419 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200420 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100421 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100422 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200423 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200424 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400425 return 1;
426}
Victor Stinner910337b2011-10-03 03:20:16 +0200427#endif
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429static PyObject*
430unicode_result_wchar(PyObject *unicode)
431{
432#ifndef Py_DEBUG
433 Py_ssize_t len;
434
435 assert(Py_REFCNT(unicode) == 1);
436
437 len = _PyUnicode_WSTR_LENGTH(unicode);
438 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100439 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200440 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100441 }
442
443 if (len == 1) {
444 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
445 if (ch < 256) {
446 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
447 Py_DECREF(unicode);
448 return latin1_char;
449 }
450 }
451
452 if (_PyUnicode_Ready(unicode) < 0) {
453 Py_XDECREF(unicode);
454 return NULL;
455 }
456#else
457 /* don't make the result ready in debug mode to ensure that the caller
458 makes the string ready before using it */
459 assert(_PyUnicode_CheckConsistency(unicode, 1));
460#endif
461 return unicode;
462}
463
464static PyObject*
465unicode_result_ready(PyObject *unicode)
466{
467 Py_ssize_t length;
468
469 length = PyUnicode_GET_LENGTH(unicode);
470 if (length == 0) {
471 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100472 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200473 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100474 }
475 return unicode_empty;
476 }
477
478 if (length == 1) {
479 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
480 if (ch < 256) {
481 PyObject *latin1_char = unicode_latin1[ch];
482 if (latin1_char != NULL) {
483 if (unicode != latin1_char) {
484 Py_INCREF(latin1_char);
485 Py_DECREF(unicode);
486 }
487 return latin1_char;
488 }
489 else {
490 assert(_PyUnicode_CheckConsistency(unicode, 1));
491 Py_INCREF(unicode);
492 unicode_latin1[ch] = unicode;
493 return unicode;
494 }
495 }
496 }
497
498 assert(_PyUnicode_CheckConsistency(unicode, 1));
499 return unicode;
500}
501
502static PyObject*
503unicode_result(PyObject *unicode)
504{
505 assert(_PyUnicode_CHECK(unicode));
506 if (PyUnicode_IS_READY(unicode))
507 return unicode_result_ready(unicode);
508 else
509 return unicode_result_wchar(unicode);
510}
511
Victor Stinnerc4b49542011-12-11 22:44:26 +0100512static PyObject*
513unicode_result_unchanged(PyObject *unicode)
514{
515 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500516 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100517 return NULL;
518 Py_INCREF(unicode);
519 return unicode;
520 }
521 else
522 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100523 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100524}
525
Victor Stinner3a50e702011-10-18 21:21:00 +0200526#ifdef HAVE_MBCS
527static OSVERSIONINFOEX winver;
528#endif
529
Thomas Wouters477c8d52006-05-27 19:21:47 +0000530/* --- Bloom Filters ----------------------------------------------------- */
531
532/* stuff to implement simple "bloom filters" for Unicode characters.
533 to keep things simple, we use a single bitmask, using the least 5
534 bits from each unicode characters as the bit index. */
535
536/* the linebreak mask is set up by Unicode_Init below */
537
Antoine Pitrouf068f942010-01-13 14:19:12 +0000538#if LONG_BIT >= 128
539#define BLOOM_WIDTH 128
540#elif LONG_BIT >= 64
541#define BLOOM_WIDTH 64
542#elif LONG_BIT >= 32
543#define BLOOM_WIDTH 32
544#else
545#error "LONG_BIT is smaller than 32"
546#endif
547
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548#define BLOOM_MASK unsigned long
549
Serhiy Storchaka05997252013-01-26 12:14:02 +0200550static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
Antoine Pitrouf068f942010-01-13 14:19:12 +0000552#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
553#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554
Benjamin Peterson29060642009-01-31 22:14:21 +0000555#define BLOOM_LINEBREAK(ch) \
556 ((ch) < 128U ? ascii_linebreak[(ch)] : \
557 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
Alexander Belopolsky40018472011-02-26 01:02:56 +0000559Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200560make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000561{
562 /* calculate simple bloom-style bitmask for a given unicode string */
563
Antoine Pitrouf068f942010-01-13 14:19:12 +0000564 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 Py_ssize_t i;
566
567 mask = 0;
568 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200569 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570
571 return mask;
572}
573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200574#define BLOOM_MEMBER(mask, chr, str) \
575 (BLOOM(mask, chr) \
576 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200578/* Compilation of templated routines */
579
580#include "stringlib/asciilib.h"
581#include "stringlib/fastsearch.h"
582#include "stringlib/partition.h"
583#include "stringlib/split.h"
584#include "stringlib/count.h"
585#include "stringlib/find.h"
586#include "stringlib/find_max_char.h"
587#include "stringlib/localeutil.h"
588#include "stringlib/undef.h"
589
590#include "stringlib/ucs1lib.h"
591#include "stringlib/fastsearch.h"
592#include "stringlib/partition.h"
593#include "stringlib/split.h"
594#include "stringlib/count.h"
595#include "stringlib/find.h"
596#include "stringlib/find_max_char.h"
597#include "stringlib/localeutil.h"
598#include "stringlib/undef.h"
599
600#include "stringlib/ucs2lib.h"
601#include "stringlib/fastsearch.h"
602#include "stringlib/partition.h"
603#include "stringlib/split.h"
604#include "stringlib/count.h"
605#include "stringlib/find.h"
606#include "stringlib/find_max_char.h"
607#include "stringlib/localeutil.h"
608#include "stringlib/undef.h"
609
610#include "stringlib/ucs4lib.h"
611#include "stringlib/fastsearch.h"
612#include "stringlib/partition.h"
613#include "stringlib/split.h"
614#include "stringlib/count.h"
615#include "stringlib/find.h"
616#include "stringlib/find_max_char.h"
617#include "stringlib/localeutil.h"
618#include "stringlib/undef.h"
619
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200620#include "stringlib/unicodedefs.h"
621#include "stringlib/fastsearch.h"
622#include "stringlib/count.h"
623#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100624#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200625
Guido van Rossumd57fd912000-03-10 22:53:23 +0000626/* --- Unicode Object ----------------------------------------------------- */
627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200628static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200629fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200630
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200631Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
632 Py_ssize_t size, Py_UCS4 ch,
633 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200634{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200635 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
636
637 switch (kind) {
638 case PyUnicode_1BYTE_KIND:
639 {
640 Py_UCS1 ch1 = (Py_UCS1) ch;
641 if (ch1 == ch)
642 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
643 else
644 return -1;
645 }
646 case PyUnicode_2BYTE_KIND:
647 {
648 Py_UCS2 ch2 = (Py_UCS2) ch;
649 if (ch2 == ch)
650 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
651 else
652 return -1;
653 }
654 case PyUnicode_4BYTE_KIND:
655 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
656 default:
657 assert(0);
658 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200660}
661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662static PyObject*
663resize_compact(PyObject *unicode, Py_ssize_t length)
664{
665 Py_ssize_t char_size;
666 Py_ssize_t struct_size;
667 Py_ssize_t new_size;
668 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100669 PyObject *new_unicode;
Victor Stinner79891572012-05-03 13:43:07 +0200670 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200671 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100672 assert(PyUnicode_IS_COMPACT(unicode));
673
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200674 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100675 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676 struct_size = sizeof(PyASCIIObject);
677 else
678 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200679 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
682 PyErr_NoMemory();
683 return NULL;
684 }
685 new_size = (struct_size + (length + 1) * char_size);
686
Victor Stinner84def372011-12-11 20:04:56 +0100687 _Py_DEC_REFTOTAL;
688 _Py_ForgetReference(unicode);
689
690 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
691 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100692 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693 PyErr_NoMemory();
694 return NULL;
695 }
Victor Stinner84def372011-12-11 20:04:56 +0100696 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200697 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100698
Victor Stinnerfe226c02011-10-03 03:52:20 +0200699 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200700 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200701 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100702 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200703 _PyUnicode_WSTR_LENGTH(unicode) = length;
704 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200705 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
706 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200707 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200708 return unicode;
709}
710
Alexander Belopolsky40018472011-02-26 01:02:56 +0000711static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200712resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000713{
Victor Stinner95663112011-10-04 01:03:50 +0200714 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100715 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200716 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200717 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000718
Victor Stinnerfe226c02011-10-03 03:52:20 +0200719 if (PyUnicode_IS_READY(unicode)) {
720 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200721 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200722 void *data;
723
724 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200725 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200726 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
727 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200728
729 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
730 PyErr_NoMemory();
731 return -1;
732 }
733 new_size = (length + 1) * char_size;
734
Victor Stinner7a9105a2011-12-12 00:13:42 +0100735 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
736 {
737 PyObject_DEL(_PyUnicode_UTF8(unicode));
738 _PyUnicode_UTF8(unicode) = NULL;
739 _PyUnicode_UTF8_LENGTH(unicode) = 0;
740 }
741
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742 data = (PyObject *)PyObject_REALLOC(data, new_size);
743 if (data == NULL) {
744 PyErr_NoMemory();
745 return -1;
746 }
747 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200748 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200749 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200750 _PyUnicode_WSTR_LENGTH(unicode) = length;
751 }
752 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200753 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200754 _PyUnicode_UTF8_LENGTH(unicode) = length;
755 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200756 _PyUnicode_LENGTH(unicode) = length;
757 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200758 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200759 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200761 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200762 }
Victor Stinner95663112011-10-04 01:03:50 +0200763 assert(_PyUnicode_WSTR(unicode) != NULL);
764
765 /* check for integer overflow */
766 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
767 PyErr_NoMemory();
768 return -1;
769 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100770 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200771 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100772 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200773 if (!wstr) {
774 PyErr_NoMemory();
775 return -1;
776 }
777 _PyUnicode_WSTR(unicode) = wstr;
778 _PyUnicode_WSTR(unicode)[length] = 0;
779 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200780 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000781 return 0;
782}
783
Victor Stinnerfe226c02011-10-03 03:52:20 +0200784static PyObject*
785resize_copy(PyObject *unicode, Py_ssize_t length)
786{
787 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100788 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200789 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100790
Benjamin Petersonbac79492012-01-14 13:34:47 -0500791 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100792 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200793
794 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
795 if (copy == NULL)
796 return NULL;
797
798 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200799 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200800 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200801 }
802 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200803 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100804
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200805 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806 if (w == NULL)
807 return NULL;
808 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
809 copy_length = Py_MIN(copy_length, length);
810 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
811 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200812 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 }
814}
815
Guido van Rossumd57fd912000-03-10 22:53:23 +0000816/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000817 Ux0000 terminated; some code (e.g. new_identifier)
818 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000819
820 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000821 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000822
823*/
824
Alexander Belopolsky40018472011-02-26 01:02:56 +0000825static PyUnicodeObject *
826_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000827{
828 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200829 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000830
Thomas Wouters477c8d52006-05-27 19:21:47 +0000831 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000832 if (length == 0 && unicode_empty != NULL) {
833 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200834 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000835 }
836
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000837 /* Ensure we won't overflow the size. */
838 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
839 return (PyUnicodeObject *)PyErr_NoMemory();
840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200841 if (length < 0) {
842 PyErr_SetString(PyExc_SystemError,
843 "Negative size passed to _PyUnicode_New");
844 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000845 }
846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200847 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
848 if (unicode == NULL)
849 return NULL;
850 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
851 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
852 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100853 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000854 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100855 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200857
Jeremy Hyltond8082792003-09-16 19:41:39 +0000858 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000859 * the caller fails before initializing str -- unicode_resize()
860 * reads str[0], and the Keep-Alive optimization can keep memory
861 * allocated for str alive across a call to unicode_dealloc(unicode).
862 * We don't want unicode_resize to read uninitialized memory in
863 * that case.
864 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200865 _PyUnicode_WSTR(unicode)[0] = 0;
866 _PyUnicode_WSTR(unicode)[length] = 0;
867 _PyUnicode_WSTR_LENGTH(unicode) = length;
868 _PyUnicode_HASH(unicode) = -1;
869 _PyUnicode_STATE(unicode).interned = 0;
870 _PyUnicode_STATE(unicode).kind = 0;
871 _PyUnicode_STATE(unicode).compact = 0;
872 _PyUnicode_STATE(unicode).ready = 0;
873 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200874 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200875 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200876 _PyUnicode_UTF8(unicode) = NULL;
877 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100878 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000879 return unicode;
880}
881
Victor Stinnerf42dc442011-10-02 23:33:16 +0200882static const char*
883unicode_kind_name(PyObject *unicode)
884{
Victor Stinner42dfd712011-10-03 14:41:45 +0200885 /* don't check consistency: unicode_kind_name() is called from
886 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200887 if (!PyUnicode_IS_COMPACT(unicode))
888 {
889 if (!PyUnicode_IS_READY(unicode))
890 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600891 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200892 {
893 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200894 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200895 return "legacy ascii";
896 else
897 return "legacy latin1";
898 case PyUnicode_2BYTE_KIND:
899 return "legacy UCS2";
900 case PyUnicode_4BYTE_KIND:
901 return "legacy UCS4";
902 default:
903 return "<legacy invalid kind>";
904 }
905 }
906 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600907 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200908 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200909 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200910 return "ascii";
911 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200912 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200913 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200914 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200915 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200916 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200917 default:
918 return "<invalid compact kind>";
919 }
920}
921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923/* Functions wrapping macros for use in debugger */
924char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200925 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200926}
927
928void *_PyUnicode_compact_data(void *unicode) {
929 return _PyUnicode_COMPACT_DATA(unicode);
930}
931void *_PyUnicode_data(void *unicode){
932 printf("obj %p\n", unicode);
933 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
934 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
935 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
936 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
937 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
938 return PyUnicode_DATA(unicode);
939}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200940
941void
942_PyUnicode_Dump(PyObject *op)
943{
944 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200945 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
946 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
947 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200948
Victor Stinnera849a4b2011-10-03 12:12:11 +0200949 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200950 {
951 if (ascii->state.ascii)
952 data = (ascii + 1);
953 else
954 data = (compact + 1);
955 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200956 else
957 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200958 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
959
Victor Stinnera849a4b2011-10-03 12:12:11 +0200960 if (ascii->wstr == data)
961 printf("shared ");
962 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200963
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200965 printf(" (%zu), ", compact->wstr_length);
966 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
967 printf("shared ");
968 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200969 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200970 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200971}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200972#endif
973
974PyObject *
975PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
976{
977 PyObject *obj;
978 PyCompactUnicodeObject *unicode;
979 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200980 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200981 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982 Py_ssize_t char_size;
983 Py_ssize_t struct_size;
984
985 /* Optimization for empty strings */
986 if (size == 0 && unicode_empty != NULL) {
987 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200988 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989 }
990
Victor Stinner9e9d6892011-10-04 01:02:02 +0200991 is_ascii = 0;
992 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993 struct_size = sizeof(PyCompactUnicodeObject);
994 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +0200995 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996 char_size = 1;
997 is_ascii = 1;
998 struct_size = sizeof(PyASCIIObject);
999 }
1000 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001001 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 char_size = 1;
1003 }
1004 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001005 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006 char_size = 2;
1007 if (sizeof(wchar_t) == 2)
1008 is_sharing = 1;
1009 }
1010 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001011 if (maxchar > MAX_UNICODE) {
1012 PyErr_SetString(PyExc_SystemError,
1013 "invalid maximum character passed to PyUnicode_New");
1014 return NULL;
1015 }
Victor Stinner8f825062012-04-27 13:55:39 +02001016 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001017 char_size = 4;
1018 if (sizeof(wchar_t) == 4)
1019 is_sharing = 1;
1020 }
1021
1022 /* Ensure we won't overflow the size. */
1023 if (size < 0) {
1024 PyErr_SetString(PyExc_SystemError,
1025 "Negative size passed to PyUnicode_New");
1026 return NULL;
1027 }
1028 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1029 return PyErr_NoMemory();
1030
1031 /* Duplicated allocation code from _PyObject_New() instead of a call to
1032 * PyObject_New() so we are able to allocate space for the object and
1033 * it's data buffer.
1034 */
1035 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1036 if (obj == NULL)
1037 return PyErr_NoMemory();
1038 obj = PyObject_INIT(obj, &PyUnicode_Type);
1039 if (obj == NULL)
1040 return NULL;
1041
1042 unicode = (PyCompactUnicodeObject *)obj;
1043 if (is_ascii)
1044 data = ((PyASCIIObject*)obj) + 1;
1045 else
1046 data = unicode + 1;
1047 _PyUnicode_LENGTH(unicode) = size;
1048 _PyUnicode_HASH(unicode) = -1;
1049 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001050 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051 _PyUnicode_STATE(unicode).compact = 1;
1052 _PyUnicode_STATE(unicode).ready = 1;
1053 _PyUnicode_STATE(unicode).ascii = is_ascii;
1054 if (is_ascii) {
1055 ((char*)data)[size] = 0;
1056 _PyUnicode_WSTR(unicode) = NULL;
1057 }
Victor Stinner8f825062012-04-27 13:55:39 +02001058 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059 ((char*)data)[size] = 0;
1060 _PyUnicode_WSTR(unicode) = NULL;
1061 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001063 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001064 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001065 else {
1066 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001067 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001068 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001070 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071 ((Py_UCS4*)data)[size] = 0;
1072 if (is_sharing) {
1073 _PyUnicode_WSTR_LENGTH(unicode) = size;
1074 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1075 }
1076 else {
1077 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1078 _PyUnicode_WSTR(unicode) = NULL;
1079 }
1080 }
Victor Stinner8f825062012-04-27 13:55:39 +02001081#ifdef Py_DEBUG
1082 /* Fill the data with invalid characters to detect bugs earlier.
1083 _PyUnicode_CheckConsistency(str, 1) detects invalid characters,
1084 at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII
1085 and U+FFFFFFFF is an invalid character in Unicode 6.0. */
1086 memset(data, 0xff, size * kind);
1087#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001088 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001089 return obj;
1090}
1091
1092#if SIZEOF_WCHAR_T == 2
1093/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1094 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001095 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001096
1097 This function assumes that unicode can hold one more code point than wstr
1098 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001099static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001101 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001102{
1103 const wchar_t *iter;
1104 Py_UCS4 *ucs4_out;
1105
Victor Stinner910337b2011-10-03 03:20:16 +02001106 assert(unicode != NULL);
1107 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001108 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1109 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1110
1111 for (iter = begin; iter < end; ) {
1112 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1113 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001114 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1115 && (iter+1) < end
1116 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 {
Victor Stinner551ac952011-11-29 22:58:13 +01001118 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 iter += 2;
1120 }
1121 else {
1122 *ucs4_out++ = *iter;
1123 iter++;
1124 }
1125 }
1126 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1127 _PyUnicode_GET_LENGTH(unicode)));
1128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129}
1130#endif
1131
Victor Stinnercd9950f2011-10-02 00:34:53 +02001132static int
Victor Stinner488fa492011-12-12 00:01:39 +01001133unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001134{
Victor Stinner488fa492011-12-12 00:01:39 +01001135 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001136 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001137 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001138 return -1;
1139 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001140 return 0;
1141}
1142
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001143static int
1144_copy_characters(PyObject *to, Py_ssize_t to_start,
1145 PyObject *from, Py_ssize_t from_start,
1146 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001148 unsigned int from_kind, to_kind;
1149 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
Victor Stinneree4544c2012-05-09 22:24:08 +02001151 assert(0 <= how_many);
1152 assert(0 <= from_start);
1153 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001154 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001155 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001156 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001157
Victor Stinnerd3f08822012-05-29 12:57:52 +02001158 assert(PyUnicode_Check(to));
1159 assert(PyUnicode_IS_READY(to));
1160 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1161
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001162 if (how_many == 0)
1163 return 0;
1164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001166 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001168 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169
Victor Stinnerf1852262012-06-16 16:38:26 +02001170#ifdef Py_DEBUG
1171 if (!check_maxchar
1172 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1173 {
1174 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1175 Py_UCS4 ch;
1176 Py_ssize_t i;
1177 for (i=0; i < how_many; i++) {
1178 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1179 assert(ch <= to_maxchar);
1180 }
1181 }
1182#endif
1183
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001184 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001185 if (check_maxchar
1186 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1187 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001188 /* Writing Latin-1 characters into an ASCII string requires to
1189 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001190 Py_UCS4 max_char;
1191 max_char = ucs1lib_find_max_char(from_data,
1192 (Py_UCS1*)from_data + how_many);
1193 if (max_char >= 128)
1194 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001195 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001196 Py_MEMCPY((char*)to_data + to_kind * to_start,
1197 (char*)from_data + from_kind * from_start,
1198 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001199 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001200 else if (from_kind == PyUnicode_1BYTE_KIND
1201 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001202 {
1203 _PyUnicode_CONVERT_BYTES(
1204 Py_UCS1, Py_UCS2,
1205 PyUnicode_1BYTE_DATA(from) + from_start,
1206 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1207 PyUnicode_2BYTE_DATA(to) + to_start
1208 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001209 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001210 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001211 && to_kind == PyUnicode_4BYTE_KIND)
1212 {
1213 _PyUnicode_CONVERT_BYTES(
1214 Py_UCS1, Py_UCS4,
1215 PyUnicode_1BYTE_DATA(from) + from_start,
1216 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1217 PyUnicode_4BYTE_DATA(to) + to_start
1218 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001219 }
1220 else if (from_kind == PyUnicode_2BYTE_KIND
1221 && to_kind == PyUnicode_4BYTE_KIND)
1222 {
1223 _PyUnicode_CONVERT_BYTES(
1224 Py_UCS2, Py_UCS4,
1225 PyUnicode_2BYTE_DATA(from) + from_start,
1226 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1227 PyUnicode_4BYTE_DATA(to) + to_start
1228 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001229 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001230 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001231 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1232
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001233 if (!check_maxchar) {
1234 if (from_kind == PyUnicode_2BYTE_KIND
1235 && to_kind == PyUnicode_1BYTE_KIND)
1236 {
1237 _PyUnicode_CONVERT_BYTES(
1238 Py_UCS2, Py_UCS1,
1239 PyUnicode_2BYTE_DATA(from) + from_start,
1240 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1241 PyUnicode_1BYTE_DATA(to) + to_start
1242 );
1243 }
1244 else if (from_kind == PyUnicode_4BYTE_KIND
1245 && to_kind == PyUnicode_1BYTE_KIND)
1246 {
1247 _PyUnicode_CONVERT_BYTES(
1248 Py_UCS4, Py_UCS1,
1249 PyUnicode_4BYTE_DATA(from) + from_start,
1250 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1251 PyUnicode_1BYTE_DATA(to) + to_start
1252 );
1253 }
1254 else if (from_kind == PyUnicode_4BYTE_KIND
1255 && to_kind == PyUnicode_2BYTE_KIND)
1256 {
1257 _PyUnicode_CONVERT_BYTES(
1258 Py_UCS4, Py_UCS2,
1259 PyUnicode_4BYTE_DATA(from) + from_start,
1260 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1261 PyUnicode_2BYTE_DATA(to) + to_start
1262 );
1263 }
1264 else {
1265 assert(0);
1266 return -1;
1267 }
1268 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001269 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001270 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001271 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001272 Py_ssize_t i;
1273
Victor Stinnera0702ab2011-09-29 14:14:38 +02001274 for (i=0; i < how_many; i++) {
1275 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001276 if (ch > to_maxchar)
1277 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001278 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1279 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001280 }
1281 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001282 return 0;
1283}
1284
Victor Stinnerd3f08822012-05-29 12:57:52 +02001285void
1286_PyUnicode_FastCopyCharacters(
1287 PyObject *to, Py_ssize_t to_start,
1288 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001289{
1290 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1291}
1292
1293Py_ssize_t
1294PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1295 PyObject *from, Py_ssize_t from_start,
1296 Py_ssize_t how_many)
1297{
1298 int err;
1299
1300 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1301 PyErr_BadInternalCall();
1302 return -1;
1303 }
1304
Benjamin Petersonbac79492012-01-14 13:34:47 -05001305 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001306 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001307 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001308 return -1;
1309
Victor Stinnerd3f08822012-05-29 12:57:52 +02001310 if (from_start < 0) {
1311 PyErr_SetString(PyExc_IndexError, "string index out of range");
1312 return -1;
1313 }
1314 if (to_start < 0) {
1315 PyErr_SetString(PyExc_IndexError, "string index out of range");
1316 return -1;
1317 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001318 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1319 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1320 PyErr_Format(PyExc_SystemError,
1321 "Cannot write %zi characters at %zi "
1322 "in a string of %zi characters",
1323 how_many, to_start, PyUnicode_GET_LENGTH(to));
1324 return -1;
1325 }
1326
1327 if (how_many == 0)
1328 return 0;
1329
Victor Stinner488fa492011-12-12 00:01:39 +01001330 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001331 return -1;
1332
1333 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1334 if (err) {
1335 PyErr_Format(PyExc_SystemError,
1336 "Cannot copy %s characters "
1337 "into a string of %s characters",
1338 unicode_kind_name(from),
1339 unicode_kind_name(to));
1340 return -1;
1341 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001342 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343}
1344
Victor Stinner17222162011-09-28 22:15:37 +02001345/* Find the maximum code point and count the number of surrogate pairs so a
1346 correct string length can be computed before converting a string to UCS4.
1347 This function counts single surrogates as a character and not as a pair.
1348
1349 Return 0 on success, or -1 on error. */
1350static int
1351find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1352 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353{
1354 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001355 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356
Victor Stinnerc53be962011-10-02 21:33:54 +02001357 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 *num_surrogates = 0;
1359 *maxchar = 0;
1360
1361 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001363 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1364 && (iter+1) < end
1365 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001366 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001367 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369 iter += 2;
1370 }
1371 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001373 {
1374 ch = *iter;
1375 iter++;
1376 }
1377 if (ch > *maxchar) {
1378 *maxchar = ch;
1379 if (*maxchar > MAX_UNICODE) {
1380 PyErr_Format(PyExc_ValueError,
1381 "character U+%x is not in range [U+0000; U+10ffff]",
1382 ch);
1383 return -1;
1384 }
1385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 }
1387 return 0;
1388}
1389
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001390int
1391_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392{
1393 wchar_t *end;
1394 Py_UCS4 maxchar = 0;
1395 Py_ssize_t num_surrogates;
1396#if SIZEOF_WCHAR_T == 2
1397 Py_ssize_t length_wo_surrogates;
1398#endif
1399
Georg Brandl7597add2011-10-05 16:36:47 +02001400 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001401 strings were created using _PyObject_New() and where no canonical
1402 representation (the str field) has been set yet aka strings
1403 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001404 assert(_PyUnicode_CHECK(unicode));
1405 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001407 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001408 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001409 /* Actually, it should neither be interned nor be anything else: */
1410 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001413 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001414 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416
1417 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001418 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1419 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420 PyErr_NoMemory();
1421 return -1;
1422 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001423 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 _PyUnicode_WSTR(unicode), end,
1425 PyUnicode_1BYTE_DATA(unicode));
1426 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1427 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1428 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1429 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001430 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001431 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001432 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 }
1434 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001435 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001436 _PyUnicode_UTF8(unicode) = NULL;
1437 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 }
1439 PyObject_FREE(_PyUnicode_WSTR(unicode));
1440 _PyUnicode_WSTR(unicode) = NULL;
1441 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1442 }
1443 /* In this case we might have to convert down from 4-byte native
1444 wchar_t to 2-byte unicode. */
1445 else if (maxchar < 65536) {
1446 assert(num_surrogates == 0 &&
1447 "FindMaxCharAndNumSurrogatePairs() messed up");
1448
Victor Stinner506f5922011-09-28 22:34:18 +02001449#if SIZEOF_WCHAR_T == 2
1450 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001451 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001452 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1453 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1454 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001455 _PyUnicode_UTF8(unicode) = NULL;
1456 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001457#else
1458 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001459 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001460 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001461 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001462 PyErr_NoMemory();
1463 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 }
Victor Stinner506f5922011-09-28 22:34:18 +02001465 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1466 _PyUnicode_WSTR(unicode), end,
1467 PyUnicode_2BYTE_DATA(unicode));
1468 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1469 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1470 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001471 _PyUnicode_UTF8(unicode) = NULL;
1472 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001473 PyObject_FREE(_PyUnicode_WSTR(unicode));
1474 _PyUnicode_WSTR(unicode) = NULL;
1475 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1476#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 }
1478 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1479 else {
1480#if SIZEOF_WCHAR_T == 2
1481 /* in case the native representation is 2-bytes, we need to allocate a
1482 new normalized 4-byte version. */
1483 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001484 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1485 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 PyErr_NoMemory();
1487 return -1;
1488 }
1489 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1490 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001491 _PyUnicode_UTF8(unicode) = NULL;
1492 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001493 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1494 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001495 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 PyObject_FREE(_PyUnicode_WSTR(unicode));
1497 _PyUnicode_WSTR(unicode) = NULL;
1498 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1499#else
1500 assert(num_surrogates == 0);
1501
Victor Stinnerc3c74152011-10-02 20:39:55 +02001502 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001503 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001504 _PyUnicode_UTF8(unicode) = NULL;
1505 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001506 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1507#endif
1508 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1509 }
1510 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001511 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 return 0;
1513}
1514
Alexander Belopolsky40018472011-02-26 01:02:56 +00001515static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001516unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001517{
Walter Dörwald16807132007-05-25 13:52:07 +00001518 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001519 case SSTATE_NOT_INTERNED:
1520 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001521
Benjamin Peterson29060642009-01-31 22:14:21 +00001522 case SSTATE_INTERNED_MORTAL:
1523 /* revive dead object temporarily for DelItem */
1524 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001525 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001526 Py_FatalError(
1527 "deletion of interned string failed");
1528 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001529
Benjamin Peterson29060642009-01-31 22:14:21 +00001530 case SSTATE_INTERNED_IMMORTAL:
1531 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001532
Benjamin Peterson29060642009-01-31 22:14:21 +00001533 default:
1534 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001535 }
1536
Victor Stinner03490912011-10-03 23:45:12 +02001537 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001538 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001539 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001540 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001541 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1542 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001544 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001545}
1546
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547#ifdef Py_DEBUG
1548static int
1549unicode_is_singleton(PyObject *unicode)
1550{
1551 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1552 if (unicode == unicode_empty)
1553 return 1;
1554 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1555 {
1556 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1557 if (ch < 256 && unicode_latin1[ch] == unicode)
1558 return 1;
1559 }
1560 return 0;
1561}
1562#endif
1563
Alexander Belopolsky40018472011-02-26 01:02:56 +00001564static int
Victor Stinner488fa492011-12-12 00:01:39 +01001565unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001566{
Victor Stinner488fa492011-12-12 00:01:39 +01001567 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001568 if (Py_REFCNT(unicode) != 1)
1569 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001570 if (_PyUnicode_HASH(unicode) != -1)
1571 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001572 if (PyUnicode_CHECK_INTERNED(unicode))
1573 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001574 if (!PyUnicode_CheckExact(unicode))
1575 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001576#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001577 /* singleton refcount is greater than 1 */
1578 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001579#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 return 1;
1581}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001582
Victor Stinnerfe226c02011-10-03 03:52:20 +02001583static int
1584unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1585{
1586 PyObject *unicode;
1587 Py_ssize_t old_length;
1588
1589 assert(p_unicode != NULL);
1590 unicode = *p_unicode;
1591
1592 assert(unicode != NULL);
1593 assert(PyUnicode_Check(unicode));
1594 assert(0 <= length);
1595
Victor Stinner910337b2011-10-03 03:20:16 +02001596 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001597 old_length = PyUnicode_WSTR_LENGTH(unicode);
1598 else
1599 old_length = PyUnicode_GET_LENGTH(unicode);
1600 if (old_length == length)
1601 return 0;
1602
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001603 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001604 _Py_INCREF_UNICODE_EMPTY();
1605 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001606 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001607 Py_DECREF(*p_unicode);
1608 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001609 return 0;
1610 }
1611
Victor Stinner488fa492011-12-12 00:01:39 +01001612 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001613 PyObject *copy = resize_copy(unicode, length);
1614 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001615 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001616 Py_DECREF(*p_unicode);
1617 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001618 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001619 }
1620
Victor Stinnerfe226c02011-10-03 03:52:20 +02001621 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001622 PyObject *new_unicode = resize_compact(unicode, length);
1623 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001624 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001625 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001627 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001628 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001629}
1630
Alexander Belopolsky40018472011-02-26 01:02:56 +00001631int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001632PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001633{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634 PyObject *unicode;
1635 if (p_unicode == NULL) {
1636 PyErr_BadInternalCall();
1637 return -1;
1638 }
1639 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001640 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641 {
1642 PyErr_BadInternalCall();
1643 return -1;
1644 }
1645 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001646}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001647
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001648static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001649unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1650 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001651{
1652 PyObject *result;
1653 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001654 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001655 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1656 return 0;
1657 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1658 maxchar);
1659 if (result == NULL)
1660 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001661 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001662 Py_DECREF(*p_unicode);
1663 *p_unicode = result;
1664 return 0;
1665}
1666
1667static int
1668unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1669 Py_UCS4 ch)
1670{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001671 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001672 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001673 return -1;
1674 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1675 PyUnicode_DATA(*p_unicode),
1676 (*pos)++, ch);
1677 return 0;
1678}
1679
Victor Stinnerc5166102012-02-22 13:55:02 +01001680/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001681
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001682 WARNING: The function doesn't copy the terminating null character and
1683 doesn't check the maximum character (may write a latin1 character in an
1684 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001685static void
1686unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1687 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001688{
1689 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1690 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001691 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001692
1693 switch (kind) {
1694 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001695 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001696 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001697 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001698 }
1699 case PyUnicode_2BYTE_KIND: {
1700 Py_UCS2 *start = (Py_UCS2 *)data + index;
1701 Py_UCS2 *ucs2 = start;
1702 assert(index <= PyUnicode_GET_LENGTH(unicode));
1703
Victor Stinner184252a2012-06-16 02:57:41 +02001704 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001705 *ucs2 = (Py_UCS2)*str;
1706
1707 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001708 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001709 }
1710 default: {
1711 Py_UCS4 *start = (Py_UCS4 *)data + index;
1712 Py_UCS4 *ucs4 = start;
1713 assert(kind == PyUnicode_4BYTE_KIND);
1714 assert(index <= PyUnicode_GET_LENGTH(unicode));
1715
Victor Stinner184252a2012-06-16 02:57:41 +02001716 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001717 *ucs4 = (Py_UCS4)*str;
1718
1719 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001720 }
1721 }
1722}
1723
1724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001725static PyObject*
1726get_latin1_char(unsigned char ch)
1727{
Victor Stinnera464fc12011-10-02 20:39:30 +02001728 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001730 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001731 if (!unicode)
1732 return NULL;
1733 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001734 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 unicode_latin1[ch] = unicode;
1736 }
1737 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001738 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739}
1740
Alexander Belopolsky40018472011-02-26 01:02:56 +00001741PyObject *
1742PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001743{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001744 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 Py_UCS4 maxchar = 0;
1746 Py_ssize_t num_surrogates;
1747
1748 if (u == NULL)
1749 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001750
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001751 /* If the Unicode data is known at construction time, we can apply
1752 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001755 if (size == 0)
1756 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 /* Single character Unicode objects in the Latin-1 range are
1759 shared when using this constructor */
1760 if (size == 1 && *u < 256)
1761 return get_latin1_char((unsigned char)*u);
1762
1763 /* If not empty and not single character, copy the Unicode data
1764 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001765 if (find_maxchar_surrogates(u, u + size,
1766 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 return NULL;
1768
Victor Stinner8faf8212011-12-08 22:14:11 +01001769 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001770 if (!unicode)
1771 return NULL;
1772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 switch (PyUnicode_KIND(unicode)) {
1774 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001775 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001776 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1777 break;
1778 case PyUnicode_2BYTE_KIND:
1779#if Py_UNICODE_SIZE == 2
1780 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1781#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001782 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1784#endif
1785 break;
1786 case PyUnicode_4BYTE_KIND:
1787#if SIZEOF_WCHAR_T == 2
1788 /* This is the only case which has to process surrogates, thus
1789 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001790 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791#else
1792 assert(num_surrogates == 0);
1793 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1794#endif
1795 break;
1796 default:
1797 assert(0 && "Impossible state");
1798 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001799
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001800 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001801}
1802
Alexander Belopolsky40018472011-02-26 01:02:56 +00001803PyObject *
1804PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001805{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001806 if (size < 0) {
1807 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001808 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001809 return NULL;
1810 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001811 if (u != NULL)
1812 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1813 else
1814 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001815}
1816
Alexander Belopolsky40018472011-02-26 01:02:56 +00001817PyObject *
1818PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001819{
1820 size_t size = strlen(u);
1821 if (size > PY_SSIZE_T_MAX) {
1822 PyErr_SetString(PyExc_OverflowError, "input too long");
1823 return NULL;
1824 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001825 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001826}
1827
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001828PyObject *
1829_PyUnicode_FromId(_Py_Identifier *id)
1830{
1831 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001832 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1833 strlen(id->string),
1834 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001835 if (!id->object)
1836 return NULL;
1837 PyUnicode_InternInPlace(&id->object);
1838 assert(!id->next);
1839 id->next = static_strings;
1840 static_strings = id;
1841 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001842 return id->object;
1843}
1844
1845void
1846_PyUnicode_ClearStaticStrings()
1847{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001848 _Py_Identifier *tmp, *s = static_strings;
1849 while (s) {
1850 Py_DECREF(s->object);
1851 s->object = NULL;
1852 tmp = s->next;
1853 s->next = NULL;
1854 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001855 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001856 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001857}
1858
Benjamin Peterson0df54292012-03-26 14:50:32 -04001859/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001860
Victor Stinnerd3f08822012-05-29 12:57:52 +02001861PyObject*
1862_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001863{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001864 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001865 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001866 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001867#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001868 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001869#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001870 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001871 }
Victor Stinner785938e2011-12-11 20:09:03 +01001872 unicode = PyUnicode_New(size, 127);
1873 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001874 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001875 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1876 assert(_PyUnicode_CheckConsistency(unicode, 1));
1877 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001878}
1879
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001880static Py_UCS4
1881kind_maxchar_limit(unsigned int kind)
1882{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001883 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001884 case PyUnicode_1BYTE_KIND:
1885 return 0x80;
1886 case PyUnicode_2BYTE_KIND:
1887 return 0x100;
1888 case PyUnicode_4BYTE_KIND:
1889 return 0x10000;
1890 default:
1891 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001892 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001893 }
1894}
1895
Victor Stinnere6abb482012-05-02 01:15:40 +02001896Py_LOCAL_INLINE(Py_UCS4)
1897align_maxchar(Py_UCS4 maxchar)
1898{
1899 if (maxchar <= 127)
1900 return 127;
1901 else if (maxchar <= 255)
1902 return 255;
1903 else if (maxchar <= 65535)
1904 return 65535;
1905 else
1906 return MAX_UNICODE;
1907}
1908
Victor Stinner702c7342011-10-05 13:50:52 +02001909static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001910_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001911{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001913 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001914
Serhiy Storchaka678db842013-01-26 12:16:36 +02001915 if (size == 0)
1916 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001917 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001918 if (size == 1)
1919 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001920
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001921 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001922 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001923 if (!res)
1924 return NULL;
1925 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001926 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001927 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001928}
1929
Victor Stinnere57b1c02011-09-28 22:20:48 +02001930static PyObject*
1931_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001932{
1933 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001934 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001935
Serhiy Storchaka678db842013-01-26 12:16:36 +02001936 if (size == 0)
1937 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001938 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001939 if (size == 1) {
1940 Py_UCS4 ch = u[0];
1941 if (ch < 256)
1942 return get_latin1_char((unsigned char)ch);
1943
1944 res = PyUnicode_New(1, ch);
1945 if (res == NULL)
1946 return NULL;
1947 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1948 assert(_PyUnicode_CheckConsistency(res, 1));
1949 return res;
1950 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001951
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001952 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001953 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 if (!res)
1955 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001956 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001958 else {
1959 _PyUnicode_CONVERT_BYTES(
1960 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1961 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001962 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001963 return res;
1964}
1965
Victor Stinnere57b1c02011-09-28 22:20:48 +02001966static PyObject*
1967_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968{
1969 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001970 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001971
Serhiy Storchaka678db842013-01-26 12:16:36 +02001972 if (size == 0)
1973 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001974 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001975 if (size == 1) {
1976 Py_UCS4 ch = u[0];
1977 if (ch < 256)
1978 return get_latin1_char((unsigned char)ch);
1979
1980 res = PyUnicode_New(1, ch);
1981 if (res == NULL)
1982 return NULL;
1983 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1984 assert(_PyUnicode_CheckConsistency(res, 1));
1985 return res;
1986 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001987
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001988 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001989 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990 if (!res)
1991 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001992 if (max_char < 256)
1993 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1994 PyUnicode_1BYTE_DATA(res));
1995 else if (max_char < 0x10000)
1996 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1997 PyUnicode_2BYTE_DATA(res));
1998 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002000 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 return res;
2002}
2003
2004PyObject*
2005PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2006{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002007 if (size < 0) {
2008 PyErr_SetString(PyExc_ValueError, "size must be positive");
2009 return NULL;
2010 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002011 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002013 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002015 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002017 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002018 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002019 PyErr_SetString(PyExc_SystemError, "invalid kind");
2020 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022}
2023
Victor Stinnerece58de2012-04-23 23:36:38 +02002024Py_UCS4
2025_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2026{
2027 enum PyUnicode_Kind kind;
2028 void *startptr, *endptr;
2029
2030 assert(PyUnicode_IS_READY(unicode));
2031 assert(0 <= start);
2032 assert(end <= PyUnicode_GET_LENGTH(unicode));
2033 assert(start <= end);
2034
2035 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2036 return PyUnicode_MAX_CHAR_VALUE(unicode);
2037
2038 if (start == end)
2039 return 127;
2040
Victor Stinner94d558b2012-04-27 22:26:58 +02002041 if (PyUnicode_IS_ASCII(unicode))
2042 return 127;
2043
Victor Stinnerece58de2012-04-23 23:36:38 +02002044 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002045 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002046 endptr = (char *)startptr + end * kind;
2047 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002048 switch(kind) {
2049 case PyUnicode_1BYTE_KIND:
2050 return ucs1lib_find_max_char(startptr, endptr);
2051 case PyUnicode_2BYTE_KIND:
2052 return ucs2lib_find_max_char(startptr, endptr);
2053 case PyUnicode_4BYTE_KIND:
2054 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002055 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002056 assert(0);
2057 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002058 }
2059}
2060
Victor Stinner25a4b292011-10-06 12:31:55 +02002061/* Ensure that a string uses the most efficient storage, if it is not the
2062 case: create a new string with of the right kind. Write NULL into *p_unicode
2063 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002064static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002065unicode_adjust_maxchar(PyObject **p_unicode)
2066{
2067 PyObject *unicode, *copy;
2068 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002069 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002070 unsigned int kind;
2071
2072 assert(p_unicode != NULL);
2073 unicode = *p_unicode;
2074 assert(PyUnicode_IS_READY(unicode));
2075 if (PyUnicode_IS_ASCII(unicode))
2076 return;
2077
2078 len = PyUnicode_GET_LENGTH(unicode);
2079 kind = PyUnicode_KIND(unicode);
2080 if (kind == PyUnicode_1BYTE_KIND) {
2081 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002082 max_char = ucs1lib_find_max_char(u, u + len);
2083 if (max_char >= 128)
2084 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002085 }
2086 else if (kind == PyUnicode_2BYTE_KIND) {
2087 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002088 max_char = ucs2lib_find_max_char(u, u + len);
2089 if (max_char >= 256)
2090 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002091 }
2092 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002093 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002094 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002095 max_char = ucs4lib_find_max_char(u, u + len);
2096 if (max_char >= 0x10000)
2097 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002098 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002099 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002100 if (copy != NULL)
2101 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002102 Py_DECREF(unicode);
2103 *p_unicode = copy;
2104}
2105
Victor Stinner034f6cf2011-09-30 02:26:44 +02002106PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002107_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002108{
Victor Stinner87af4f22011-11-21 23:03:47 +01002109 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002110 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002111
Victor Stinner034f6cf2011-09-30 02:26:44 +02002112 if (!PyUnicode_Check(unicode)) {
2113 PyErr_BadInternalCall();
2114 return NULL;
2115 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002116 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002117 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002118
Victor Stinner87af4f22011-11-21 23:03:47 +01002119 length = PyUnicode_GET_LENGTH(unicode);
2120 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002121 if (!copy)
2122 return NULL;
2123 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2124
Victor Stinner87af4f22011-11-21 23:03:47 +01002125 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2126 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002127 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002128 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002129}
2130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131
Victor Stinnerbc603d12011-10-02 01:00:40 +02002132/* Widen Unicode objects to larger buffers. Don't write terminating null
2133 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002134
2135void*
2136_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2137{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002138 Py_ssize_t len;
2139 void *result;
2140 unsigned int skind;
2141
Benjamin Petersonbac79492012-01-14 13:34:47 -05002142 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002143 return NULL;
2144
2145 len = PyUnicode_GET_LENGTH(s);
2146 skind = PyUnicode_KIND(s);
2147 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002148 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 return NULL;
2150 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002151 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002152 case PyUnicode_2BYTE_KIND:
2153 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2154 if (!result)
2155 return PyErr_NoMemory();
2156 assert(skind == PyUnicode_1BYTE_KIND);
2157 _PyUnicode_CONVERT_BYTES(
2158 Py_UCS1, Py_UCS2,
2159 PyUnicode_1BYTE_DATA(s),
2160 PyUnicode_1BYTE_DATA(s) + len,
2161 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002163 case PyUnicode_4BYTE_KIND:
2164 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2165 if (!result)
2166 return PyErr_NoMemory();
2167 if (skind == PyUnicode_2BYTE_KIND) {
2168 _PyUnicode_CONVERT_BYTES(
2169 Py_UCS2, Py_UCS4,
2170 PyUnicode_2BYTE_DATA(s),
2171 PyUnicode_2BYTE_DATA(s) + len,
2172 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 else {
2175 assert(skind == PyUnicode_1BYTE_KIND);
2176 _PyUnicode_CONVERT_BYTES(
2177 Py_UCS1, Py_UCS4,
2178 PyUnicode_1BYTE_DATA(s),
2179 PyUnicode_1BYTE_DATA(s) + len,
2180 result);
2181 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002182 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002183 default:
2184 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 }
Victor Stinner01698042011-10-04 00:04:26 +02002186 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002187 return NULL;
2188}
2189
2190static Py_UCS4*
2191as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2192 int copy_null)
2193{
2194 int kind;
2195 void *data;
2196 Py_ssize_t len, targetlen;
2197 if (PyUnicode_READY(string) == -1)
2198 return NULL;
2199 kind = PyUnicode_KIND(string);
2200 data = PyUnicode_DATA(string);
2201 len = PyUnicode_GET_LENGTH(string);
2202 targetlen = len;
2203 if (copy_null)
2204 targetlen++;
2205 if (!target) {
2206 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2207 PyErr_NoMemory();
2208 return NULL;
2209 }
2210 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2211 if (!target) {
2212 PyErr_NoMemory();
2213 return NULL;
2214 }
2215 }
2216 else {
2217 if (targetsize < targetlen) {
2218 PyErr_Format(PyExc_SystemError,
2219 "string is longer than the buffer");
2220 if (copy_null && 0 < targetsize)
2221 target[0] = 0;
2222 return NULL;
2223 }
2224 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002225 if (kind == PyUnicode_1BYTE_KIND) {
2226 Py_UCS1 *start = (Py_UCS1 *) data;
2227 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002228 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002229 else if (kind == PyUnicode_2BYTE_KIND) {
2230 Py_UCS2 *start = (Py_UCS2 *) data;
2231 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2232 }
2233 else {
2234 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 if (copy_null)
2238 target[len] = 0;
2239 return target;
2240}
2241
2242Py_UCS4*
2243PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2244 int copy_null)
2245{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002246 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 PyErr_BadInternalCall();
2248 return NULL;
2249 }
2250 return as_ucs4(string, target, targetsize, copy_null);
2251}
2252
2253Py_UCS4*
2254PyUnicode_AsUCS4Copy(PyObject *string)
2255{
2256 return as_ucs4(string, NULL, 0, 1);
2257}
2258
2259#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002260
Alexander Belopolsky40018472011-02-26 01:02:56 +00002261PyObject *
2262PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002263{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002264 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002265 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002266 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002267 PyErr_BadInternalCall();
2268 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002269 }
2270
Martin v. Löwis790465f2008-04-05 20:41:37 +00002271 if (size == -1) {
2272 size = wcslen(w);
2273 }
2274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002276}
2277
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002279
Walter Dörwald346737f2007-05-31 10:44:43 +00002280static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002281makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2282 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002283{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002284 *fmt++ = '%';
2285 if (width) {
2286 if (zeropad)
2287 *fmt++ = '0';
2288 fmt += sprintf(fmt, "%d", width);
2289 }
2290 if (precision)
2291 fmt += sprintf(fmt, ".%d", precision);
2292 if (longflag)
2293 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002294 else if (longlongflag) {
2295 /* longlongflag should only ever be nonzero on machines with
2296 HAVE_LONG_LONG defined */
2297#ifdef HAVE_LONG_LONG
2298 char *f = PY_FORMAT_LONG_LONG;
2299 while (*f)
2300 *fmt++ = *f++;
2301#else
2302 /* we shouldn't ever get here */
2303 assert(0);
2304 *fmt++ = 'l';
2305#endif
2306 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002307 else if (size_tflag) {
2308 char *f = PY_FORMAT_SIZE_T;
2309 while (*f)
2310 *fmt++ = *f++;
2311 }
2312 *fmt++ = c;
2313 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002314}
2315
Victor Stinner96865452011-03-01 23:44:09 +00002316/* helper for PyUnicode_FromFormatV() */
2317
2318static const char*
2319parse_format_flags(const char *f,
2320 int *p_width, int *p_precision,
2321 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2322{
2323 int width, precision, longflag, longlongflag, size_tflag;
2324
2325 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2326 f++;
2327 width = 0;
2328 while (Py_ISDIGIT((unsigned)*f))
2329 width = (width*10) + *f++ - '0';
2330 precision = 0;
2331 if (*f == '.') {
2332 f++;
2333 while (Py_ISDIGIT((unsigned)*f))
2334 precision = (precision*10) + *f++ - '0';
2335 if (*f == '%') {
2336 /* "%.3%s" => f points to "3" */
2337 f--;
2338 }
2339 }
2340 if (*f == '\0') {
2341 /* bogus format "%.1" => go backward, f points to "1" */
2342 f--;
2343 }
2344 if (p_width != NULL)
2345 *p_width = width;
2346 if (p_precision != NULL)
2347 *p_precision = precision;
2348
2349 /* Handle %ld, %lu, %lld and %llu. */
2350 longflag = 0;
2351 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002352 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002353
2354 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002355 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002356 longflag = 1;
2357 ++f;
2358 }
2359#ifdef HAVE_LONG_LONG
2360 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002361 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002362 longlongflag = 1;
2363 f += 2;
2364 }
2365#endif
2366 }
2367 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002368 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002369 size_tflag = 1;
2370 ++f;
2371 }
2372 if (p_longflag != NULL)
2373 *p_longflag = longflag;
2374 if (p_longlongflag != NULL)
2375 *p_longlongflag = longlongflag;
2376 if (p_size_tflag != NULL)
2377 *p_size_tflag = size_tflag;
2378 return f;
2379}
2380
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002381/* maximum number of characters required for output of %ld. 21 characters
2382 allows for 64-bit integers (in decimal) and an optional sign. */
2383#define MAX_LONG_CHARS 21
2384/* maximum number of characters required for output of %lld.
2385 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2386 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2387#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2388
Walter Dörwaldd2034312007-05-18 16:29:38 +00002389PyObject *
2390PyUnicode_FromFormatV(const char *format, va_list vargs)
2391{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002392 va_list count;
2393 Py_ssize_t callcount = 0;
2394 PyObject **callresults = NULL;
2395 PyObject **callresult = NULL;
2396 Py_ssize_t n = 0;
2397 int width = 0;
2398 int precision = 0;
2399 int zeropad;
2400 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002401 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002402 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002403 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002404 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2405 Py_UCS4 argmaxchar;
2406 Py_ssize_t numbersize = 0;
2407 char *numberresults = NULL;
2408 char *numberresult = NULL;
2409 Py_ssize_t i;
2410 int kind;
2411 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002412
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002413 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002414 /* step 1: count the number of %S/%R/%A/%s format specifications
2415 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2416 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002418 * also estimate a upper bound for all the number formats in the string,
2419 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002421 for (f = format; *f; f++) {
2422 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002423 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002424 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2425 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2426 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2427 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002430#ifdef HAVE_LONG_LONG
2431 if (longlongflag) {
2432 if (width < MAX_LONG_LONG_CHARS)
2433 width = MAX_LONG_LONG_CHARS;
2434 }
2435 else
2436#endif
2437 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2438 including sign. Decimal takes the most space. This
2439 isn't enough for octal. If a width is specified we
2440 need more (which we allocate later). */
2441 if (width < MAX_LONG_CHARS)
2442 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002443
2444 /* account for the size + '\0' to separate numbers
2445 inside of the numberresults buffer */
2446 numbersize += (width + 1);
2447 }
2448 }
2449 else if ((unsigned char)*f > 127) {
2450 PyErr_Format(PyExc_ValueError,
2451 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2452 "string, got a non-ASCII byte: 0x%02x",
2453 (unsigned char)*f);
2454 return NULL;
2455 }
2456 }
2457 /* step 2: allocate memory for the results of
2458 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2459 if (callcount) {
2460 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2461 if (!callresults) {
2462 PyErr_NoMemory();
2463 return NULL;
2464 }
2465 callresult = callresults;
2466 }
2467 /* step 2.5: allocate memory for the results of formating numbers */
2468 if (numbersize) {
2469 numberresults = PyObject_Malloc(numbersize);
2470 if (!numberresults) {
2471 PyErr_NoMemory();
2472 goto fail;
2473 }
2474 numberresult = numberresults;
2475 }
2476
2477 /* step 3: format numbers and figure out how large a buffer we need */
2478 for (f = format; *f; f++) {
2479 if (*f == '%') {
2480 const char* p;
2481 int longflag;
2482 int longlongflag;
2483 int size_tflag;
2484 int numprinted;
2485
2486 p = f;
2487 zeropad = (f[1] == '0');
2488 f = parse_format_flags(f, &width, &precision,
2489 &longflag, &longlongflag, &size_tflag);
2490 switch (*f) {
2491 case 'c':
2492 {
2493 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002494 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002495 n++;
2496 break;
2497 }
2498 case '%':
2499 n++;
2500 break;
2501 case 'i':
2502 case 'd':
2503 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2504 width, precision, *f);
2505 if (longflag)
2506 numprinted = sprintf(numberresult, fmt,
2507 va_arg(count, long));
2508#ifdef HAVE_LONG_LONG
2509 else if (longlongflag)
2510 numprinted = sprintf(numberresult, fmt,
2511 va_arg(count, PY_LONG_LONG));
2512#endif
2513 else if (size_tflag)
2514 numprinted = sprintf(numberresult, fmt,
2515 va_arg(count, Py_ssize_t));
2516 else
2517 numprinted = sprintf(numberresult, fmt,
2518 va_arg(count, int));
2519 n += numprinted;
2520 /* advance by +1 to skip over the '\0' */
2521 numberresult += (numprinted + 1);
2522 assert(*(numberresult - 1) == '\0');
2523 assert(*(numberresult - 2) != '\0');
2524 assert(numprinted >= 0);
2525 assert(numberresult <= numberresults + numbersize);
2526 break;
2527 case 'u':
2528 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2529 width, precision, 'u');
2530 if (longflag)
2531 numprinted = sprintf(numberresult, fmt,
2532 va_arg(count, unsigned long));
2533#ifdef HAVE_LONG_LONG
2534 else if (longlongflag)
2535 numprinted = sprintf(numberresult, fmt,
2536 va_arg(count, unsigned PY_LONG_LONG));
2537#endif
2538 else if (size_tflag)
2539 numprinted = sprintf(numberresult, fmt,
2540 va_arg(count, size_t));
2541 else
2542 numprinted = sprintf(numberresult, fmt,
2543 va_arg(count, unsigned int));
2544 n += numprinted;
2545 numberresult += (numprinted + 1);
2546 assert(*(numberresult - 1) == '\0');
2547 assert(*(numberresult - 2) != '\0');
2548 assert(numprinted >= 0);
2549 assert(numberresult <= numberresults + numbersize);
2550 break;
2551 case 'x':
2552 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2553 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2554 n += numprinted;
2555 numberresult += (numprinted + 1);
2556 assert(*(numberresult - 1) == '\0');
2557 assert(*(numberresult - 2) != '\0');
2558 assert(numprinted >= 0);
2559 assert(numberresult <= numberresults + numbersize);
2560 break;
2561 case 'p':
2562 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2563 /* %p is ill-defined: ensure leading 0x. */
2564 if (numberresult[1] == 'X')
2565 numberresult[1] = 'x';
2566 else if (numberresult[1] != 'x') {
2567 memmove(numberresult + 2, numberresult,
2568 strlen(numberresult) + 1);
2569 numberresult[0] = '0';
2570 numberresult[1] = 'x';
2571 numprinted += 2;
2572 }
2573 n += numprinted;
2574 numberresult += (numprinted + 1);
2575 assert(*(numberresult - 1) == '\0');
2576 assert(*(numberresult - 2) != '\0');
2577 assert(numprinted >= 0);
2578 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002579 break;
2580 case 's':
2581 {
2582 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002583 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002584 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002585 if (!str)
2586 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 /* since PyUnicode_DecodeUTF8 returns already flexible
2588 unicode objects, there is no need to call ready on them */
2589 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002590 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002592 /* Remember the str and switch to the next slot */
2593 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 break;
2595 }
2596 case 'U':
2597 {
2598 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002599 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 if (PyUnicode_READY(obj) == -1)
2601 goto fail;
2602 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002603 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 break;
2606 }
2607 case 'V':
2608 {
2609 PyObject *obj = va_arg(count, PyObject *);
2610 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002611 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002613 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002614 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002615 if (PyUnicode_READY(obj) == -1)
2616 goto fail;
2617 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002618 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002620 *callresult++ = NULL;
2621 }
2622 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002623 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002624 if (!str_obj)
2625 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002626 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002627 Py_DECREF(str_obj);
2628 goto fail;
2629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002630 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002631 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002633 *callresult++ = str_obj;
2634 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 break;
2636 }
2637 case 'S':
2638 {
2639 PyObject *obj = va_arg(count, PyObject *);
2640 PyObject *str;
2641 assert(obj);
2642 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002643 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002644 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002645 if (PyUnicode_READY(str) == -1) {
2646 Py_DECREF(str);
2647 goto fail;
2648 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002649 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002650 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002652 /* Remember the str and switch to the next slot */
2653 *callresult++ = str;
2654 break;
2655 }
2656 case 'R':
2657 {
2658 PyObject *obj = va_arg(count, PyObject *);
2659 PyObject *repr;
2660 assert(obj);
2661 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002662 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002663 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002664 if (PyUnicode_READY(repr) == -1) {
2665 Py_DECREF(repr);
2666 goto fail;
2667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002669 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002670 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002671 /* Remember the repr and switch to the next slot */
2672 *callresult++ = repr;
2673 break;
2674 }
2675 case 'A':
2676 {
2677 PyObject *obj = va_arg(count, PyObject *);
2678 PyObject *ascii;
2679 assert(obj);
2680 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002681 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002682 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002683 if (PyUnicode_READY(ascii) == -1) {
2684 Py_DECREF(ascii);
2685 goto fail;
2686 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002688 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002690 /* Remember the repr and switch to the next slot */
2691 *callresult++ = ascii;
2692 break;
2693 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 default:
2695 /* if we stumble upon an unknown
2696 formatting code, copy the rest of
2697 the format string to the output
2698 string. (we cannot just skip the
2699 code, since there's no way to know
2700 what's in the argument list) */
2701 n += strlen(p);
2702 goto expand;
2703 }
2704 } else
2705 n++;
2706 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002707 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002708 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002710 we don't have to resize the string.
2711 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002712 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002713 if (!string)
2714 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002715 kind = PyUnicode_KIND(string);
2716 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002717 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002718 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002721 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002722 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002723
2724 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002725 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2726 /* checking for == because the last argument could be a empty
2727 string, which causes i to point to end, the assert at the end of
2728 the loop */
2729 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002730
Benjamin Peterson14339b62009-01-31 16:36:08 +00002731 switch (*f) {
2732 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002733 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 const int ordinal = va_arg(vargs, int);
2735 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002736 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002737 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002738 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002739 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002740 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002743 {
Victor Stinner184252a2012-06-16 02:57:41 +02002744 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 /* unused, since we already have the result */
2746 if (*f == 'p')
2747 (void) va_arg(vargs, void *);
2748 else
2749 (void) va_arg(vargs, int);
2750 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002751 len = strlen(numberresult);
2752 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002753 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002754 i += len;
2755 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002756 assert(*numberresult == '\0');
2757 numberresult++;
2758 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002759 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002760 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 case 's':
2762 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002763 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002765 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002766 size = PyUnicode_GET_LENGTH(*callresult);
2767 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002768 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002769 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002770 /* We're done with the unicode()/repr() => forget it */
2771 Py_DECREF(*callresult);
2772 /* switch to next unicode()/repr() result */
2773 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002774 break;
2775 }
2776 case 'U':
2777 {
2778 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002779 Py_ssize_t size;
2780 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2781 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002782 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002784 break;
2785 }
2786 case 'V':
2787 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002788 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002789 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002790 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002791 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 size = PyUnicode_GET_LENGTH(obj);
2793 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002794 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002795 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002796 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002797 size = PyUnicode_GET_LENGTH(*callresult);
2798 assert(PyUnicode_KIND(*callresult) <=
2799 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002800 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002801 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002802 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002803 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002804 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002805 break;
2806 }
2807 case 'S':
2808 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002809 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002810 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002811 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002812 /* unused, since we already have the result */
2813 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002814 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002815 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002816 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002817 /* We're done with the unicode()/repr() => forget it */
2818 Py_DECREF(*callresult);
2819 /* switch to next unicode()/repr() result */
2820 ++callresult;
2821 break;
2822 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002823 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002824 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002825 break;
2826 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002827 {
2828 Py_ssize_t len = strlen(p);
2829 unicode_write_cstr(string, i, p, len);
2830 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002831 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002832 goto end;
2833 }
Victor Stinner184252a2012-06-16 02:57:41 +02002834 }
Victor Stinner1205f272010-09-11 00:54:47 +00002835 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002836 else {
2837 assert(i < PyUnicode_GET_LENGTH(string));
2838 PyUnicode_WRITE(kind, data, i++, *f);
2839 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002842
Benjamin Peterson29060642009-01-31 22:14:21 +00002843 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002844 if (callresults)
2845 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002846 if (numberresults)
2847 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002848 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002849 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002850 if (callresults) {
2851 PyObject **callresult2 = callresults;
2852 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002853 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002854 ++callresult2;
2855 }
2856 PyObject_Free(callresults);
2857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002858 if (numberresults)
2859 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002860 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002861}
2862
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863PyObject *
2864PyUnicode_FromFormat(const char *format, ...)
2865{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002866 PyObject* ret;
2867 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002868
2869#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002870 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002871#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002872 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002873#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002874 ret = PyUnicode_FromFormatV(format, vargs);
2875 va_end(vargs);
2876 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002877}
2878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002879#ifdef HAVE_WCHAR_H
2880
Victor Stinner5593d8a2010-10-02 11:11:27 +00002881/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2882 convert a Unicode object to a wide character string.
2883
Victor Stinnerd88d9832011-09-06 02:00:05 +02002884 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002885 character) required to convert the unicode object. Ignore size argument.
2886
Victor Stinnerd88d9832011-09-06 02:00:05 +02002887 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002888 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002889 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002890static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002891unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002892 wchar_t *w,
2893 Py_ssize_t size)
2894{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002895 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002896 const wchar_t *wstr;
2897
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002898 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002899 if (wstr == NULL)
2900 return -1;
2901
Victor Stinner5593d8a2010-10-02 11:11:27 +00002902 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002903 if (size > res)
2904 size = res + 1;
2905 else
2906 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002907 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002908 return res;
2909 }
2910 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002911 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002912}
2913
2914Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002915PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002916 wchar_t *w,
2917 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002918{
2919 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 PyErr_BadInternalCall();
2921 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002923 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002924}
2925
Victor Stinner137c34c2010-09-29 10:25:54 +00002926wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002927PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002928 Py_ssize_t *size)
2929{
2930 wchar_t* buffer;
2931 Py_ssize_t buflen;
2932
2933 if (unicode == NULL) {
2934 PyErr_BadInternalCall();
2935 return NULL;
2936 }
2937
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002938 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002939 if (buflen == -1)
2940 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002942 PyErr_NoMemory();
2943 return NULL;
2944 }
2945
Victor Stinner137c34c2010-09-29 10:25:54 +00002946 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2947 if (buffer == NULL) {
2948 PyErr_NoMemory();
2949 return NULL;
2950 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002951 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002952 if (buflen == -1) {
2953 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002954 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002955 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002956 if (size != NULL)
2957 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002958 return buffer;
2959}
2960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002961#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002962
Alexander Belopolsky40018472011-02-26 01:02:56 +00002963PyObject *
2964PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002966 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002967 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002968 PyErr_SetString(PyExc_ValueError,
2969 "chr() arg not in range(0x110000)");
2970 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002971 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002973 if (ordinal < 256)
2974 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002976 v = PyUnicode_New(1, ordinal);
2977 if (v == NULL)
2978 return NULL;
2979 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002980 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002981 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002982}
2983
Alexander Belopolsky40018472011-02-26 01:02:56 +00002984PyObject *
2985PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002986{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002987 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002988 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002989 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002990 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002991 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002992 Py_INCREF(obj);
2993 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002994 }
2995 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002996 /* For a Unicode subtype that's not a Unicode object,
2997 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002998 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002999 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003000 PyErr_Format(PyExc_TypeError,
3001 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003002 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003003 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003004}
3005
Alexander Belopolsky40018472011-02-26 01:02:56 +00003006PyObject *
3007PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003008 const char *encoding,
3009 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003010{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003011 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003012 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003013
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003015 PyErr_BadInternalCall();
3016 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003018
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003019 /* Decoding bytes objects is the most common case and should be fast */
3020 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003021 if (PyBytes_GET_SIZE(obj) == 0)
3022 _Py_RETURN_UNICODE_EMPTY();
3023 v = PyUnicode_Decode(
3024 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3025 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003026 return v;
3027 }
3028
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003029 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 PyErr_SetString(PyExc_TypeError,
3031 "decoding str is not supported");
3032 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003033 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003034
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003035 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3036 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3037 PyErr_Format(PyExc_TypeError,
3038 "coercing to str: need bytes, bytearray "
3039 "or buffer-like object, %.80s found",
3040 Py_TYPE(obj)->tp_name);
3041 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003042 }
Tim Petersced69f82003-09-16 20:30:58 +00003043
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003044 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003045 PyBuffer_Release(&buffer);
3046 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003047 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003048
Serhiy Storchaka05997252013-01-26 12:14:02 +02003049 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003050 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003051 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052}
3053
Victor Stinner600d3be2010-06-10 12:00:55 +00003054/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003055 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3056 1 on success. */
Victor Stinner20b654a2013-01-03 01:08:58 +01003057int
3058_Py_normalize_encoding(const char *encoding,
Victor Stinner37296e82010-06-10 13:36:23 +00003059 char *lower,
3060 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003061{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003062 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003063 char *l;
3064 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003065
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003066 if (encoding == NULL) {
3067 strcpy(lower, "utf-8");
3068 return 1;
3069 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003070 e = encoding;
3071 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003072 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003073 while (*e) {
3074 if (l == l_end)
3075 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003076 if (Py_ISUPPER(*e)) {
3077 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003078 }
3079 else if (*e == '_') {
3080 *l++ = '-';
3081 e++;
3082 }
3083 else {
3084 *l++ = *e++;
3085 }
3086 }
3087 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003088 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003089}
3090
Alexander Belopolsky40018472011-02-26 01:02:56 +00003091PyObject *
3092PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003093 Py_ssize_t size,
3094 const char *encoding,
3095 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003096{
3097 PyObject *buffer = NULL, *unicode;
3098 Py_buffer info;
3099 char lower[11]; /* Enough for any encoding shortcut */
3100
Fred Drakee4315f52000-05-09 19:53:39 +00003101 /* Shortcuts for common default encodings */
Victor Stinner20b654a2013-01-03 01:08:58 +01003102 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003103 if ((strcmp(lower, "utf-8") == 0) ||
3104 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003105 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003106 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003107 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003108 (strcmp(lower, "iso-8859-1") == 0))
3109 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003110#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003111 else if (strcmp(lower, "mbcs") == 0)
3112 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003113#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003114 else if (strcmp(lower, "ascii") == 0)
3115 return PyUnicode_DecodeASCII(s, size, errors);
3116 else if (strcmp(lower, "utf-16") == 0)
3117 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3118 else if (strcmp(lower, "utf-32") == 0)
3119 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3120 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121
3122 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003123 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003124 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003125 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003126 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 if (buffer == NULL)
3128 goto onError;
3129 unicode = PyCodec_Decode(buffer, encoding, errors);
3130 if (unicode == NULL)
3131 goto onError;
3132 if (!PyUnicode_Check(unicode)) {
3133 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003134 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003135 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003136 Py_DECREF(unicode);
3137 goto onError;
3138 }
3139 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003140 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003141
Benjamin Peterson29060642009-01-31 22:14:21 +00003142 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003143 Py_XDECREF(buffer);
3144 return NULL;
3145}
3146
Alexander Belopolsky40018472011-02-26 01:02:56 +00003147PyObject *
3148PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003149 const char *encoding,
3150 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003151{
3152 PyObject *v;
3153
3154 if (!PyUnicode_Check(unicode)) {
3155 PyErr_BadArgument();
3156 goto onError;
3157 }
3158
3159 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003160 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003161
3162 /* Decode via the codec registry */
3163 v = PyCodec_Decode(unicode, encoding, errors);
3164 if (v == NULL)
3165 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003166 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003167
Benjamin Peterson29060642009-01-31 22:14:21 +00003168 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003169 return NULL;
3170}
3171
Alexander Belopolsky40018472011-02-26 01:02:56 +00003172PyObject *
3173PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003174 const char *encoding,
3175 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003176{
3177 PyObject *v;
3178
3179 if (!PyUnicode_Check(unicode)) {
3180 PyErr_BadArgument();
3181 goto onError;
3182 }
3183
3184 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003185 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003186
3187 /* Decode via the codec registry */
3188 v = PyCodec_Decode(unicode, encoding, errors);
3189 if (v == NULL)
3190 goto onError;
3191 if (!PyUnicode_Check(v)) {
3192 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003193 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003194 Py_TYPE(v)->tp_name);
3195 Py_DECREF(v);
3196 goto onError;
3197 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003198 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003199
Benjamin Peterson29060642009-01-31 22:14:21 +00003200 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003201 return NULL;
3202}
3203
Alexander Belopolsky40018472011-02-26 01:02:56 +00003204PyObject *
3205PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003206 Py_ssize_t size,
3207 const char *encoding,
3208 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209{
3210 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003211
Guido van Rossumd57fd912000-03-10 22:53:23 +00003212 unicode = PyUnicode_FromUnicode(s, size);
3213 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003215 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3216 Py_DECREF(unicode);
3217 return v;
3218}
3219
Alexander Belopolsky40018472011-02-26 01:02:56 +00003220PyObject *
3221PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003222 const char *encoding,
3223 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003224{
3225 PyObject *v;
3226
3227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
3229 goto onError;
3230 }
3231
3232 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003233 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003234
3235 /* Encode via the codec registry */
3236 v = PyCodec_Encode(unicode, encoding, errors);
3237 if (v == NULL)
3238 goto onError;
3239 return v;
3240
Benjamin Peterson29060642009-01-31 22:14:21 +00003241 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242 return NULL;
3243}
3244
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003245static size_t
3246wcstombs_errorpos(const wchar_t *wstr)
3247{
3248 size_t len;
3249#if SIZEOF_WCHAR_T == 2
3250 wchar_t buf[3];
3251#else
3252 wchar_t buf[2];
3253#endif
3254 char outbuf[MB_LEN_MAX];
3255 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003256
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003257#if SIZEOF_WCHAR_T == 2
3258 buf[2] = 0;
3259#else
3260 buf[1] = 0;
3261#endif
3262 start = wstr;
3263 while (*wstr != L'\0')
3264 {
3265 previous = wstr;
3266#if SIZEOF_WCHAR_T == 2
3267 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3268 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3269 {
3270 buf[0] = wstr[0];
3271 buf[1] = wstr[1];
3272 wstr += 2;
3273 }
3274 else {
3275 buf[0] = *wstr;
3276 buf[1] = 0;
3277 wstr++;
3278 }
3279#else
3280 buf[0] = *wstr;
3281 wstr++;
3282#endif
3283 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003284 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003285 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003286 }
3287
3288 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003289 return 0;
3290}
3291
Victor Stinner1b579672011-12-17 05:47:23 +01003292static int
3293locale_error_handler(const char *errors, int *surrogateescape)
3294{
3295 if (errors == NULL) {
3296 *surrogateescape = 0;
3297 return 0;
3298 }
3299
3300 if (strcmp(errors, "strict") == 0) {
3301 *surrogateescape = 0;
3302 return 0;
3303 }
3304 if (strcmp(errors, "surrogateescape") == 0) {
3305 *surrogateescape = 1;
3306 return 0;
3307 }
3308 PyErr_Format(PyExc_ValueError,
3309 "only 'strict' and 'surrogateescape' error handlers "
3310 "are supported, not '%s'",
3311 errors);
3312 return -1;
3313}
3314
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003315PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003316PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003317{
3318 Py_ssize_t wlen, wlen2;
3319 wchar_t *wstr;
3320 PyObject *bytes = NULL;
3321 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003322 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003323 PyObject *exc;
3324 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003325 int surrogateescape;
3326
3327 if (locale_error_handler(errors, &surrogateescape) < 0)
3328 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003329
3330 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3331 if (wstr == NULL)
3332 return NULL;
3333
3334 wlen2 = wcslen(wstr);
3335 if (wlen2 != wlen) {
3336 PyMem_Free(wstr);
3337 PyErr_SetString(PyExc_TypeError, "embedded null character");
3338 return NULL;
3339 }
3340
3341 if (surrogateescape) {
3342 /* locale encoding with surrogateescape */
3343 char *str;
3344
3345 str = _Py_wchar2char(wstr, &error_pos);
3346 if (str == NULL) {
3347 if (error_pos == (size_t)-1) {
3348 PyErr_NoMemory();
3349 PyMem_Free(wstr);
3350 return NULL;
3351 }
3352 else {
3353 goto encode_error;
3354 }
3355 }
3356 PyMem_Free(wstr);
3357
3358 bytes = PyBytes_FromString(str);
3359 PyMem_Free(str);
3360 }
3361 else {
3362 size_t len, len2;
3363
3364 len = wcstombs(NULL, wstr, 0);
3365 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003366 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003367 goto encode_error;
3368 }
3369
3370 bytes = PyBytes_FromStringAndSize(NULL, len);
3371 if (bytes == NULL) {
3372 PyMem_Free(wstr);
3373 return NULL;
3374 }
3375
3376 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3377 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003378 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003379 goto encode_error;
3380 }
3381 PyMem_Free(wstr);
3382 }
3383 return bytes;
3384
3385encode_error:
3386 errmsg = strerror(errno);
3387 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003388
3389 if (error_pos == (size_t)-1)
3390 error_pos = wcstombs_errorpos(wstr);
3391
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003392 PyMem_Free(wstr);
3393 Py_XDECREF(bytes);
3394
Victor Stinner2f197072011-12-17 07:08:30 +01003395 if (errmsg != NULL) {
3396 size_t errlen;
3397 wstr = _Py_char2wchar(errmsg, &errlen);
3398 if (wstr != NULL) {
3399 reason = PyUnicode_FromWideChar(wstr, errlen);
3400 PyMem_Free(wstr);
3401 } else
3402 errmsg = NULL;
3403 }
3404 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003405 reason = PyUnicode_FromString(
3406 "wcstombs() encountered an unencodable "
3407 "wide character");
3408 if (reason == NULL)
3409 return NULL;
3410
3411 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3412 "locale", unicode,
3413 (Py_ssize_t)error_pos,
3414 (Py_ssize_t)(error_pos+1),
3415 reason);
3416 Py_DECREF(reason);
3417 if (exc != NULL) {
3418 PyCodec_StrictErrors(exc);
3419 Py_XDECREF(exc);
3420 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003421 return NULL;
3422}
3423
Victor Stinnerad158722010-10-27 00:25:46 +00003424PyObject *
3425PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003426{
Victor Stinner99b95382011-07-04 14:23:54 +02003427#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003428 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003429#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003430 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003431#else
Victor Stinner793b5312011-04-27 00:24:21 +02003432 PyInterpreterState *interp = PyThreadState_GET()->interp;
3433 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3434 cannot use it to encode and decode filenames before it is loaded. Load
3435 the Python codec requires to encode at least its own filename. Use the C
3436 version of the locale codec until the codec registry is initialized and
3437 the Python codec is loaded.
3438
3439 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3440 cannot only rely on it: check also interp->fscodec_initialized for
3441 subinterpreters. */
3442 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003443 return PyUnicode_AsEncodedString(unicode,
3444 Py_FileSystemDefaultEncoding,
3445 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003446 }
3447 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003448 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003449 }
Victor Stinnerad158722010-10-27 00:25:46 +00003450#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003451}
3452
Alexander Belopolsky40018472011-02-26 01:02:56 +00003453PyObject *
3454PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003455 const char *encoding,
3456 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003457{
3458 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003459 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003460
Guido van Rossumd57fd912000-03-10 22:53:23 +00003461 if (!PyUnicode_Check(unicode)) {
3462 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003463 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003464 }
Fred Drakee4315f52000-05-09 19:53:39 +00003465
Fred Drakee4315f52000-05-09 19:53:39 +00003466 /* Shortcuts for common default encodings */
Victor Stinner20b654a2013-01-03 01:08:58 +01003467 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003468 if ((strcmp(lower, "utf-8") == 0) ||
3469 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003470 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003471 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003472 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003473 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003474 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003475 }
Victor Stinner37296e82010-06-10 13:36:23 +00003476 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003477 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003478 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003479 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003480#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003481 else if (strcmp(lower, "mbcs") == 0)
3482 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003483#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003484 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003485 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003486 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003487
3488 /* Encode via the codec registry */
3489 v = PyCodec_Encode(unicode, encoding, errors);
3490 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003491 return NULL;
3492
3493 /* The normal path */
3494 if (PyBytes_Check(v))
3495 return v;
3496
3497 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003498 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003499 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003500 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003501
3502 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3503 "encoder %s returned bytearray instead of bytes",
3504 encoding);
3505 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003506 Py_DECREF(v);
3507 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003508 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003509
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003510 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3511 Py_DECREF(v);
3512 return b;
3513 }
3514
3515 PyErr_Format(PyExc_TypeError,
3516 "encoder did not return a bytes object (type=%.400s)",
3517 Py_TYPE(v)->tp_name);
3518 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003519 return NULL;
3520}
3521
Alexander Belopolsky40018472011-02-26 01:02:56 +00003522PyObject *
3523PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003524 const char *encoding,
3525 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003526{
3527 PyObject *v;
3528
3529 if (!PyUnicode_Check(unicode)) {
3530 PyErr_BadArgument();
3531 goto onError;
3532 }
3533
3534 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003535 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003536
3537 /* Encode via the codec registry */
3538 v = PyCodec_Encode(unicode, encoding, errors);
3539 if (v == NULL)
3540 goto onError;
3541 if (!PyUnicode_Check(v)) {
3542 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003543 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003544 Py_TYPE(v)->tp_name);
3545 Py_DECREF(v);
3546 goto onError;
3547 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003548 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003549
Benjamin Peterson29060642009-01-31 22:14:21 +00003550 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003551 return NULL;
3552}
3553
Victor Stinner2f197072011-12-17 07:08:30 +01003554static size_t
3555mbstowcs_errorpos(const char *str, size_t len)
3556{
3557#ifdef HAVE_MBRTOWC
3558 const char *start = str;
3559 mbstate_t mbs;
3560 size_t converted;
3561 wchar_t ch;
3562
3563 memset(&mbs, 0, sizeof mbs);
3564 while (len)
3565 {
3566 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3567 if (converted == 0)
3568 /* Reached end of string */
3569 break;
3570 if (converted == (size_t)-1 || converted == (size_t)-2) {
3571 /* Conversion error or incomplete character */
3572 return str - start;
3573 }
3574 else {
3575 str += converted;
3576 len -= converted;
3577 }
3578 }
3579 /* failed to find the undecodable byte sequence */
3580 return 0;
3581#endif
3582 return 0;
3583}
3584
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003585PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003586PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003587 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003588{
3589 wchar_t smallbuf[256];
3590 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3591 wchar_t *wstr;
3592 size_t wlen, wlen2;
3593 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003594 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003595 size_t error_pos;
3596 char *errmsg;
3597 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003598
3599 if (locale_error_handler(errors, &surrogateescape) < 0)
3600 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003601
3602 if (str[len] != '\0' || len != strlen(str)) {
3603 PyErr_SetString(PyExc_TypeError, "embedded null character");
3604 return NULL;
3605 }
3606
3607 if (surrogateescape)
3608 {
3609 wstr = _Py_char2wchar(str, &wlen);
3610 if (wstr == NULL) {
3611 if (wlen == (size_t)-1)
3612 PyErr_NoMemory();
3613 else
3614 PyErr_SetFromErrno(PyExc_OSError);
3615 return NULL;
3616 }
3617
3618 unicode = PyUnicode_FromWideChar(wstr, wlen);
3619 PyMem_Free(wstr);
3620 }
3621 else {
3622#ifndef HAVE_BROKEN_MBSTOWCS
3623 wlen = mbstowcs(NULL, str, 0);
3624#else
3625 wlen = len;
3626#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003627 if (wlen == (size_t)-1)
3628 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003629 if (wlen+1 <= smallbuf_len) {
3630 wstr = smallbuf;
3631 }
3632 else {
3633 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3634 return PyErr_NoMemory();
3635
3636 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3637 if (!wstr)
3638 return PyErr_NoMemory();
3639 }
3640
3641 /* This shouldn't fail now */
3642 wlen2 = mbstowcs(wstr, str, wlen+1);
3643 if (wlen2 == (size_t)-1) {
3644 if (wstr != smallbuf)
3645 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003646 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003647 }
3648#ifdef HAVE_BROKEN_MBSTOWCS
3649 assert(wlen2 == wlen);
3650#endif
3651 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3652 if (wstr != smallbuf)
3653 PyMem_Free(wstr);
3654 }
3655 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003656
3657decode_error:
3658 errmsg = strerror(errno);
3659 assert(errmsg != NULL);
3660
3661 error_pos = mbstowcs_errorpos(str, len);
3662 if (errmsg != NULL) {
3663 size_t errlen;
3664 wstr = _Py_char2wchar(errmsg, &errlen);
3665 if (wstr != NULL) {
3666 reason = PyUnicode_FromWideChar(wstr, errlen);
3667 PyMem_Free(wstr);
3668 } else
3669 errmsg = NULL;
3670 }
3671 if (errmsg == NULL)
3672 reason = PyUnicode_FromString(
3673 "mbstowcs() encountered an invalid multibyte sequence");
3674 if (reason == NULL)
3675 return NULL;
3676
3677 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3678 "locale", str, len,
3679 (Py_ssize_t)error_pos,
3680 (Py_ssize_t)(error_pos+1),
3681 reason);
3682 Py_DECREF(reason);
3683 if (exc != NULL) {
3684 PyCodec_StrictErrors(exc);
3685 Py_XDECREF(exc);
3686 }
3687 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003688}
3689
3690PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003691PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003692{
3693 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003694 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003695}
3696
3697
3698PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003699PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003700 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003701 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3702}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003703
Christian Heimes5894ba72007-11-04 11:43:14 +00003704PyObject*
3705PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3706{
Victor Stinner99b95382011-07-04 14:23:54 +02003707#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003708 return PyUnicode_DecodeMBCS(s, size, NULL);
3709#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003710 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003711#else
Victor Stinner793b5312011-04-27 00:24:21 +02003712 PyInterpreterState *interp = PyThreadState_GET()->interp;
3713 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3714 cannot use it to encode and decode filenames before it is loaded. Load
3715 the Python codec requires to encode at least its own filename. Use the C
3716 version of the locale codec until the codec registry is initialized and
3717 the Python codec is loaded.
3718
3719 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3720 cannot only rely on it: check also interp->fscodec_initialized for
3721 subinterpreters. */
3722 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003723 return PyUnicode_Decode(s, size,
3724 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003725 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003726 }
3727 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003728 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003729 }
Victor Stinnerad158722010-10-27 00:25:46 +00003730#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003731}
3732
Martin v. Löwis011e8422009-05-05 04:43:17 +00003733
3734int
Antoine Pitrou13348842012-01-29 18:36:34 +01003735_PyUnicode_HasNULChars(PyObject* s)
3736{
3737 static PyObject *nul = NULL;
3738
3739 if (nul == NULL)
3740 nul = PyUnicode_FromStringAndSize("\0", 1);
3741 if (nul == NULL)
3742 return -1;
3743 return PyUnicode_Contains(s, nul);
3744}
3745
3746
3747int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003748PyUnicode_FSConverter(PyObject* arg, void* addr)
3749{
3750 PyObject *output = NULL;
3751 Py_ssize_t size;
3752 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003753 if (arg == NULL) {
3754 Py_DECREF(*(PyObject**)addr);
3755 return 1;
3756 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003757 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003758 output = arg;
3759 Py_INCREF(output);
3760 }
3761 else {
3762 arg = PyUnicode_FromObject(arg);
3763 if (!arg)
3764 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003765 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003766 Py_DECREF(arg);
3767 if (!output)
3768 return 0;
3769 if (!PyBytes_Check(output)) {
3770 Py_DECREF(output);
3771 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3772 return 0;
3773 }
3774 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003775 size = PyBytes_GET_SIZE(output);
3776 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003777 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003778 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003779 Py_DECREF(output);
3780 return 0;
3781 }
3782 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003783 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003784}
3785
3786
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003787int
3788PyUnicode_FSDecoder(PyObject* arg, void* addr)
3789{
3790 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003791 if (arg == NULL) {
3792 Py_DECREF(*(PyObject**)addr);
3793 return 1;
3794 }
3795 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003796 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003797 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003798 output = arg;
3799 Py_INCREF(output);
3800 }
3801 else {
3802 arg = PyBytes_FromObject(arg);
3803 if (!arg)
3804 return 0;
3805 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3806 PyBytes_GET_SIZE(arg));
3807 Py_DECREF(arg);
3808 if (!output)
3809 return 0;
3810 if (!PyUnicode_Check(output)) {
3811 Py_DECREF(output);
3812 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3813 return 0;
3814 }
3815 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003816 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003817 Py_DECREF(output);
3818 return 0;
3819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003821 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003822 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3823 Py_DECREF(output);
3824 return 0;
3825 }
3826 *(PyObject**)addr = output;
3827 return Py_CLEANUP_SUPPORTED;
3828}
3829
3830
Martin v. Löwis5b222132007-06-10 09:51:05 +00003831char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003832PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003833{
Christian Heimesf3863112007-11-22 07:46:41 +00003834 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003835
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003836 if (!PyUnicode_Check(unicode)) {
3837 PyErr_BadArgument();
3838 return NULL;
3839 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003841 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003843 if (PyUnicode_UTF8(unicode) == NULL) {
3844 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3846 if (bytes == NULL)
3847 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003848 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3849 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850 Py_DECREF(bytes);
3851 return NULL;
3852 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003853 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3854 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3855 PyBytes_AS_STRING(bytes),
3856 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003857 Py_DECREF(bytes);
3858 }
3859
3860 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003861 *psize = PyUnicode_UTF8_LENGTH(unicode);
3862 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003863}
3864
3865char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003867{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3869}
3870
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871Py_UNICODE *
3872PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3873{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 const unsigned char *one_byte;
3875#if SIZEOF_WCHAR_T == 4
3876 const Py_UCS2 *two_bytes;
3877#else
3878 const Py_UCS4 *four_bytes;
3879 const Py_UCS4 *ucs4_end;
3880 Py_ssize_t num_surrogates;
3881#endif
3882 wchar_t *w;
3883 wchar_t *wchar_end;
3884
3885 if (!PyUnicode_Check(unicode)) {
3886 PyErr_BadArgument();
3887 return NULL;
3888 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003889 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003891 assert(_PyUnicode_KIND(unicode) != 0);
3892 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003894 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003895#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003896 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3897 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003898 num_surrogates = 0;
3899
3900 for (; four_bytes < ucs4_end; ++four_bytes) {
3901 if (*four_bytes > 0xFFFF)
3902 ++num_surrogates;
3903 }
3904
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003905 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3906 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3907 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 PyErr_NoMemory();
3909 return NULL;
3910 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003911 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003913 w = _PyUnicode_WSTR(unicode);
3914 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3915 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3917 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003918 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003919 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003920 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3921 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003922 }
3923 else
3924 *w = *four_bytes;
3925
3926 if (w > wchar_end) {
3927 assert(0 && "Miscalculated string end");
3928 }
3929 }
3930 *w = 0;
3931#else
3932 /* sizeof(wchar_t) == 4 */
3933 Py_FatalError("Impossible unicode object state, wstr and str "
3934 "should share memory already.");
3935 return NULL;
3936#endif
3937 }
3938 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003939 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3940 (_PyUnicode_LENGTH(unicode) + 1));
3941 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003942 PyErr_NoMemory();
3943 return NULL;
3944 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003945 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3946 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3947 w = _PyUnicode_WSTR(unicode);
3948 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003950 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3951 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952 for (; w < wchar_end; ++one_byte, ++w)
3953 *w = *one_byte;
3954 /* null-terminate the wstr */
3955 *w = 0;
3956 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003957 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003959 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003960 for (; w < wchar_end; ++two_bytes, ++w)
3961 *w = *two_bytes;
3962 /* null-terminate the wstr */
3963 *w = 0;
3964#else
3965 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003966 PyObject_FREE(_PyUnicode_WSTR(unicode));
3967 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003968 Py_FatalError("Impossible unicode object state, wstr "
3969 "and str should share memory already.");
3970 return NULL;
3971#endif
3972 }
3973 else {
3974 assert(0 && "This should never happen.");
3975 }
3976 }
3977 }
3978 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003979 *size = PyUnicode_WSTR_LENGTH(unicode);
3980 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003981}
3982
Alexander Belopolsky40018472011-02-26 01:02:56 +00003983Py_UNICODE *
3984PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003985{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003986 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003987}
3988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003989
Alexander Belopolsky40018472011-02-26 01:02:56 +00003990Py_ssize_t
3991PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003992{
3993 if (!PyUnicode_Check(unicode)) {
3994 PyErr_BadArgument();
3995 goto onError;
3996 }
3997 return PyUnicode_GET_SIZE(unicode);
3998
Benjamin Peterson29060642009-01-31 22:14:21 +00003999 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004000 return -1;
4001}
4002
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003Py_ssize_t
4004PyUnicode_GetLength(PyObject *unicode)
4005{
Victor Stinner07621332012-06-16 04:53:46 +02004006 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007 PyErr_BadArgument();
4008 return -1;
4009 }
Victor Stinner07621332012-06-16 04:53:46 +02004010 if (PyUnicode_READY(unicode) == -1)
4011 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004012 return PyUnicode_GET_LENGTH(unicode);
4013}
4014
4015Py_UCS4
4016PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4017{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004018 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4019 PyErr_BadArgument();
4020 return (Py_UCS4)-1;
4021 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004022 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004023 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 return (Py_UCS4)-1;
4025 }
4026 return PyUnicode_READ_CHAR(unicode, index);
4027}
4028
4029int
4030PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4031{
4032 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004033 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034 return -1;
4035 }
Victor Stinner488fa492011-12-12 00:01:39 +01004036 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004037 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004038 PyErr_SetString(PyExc_IndexError, "string index out of range");
4039 return -1;
4040 }
Victor Stinner488fa492011-12-12 00:01:39 +01004041 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004042 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004043 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4044 PyErr_SetString(PyExc_ValueError, "character out of range");
4045 return -1;
4046 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4048 index, ch);
4049 return 0;
4050}
4051
Alexander Belopolsky40018472011-02-26 01:02:56 +00004052const char *
4053PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004054{
Victor Stinner42cb4622010-09-01 19:39:01 +00004055 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004056}
4057
Victor Stinner554f3f02010-06-16 23:33:54 +00004058/* create or adjust a UnicodeDecodeError */
4059static void
4060make_decode_exception(PyObject **exceptionObject,
4061 const char *encoding,
4062 const char *input, Py_ssize_t length,
4063 Py_ssize_t startpos, Py_ssize_t endpos,
4064 const char *reason)
4065{
4066 if (*exceptionObject == NULL) {
4067 *exceptionObject = PyUnicodeDecodeError_Create(
4068 encoding, input, length, startpos, endpos, reason);
4069 }
4070 else {
4071 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4072 goto onError;
4073 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4074 goto onError;
4075 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4076 goto onError;
4077 }
4078 return;
4079
4080onError:
4081 Py_DECREF(*exceptionObject);
4082 *exceptionObject = NULL;
4083}
4084
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004085/* error handling callback helper:
4086 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004087 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004088 and adjust various state variables.
4089 return 0 on success, -1 on error
4090*/
4091
Alexander Belopolsky40018472011-02-26 01:02:56 +00004092static int
4093unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004094 const char *encoding, const char *reason,
4095 const char **input, const char **inend, Py_ssize_t *startinpos,
4096 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004097 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004098{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004099 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004100
4101 PyObject *restuple = NULL;
4102 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004103 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004104 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004105 Py_ssize_t requiredsize;
4106 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004107 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004108 int res = -1;
4109
Victor Stinner596a6c42011-11-09 00:02:18 +01004110 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4111 outsize = PyUnicode_GET_LENGTH(*output);
4112 else
4113 outsize = _PyUnicode_WSTR_LENGTH(*output);
4114
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004115 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004116 *errorHandler = PyCodec_LookupError(errors);
4117 if (*errorHandler == NULL)
4118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119 }
4120
Victor Stinner554f3f02010-06-16 23:33:54 +00004121 make_decode_exception(exceptionObject,
4122 encoding,
4123 *input, *inend - *input,
4124 *startinpos, *endinpos,
4125 reason);
4126 if (*exceptionObject == NULL)
4127 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128
4129 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4130 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004131 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004132 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004133 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004134 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 }
4136 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004137 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004138 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004139 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140
4141 /* Copy back the bytes variables, which might have been modified by the
4142 callback */
4143 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4144 if (!inputobj)
4145 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004146 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004147 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004148 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004149 *input = PyBytes_AS_STRING(inputobj);
4150 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004151 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004152 /* we can DECREF safely, as the exception has another reference,
4153 so the object won't go away. */
4154 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004155
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004156 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004157 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004158 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004159 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4160 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004161 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004162
Victor Stinner596a6c42011-11-09 00:02:18 +01004163 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4164 /* need more space? (at least enough for what we
4165 have+the replacement+the rest of the string (starting
4166 at the new input position), so we won't have to check space
4167 when there are no errors in the rest of the string) */
4168 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4169 requiredsize = *outpos + replen + insize-newpos;
4170 if (requiredsize > outsize) {
4171 if (requiredsize<2*outsize)
4172 requiredsize = 2*outsize;
4173 if (unicode_resize(output, requiredsize) < 0)
4174 goto onError;
4175 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004176 if (unicode_widen(output, *outpos,
4177 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004179 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004180 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004182 else {
4183 wchar_t *repwstr;
4184 Py_ssize_t repwlen;
4185 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4186 if (repwstr == NULL)
4187 goto onError;
4188 /* need more space? (at least enough for what we
4189 have+the replacement+the rest of the string (starting
4190 at the new input position), so we won't have to check space
4191 when there are no errors in the rest of the string) */
4192 requiredsize = *outpos + repwlen + insize-newpos;
4193 if (requiredsize > outsize) {
4194 if (requiredsize < 2*outsize)
4195 requiredsize = 2*outsize;
4196 if (unicode_resize(output, requiredsize) < 0)
4197 goto onError;
4198 }
4199 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4200 *outpos += repwlen;
4201 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004202 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004203 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004204
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004205 /* we made it! */
4206 res = 0;
4207
Benjamin Peterson29060642009-01-31 22:14:21 +00004208 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209 Py_XDECREF(restuple);
4210 return res;
4211}
4212
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004213/* --- UTF-7 Codec -------------------------------------------------------- */
4214
Antoine Pitrou244651a2009-05-04 18:56:13 +00004215/* See RFC2152 for details. We encode conservatively and decode liberally. */
4216
4217/* Three simple macros defining base-64. */
4218
4219/* Is c a base-64 character? */
4220
4221#define IS_BASE64(c) \
4222 (((c) >= 'A' && (c) <= 'Z') || \
4223 ((c) >= 'a' && (c) <= 'z') || \
4224 ((c) >= '0' && (c) <= '9') || \
4225 (c) == '+' || (c) == '/')
4226
4227/* given that c is a base-64 character, what is its base-64 value? */
4228
4229#define FROM_BASE64(c) \
4230 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4231 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4232 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4233 (c) == '+' ? 62 : 63)
4234
4235/* What is the base-64 character of the bottom 6 bits of n? */
4236
4237#define TO_BASE64(n) \
4238 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4239
4240/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4241 * decoded as itself. We are permissive on decoding; the only ASCII
4242 * byte not decoding to itself is the + which begins a base64
4243 * string. */
4244
4245#define DECODE_DIRECT(c) \
4246 ((c) <= 127 && (c) != '+')
4247
4248/* The UTF-7 encoder treats ASCII characters differently according to
4249 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4250 * the above). See RFC2152. This array identifies these different
4251 * sets:
4252 * 0 : "Set D"
4253 * alphanumeric and '(),-./:?
4254 * 1 : "Set O"
4255 * !"#$%&*;<=>@[]^_`{|}
4256 * 2 : "whitespace"
4257 * ht nl cr sp
4258 * 3 : special (must be base64 encoded)
4259 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4260 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261
Tim Petersced69f82003-09-16 20:30:58 +00004262static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263char utf7_category[128] = {
4264/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4265 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4266/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4267 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4268/* sp ! " # $ % & ' ( ) * + , - . / */
4269 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4270/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4272/* @ A B C D E F G H I J K L M N O */
4273 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4274/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
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 { | } ~ del */
4279 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004280};
4281
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282/* ENCODE_DIRECT: this character should be encoded as itself. The
4283 * answer depends on whether we are encoding set O as itself, and also
4284 * on whether we are encoding whitespace as itself. RFC2152 makes it
4285 * clear that the answers to these questions vary between
4286 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004287
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288#define ENCODE_DIRECT(c, directO, directWS) \
4289 ((c) < 128 && (c) > 0 && \
4290 ((utf7_category[(c)] == 0) || \
4291 (directWS && (utf7_category[(c)] == 2)) || \
4292 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293
Alexander Belopolsky40018472011-02-26 01:02:56 +00004294PyObject *
4295PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004296 Py_ssize_t size,
4297 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004298{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004299 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4300}
4301
Antoine Pitrou244651a2009-05-04 18:56:13 +00004302/* The decoder. The only state we preserve is our read position,
4303 * i.e. how many characters we have consumed. So if we end in the
4304 * middle of a shift sequence we have to back off the read position
4305 * and the output to the beginning of the sequence, otherwise we lose
4306 * all the shift state (seen bits, number of bits seen, high
4307 * surrogate). */
4308
Alexander Belopolsky40018472011-02-26 01:02:56 +00004309PyObject *
4310PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004311 Py_ssize_t size,
4312 const char *errors,
4313 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004314{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004315 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004316 Py_ssize_t startinpos;
4317 Py_ssize_t endinpos;
4318 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004320 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004321 const char *errmsg = "";
4322 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004323 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324 unsigned int base64bits = 0;
4325 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004326 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004327 PyObject *errorHandler = NULL;
4328 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004329
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004330 /* Start off assuming it's all ASCII. Widen later as necessary. */
4331 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332 if (!unicode)
4333 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004334 if (size == 0) {
4335 if (consumed)
4336 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004337 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004338 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004339
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004340 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341 e = s + size;
4342
4343 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004344 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004345 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004346 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 if (inShift) { /* in a base-64 section */
4349 if (IS_BASE64(ch)) { /* consume a base-64 character */
4350 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4351 base64bits += 6;
4352 s++;
4353 if (base64bits >= 16) {
4354 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004355 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 base64bits -= 16;
4357 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4358 if (surrogate) {
4359 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004360 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4361 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4363 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004365 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 }
4367 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004368 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 }
Victor Stinner551ac952011-11-29 22:58:13 +01004373 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 /* first surrogate */
4375 surrogate = outCh;
4376 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004378 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4379 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004380 }
4381 }
4382 }
4383 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384 inShift = 0;
4385 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004386 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004387 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4388 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004389 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 if (base64bits > 0) { /* left-over bits */
4392 if (base64bits >= 6) {
4393 /* We've seen at least one base-64 character */
4394 errmsg = "partial character in shift sequence";
4395 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397 else {
4398 /* Some bits remain; they should be zero */
4399 if (base64buffer != 0) {
4400 errmsg = "non-zero padding bits in shift sequence";
4401 goto utf7Error;
4402 }
4403 }
4404 }
4405 if (ch != '-') {
4406 /* '-' is absorbed; other terminating
4407 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4409 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 }
4412 }
4413 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 s++; /* consume '+' */
4416 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004418 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4419 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 }
4421 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004423 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425 }
4426 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004428 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4429 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430 s++;
4431 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 else {
4433 startinpos = s-starts;
4434 s++;
4435 errmsg = "unexpected special character";
4436 goto utf7Error;
4437 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004440 endinpos = s-starts;
4441 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004442 errors, &errorHandler,
4443 "utf7", errmsg,
4444 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004445 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004446 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447 }
4448
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 /* end of string */
4450
4451 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4452 /* if we're in an inconsistent state, that's an error */
4453 if (surrogate ||
4454 (base64bits >= 6) ||
4455 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 endinpos = size;
4457 if (unicode_decode_call_errorhandler(
4458 errors, &errorHandler,
4459 "utf7", "unterminated shift sequence",
4460 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004461 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 goto onError;
4463 if (s < e)
4464 goto restart;
4465 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467
4468 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004469 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004471 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004472 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 }
4474 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004475 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004477 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004479 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480 goto onError;
4481
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004482 Py_XDECREF(errorHandler);
4483 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004484 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485
Benjamin Peterson29060642009-01-31 22:14:21 +00004486 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004487 Py_XDECREF(errorHandler);
4488 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489 Py_DECREF(unicode);
4490 return NULL;
4491}
4492
4493
Alexander Belopolsky40018472011-02-26 01:02:56 +00004494PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495_PyUnicode_EncodeUTF7(PyObject *str,
4496 int base64SetO,
4497 int base64WhiteSpace,
4498 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004500 int kind;
4501 void *data;
4502 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004503 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004505 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506 unsigned int base64bits = 0;
4507 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 char * out;
4509 char * start;
4510
Benjamin Petersonbac79492012-01-14 13:34:47 -05004511 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004512 return NULL;
4513 kind = PyUnicode_KIND(str);
4514 data = PyUnicode_DATA(str);
4515 len = PyUnicode_GET_LENGTH(str);
4516
4517 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004518 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004520 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004521 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004522 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004523 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 if (v == NULL)
4525 return NULL;
4526
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004527 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004528 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004529 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 if (inShift) {
4532 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4533 /* shifting out */
4534 if (base64bits) { /* output remaining bits */
4535 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4536 base64buffer = 0;
4537 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 }
4539 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004540 /* Characters not in the BASE64 set implicitly unshift the sequence
4541 so no '-' is required, except if the character is itself a '-' */
4542 if (IS_BASE64(ch) || ch == '-') {
4543 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 *out++ = (char) ch;
4546 }
4547 else {
4548 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004549 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004551 else { /* not in a shift sequence */
4552 if (ch == '+') {
4553 *out++ = '+';
4554 *out++ = '-';
4555 }
4556 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4557 *out++ = (char) ch;
4558 }
4559 else {
4560 *out++ = '+';
4561 inShift = 1;
4562 goto encode_char;
4563 }
4564 }
4565 continue;
4566encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004568 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004569
Antoine Pitrou244651a2009-05-04 18:56:13 +00004570 /* code first surrogate */
4571 base64bits += 16;
4572 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4573 while (base64bits >= 6) {
4574 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4575 base64bits -= 6;
4576 }
4577 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004578 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004579 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 base64bits += 16;
4581 base64buffer = (base64buffer << 16) | ch;
4582 while (base64bits >= 6) {
4583 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4584 base64bits -= 6;
4585 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004586 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 if (base64bits)
4588 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4589 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004590 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004591 if (_PyBytes_Resize(&v, out - start) < 0)
4592 return NULL;
4593 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004594}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004595PyObject *
4596PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4597 Py_ssize_t size,
4598 int base64SetO,
4599 int base64WhiteSpace,
4600 const char *errors)
4601{
4602 PyObject *result;
4603 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4604 if (tmp == NULL)
4605 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004606 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004607 base64WhiteSpace, errors);
4608 Py_DECREF(tmp);
4609 return result;
4610}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611
Antoine Pitrou244651a2009-05-04 18:56:13 +00004612#undef IS_BASE64
4613#undef FROM_BASE64
4614#undef TO_BASE64
4615#undef DECODE_DIRECT
4616#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004617
Guido van Rossumd57fd912000-03-10 22:53:23 +00004618/* --- UTF-8 Codec -------------------------------------------------------- */
4619
Alexander Belopolsky40018472011-02-26 01:02:56 +00004620PyObject *
4621PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004622 Py_ssize_t size,
4623 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004624{
Walter Dörwald69652032004-09-07 20:24:22 +00004625 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4626}
4627
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004628#include "stringlib/asciilib.h"
4629#include "stringlib/codecs.h"
4630#include "stringlib/undef.h"
4631
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004632#include "stringlib/ucs1lib.h"
4633#include "stringlib/codecs.h"
4634#include "stringlib/undef.h"
4635
4636#include "stringlib/ucs2lib.h"
4637#include "stringlib/codecs.h"
4638#include "stringlib/undef.h"
4639
4640#include "stringlib/ucs4lib.h"
4641#include "stringlib/codecs.h"
4642#include "stringlib/undef.h"
4643
Antoine Pitrouab868312009-01-10 15:40:25 +00004644/* Mask to quickly check whether a C 'long' contains a
4645 non-ASCII, UTF8-encoded char. */
4646#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004647# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004648#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004649# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004650#else
4651# error C 'long' size should be either 4 or 8!
4652#endif
4653
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654static Py_ssize_t
4655ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004656{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004658 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004659
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004660#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004661 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4662 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004663 /* Fast path, see in STRINGLIB(utf8_decode) for
4664 an explanation. */
4665 /* Help register allocation */
4666 register const char *_p = p;
4667 register Py_UCS1 * q = dest;
4668 while (_p < aligned_end) {
4669 unsigned long value = *(const unsigned long *) _p;
4670 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004671 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672 *((unsigned long *)q) = value;
4673 _p += SIZEOF_LONG;
4674 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004675 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 p = _p;
4677 while (p < end) {
4678 if ((unsigned char)*p & 0x80)
4679 break;
4680 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004681 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004683 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004684#endif
4685 while (p < end) {
4686 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4687 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004688 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004689 /* Help register allocation */
4690 register const char *_p = p;
4691 while (_p < aligned_end) {
4692 unsigned long value = *(unsigned long *) _p;
4693 if (value & ASCII_CHAR_MASK)
4694 break;
4695 _p += SIZEOF_LONG;
4696 }
4697 p = _p;
4698 if (_p == end)
4699 break;
4700 }
4701 if ((unsigned char)*p & 0x80)
4702 break;
4703 ++p;
4704 }
4705 memcpy(dest, start, p - start);
4706 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004707}
Antoine Pitrouab868312009-01-10 15:40:25 +00004708
Victor Stinner785938e2011-12-11 20:09:03 +01004709PyObject *
4710PyUnicode_DecodeUTF8Stateful(const char *s,
4711 Py_ssize_t size,
4712 const char *errors,
4713 Py_ssize_t *consumed)
4714{
Victor Stinner785938e2011-12-11 20:09:03 +01004715 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004716 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004717 const char *end = s + size;
4718 Py_ssize_t outpos;
4719
4720 Py_ssize_t startinpos;
4721 Py_ssize_t endinpos;
4722 const char *errmsg = "";
4723 PyObject *errorHandler = NULL;
4724 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004725
4726 if (size == 0) {
4727 if (consumed)
4728 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004729 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004730 }
4731
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004732 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4733 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004734 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004735 *consumed = 1;
4736 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004737 }
4738
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004740 if (!unicode)
4741 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004742
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004743 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4744 s += outpos;
4745 while (s < end) {
4746 Py_UCS4 ch;
4747 int kind = PyUnicode_KIND(unicode);
4748 if (kind == PyUnicode_1BYTE_KIND) {
4749 if (PyUnicode_IS_ASCII(unicode))
4750 ch = asciilib_utf8_decode(&s, end,
4751 PyUnicode_1BYTE_DATA(unicode), &outpos);
4752 else
4753 ch = ucs1lib_utf8_decode(&s, end,
4754 PyUnicode_1BYTE_DATA(unicode), &outpos);
4755 } else if (kind == PyUnicode_2BYTE_KIND) {
4756 ch = ucs2lib_utf8_decode(&s, end,
4757 PyUnicode_2BYTE_DATA(unicode), &outpos);
4758 } else {
4759 assert(kind == PyUnicode_4BYTE_KIND);
4760 ch = ucs4lib_utf8_decode(&s, end,
4761 PyUnicode_4BYTE_DATA(unicode), &outpos);
4762 }
4763
4764 switch (ch) {
4765 case 0:
4766 if (s == end || consumed)
4767 goto End;
4768 errmsg = "unexpected end of data";
4769 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004770 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 break;
4772 case 1:
4773 errmsg = "invalid start byte";
4774 startinpos = s - starts;
4775 endinpos = startinpos + 1;
4776 break;
4777 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004778 case 3:
4779 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004780 errmsg = "invalid continuation byte";
4781 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004782 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004783 break;
4784 default:
4785 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4786 goto onError;
4787 continue;
4788 }
4789
4790 if (unicode_decode_call_errorhandler(
4791 errors, &errorHandler,
4792 "utf-8", errmsg,
4793 &starts, &end, &startinpos, &endinpos, &exc, &s,
4794 &unicode, &outpos))
4795 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004796 }
4797
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798End:
4799 if (unicode_resize(&unicode, outpos) < 0)
4800 goto onError;
4801
4802 if (consumed)
4803 *consumed = s - starts;
4804
4805 Py_XDECREF(errorHandler);
4806 Py_XDECREF(exc);
4807 assert(_PyUnicode_CheckConsistency(unicode, 1));
4808 return unicode;
4809
4810onError:
4811 Py_XDECREF(errorHandler);
4812 Py_XDECREF(exc);
4813 Py_XDECREF(unicode);
4814 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004815}
4816
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817#ifdef __APPLE__
4818
4819/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner27b1ca22012-12-03 12:47:59 +01004820 used to decode the command line arguments on Mac OS X.
4821
4822 Return a pointer to a newly allocated wide character string (use
4823 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004824
4825wchar_t*
4826_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4827{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004828 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004829 wchar_t *unicode;
4830 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004831
4832 /* Note: size will always be longer than the resulting Unicode
4833 character count */
Victor Stinner27b1ca22012-12-03 12:47:59 +01004834 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004835 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4837 if (!unicode)
4838 return NULL;
4839
4840 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004841 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004842 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004843 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004844 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004845#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004846 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004847#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004848 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004849#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 if (ch > 0xFF) {
4851#if SIZEOF_WCHAR_T == 4
4852 assert(0);
4853#else
4854 assert(Py_UNICODE_IS_SURROGATE(ch));
4855 /* compute and append the two surrogates: */
4856 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4857 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4858#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004859 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004860 else {
4861 if (!ch && s == e)
4862 break;
4863 /* surrogateescape */
4864 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4865 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004866 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004868 return unicode;
4869}
4870
4871#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004873/* Primary internal function which creates utf8 encoded bytes objects.
4874
4875 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004876 and allocate exactly as much space needed at the end. Else allocate the
4877 maximum possible needed (4 result bytes per Unicode character), and return
4878 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004879*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004880PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004881_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004882{
Victor Stinner6099a032011-12-18 14:22:26 +01004883 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884 void *data;
4885 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004887 if (!PyUnicode_Check(unicode)) {
4888 PyErr_BadArgument();
4889 return NULL;
4890 }
4891
4892 if (PyUnicode_READY(unicode) == -1)
4893 return NULL;
4894
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004895 if (PyUnicode_UTF8(unicode))
4896 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4897 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004898
4899 kind = PyUnicode_KIND(unicode);
4900 data = PyUnicode_DATA(unicode);
4901 size = PyUnicode_GET_LENGTH(unicode);
4902
Benjamin Petersonead6b532011-12-20 17:23:42 -06004903 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004904 default:
4905 assert(0);
4906 case PyUnicode_1BYTE_KIND:
4907 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4908 assert(!PyUnicode_IS_ASCII(unicode));
4909 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4910 case PyUnicode_2BYTE_KIND:
4911 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4912 case PyUnicode_4BYTE_KIND:
4913 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004914 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004915}
4916
Alexander Belopolsky40018472011-02-26 01:02:56 +00004917PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004918PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4919 Py_ssize_t size,
4920 const char *errors)
4921{
4922 PyObject *v, *unicode;
4923
4924 unicode = PyUnicode_FromUnicode(s, size);
4925 if (unicode == NULL)
4926 return NULL;
4927 v = _PyUnicode_AsUTF8String(unicode, errors);
4928 Py_DECREF(unicode);
4929 return v;
4930}
4931
4932PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004933PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004934{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004935 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004936}
4937
Walter Dörwald41980ca2007-08-16 21:55:45 +00004938/* --- UTF-32 Codec ------------------------------------------------------- */
4939
4940PyObject *
4941PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004942 Py_ssize_t size,
4943 const char *errors,
4944 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004945{
4946 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4947}
4948
4949PyObject *
4950PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004951 Py_ssize_t size,
4952 const char *errors,
4953 int *byteorder,
4954 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955{
4956 const char *starts = s;
4957 Py_ssize_t startinpos;
4958 Py_ssize_t endinpos;
4959 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004960 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004961 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004962 int bo = 0; /* assume native ordering by default */
4963 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 /* Offsets from q for retrieving bytes in the right order. */
4965#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4966 int iorder[] = {0, 1, 2, 3};
4967#else
4968 int iorder[] = {3, 2, 1, 0};
4969#endif
4970 PyObject *errorHandler = NULL;
4971 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004972
Walter Dörwald41980ca2007-08-16 21:55:45 +00004973 q = (unsigned char *)s;
4974 e = q + size;
4975
4976 if (byteorder)
4977 bo = *byteorder;
4978
4979 /* Check for BOM marks (U+FEFF) in the input and adjust current
4980 byte order setting accordingly. In native mode, the leading BOM
4981 mark is skipped, in all other modes, it is copied to the output
4982 stream as-is (giving a ZWNBSP character). */
4983 if (bo == 0) {
4984 if (size >= 4) {
4985 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004986 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004987#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004988 if (bom == 0x0000FEFF) {
4989 q += 4;
4990 bo = -1;
4991 }
4992 else if (bom == 0xFFFE0000) {
4993 q += 4;
4994 bo = 1;
4995 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004996#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004997 if (bom == 0x0000FEFF) {
4998 q += 4;
4999 bo = 1;
5000 }
5001 else if (bom == 0xFFFE0000) {
5002 q += 4;
5003 bo = -1;
5004 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005005#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005006 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005007 }
5008
5009 if (bo == -1) {
5010 /* force LE */
5011 iorder[0] = 0;
5012 iorder[1] = 1;
5013 iorder[2] = 2;
5014 iorder[3] = 3;
5015 }
5016 else if (bo == 1) {
5017 /* force BE */
5018 iorder[0] = 3;
5019 iorder[1] = 2;
5020 iorder[2] = 1;
5021 iorder[3] = 0;
5022 }
5023
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005024 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005025 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005026 if (!unicode)
5027 return NULL;
5028 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005029 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005030 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005031
Walter Dörwald41980ca2007-08-16 21:55:45 +00005032 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 Py_UCS4 ch;
5034 /* remaining bytes at the end? (size should be divisible by 4) */
5035 if (e-q<4) {
5036 if (consumed)
5037 break;
5038 errmsg = "truncated data";
5039 startinpos = ((const char *)q)-starts;
5040 endinpos = ((const char *)e)-starts;
5041 goto utf32Error;
5042 /* The remaining input chars are ignored if the callback
5043 chooses to skip the input */
5044 }
5045 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5046 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 if (ch >= 0x110000)
5049 {
5050 errmsg = "codepoint not in range(0x110000)";
5051 startinpos = ((const char *)q)-starts;
5052 endinpos = startinpos+4;
5053 goto utf32Error;
5054 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005055 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5056 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 q += 4;
5058 continue;
5059 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 if (unicode_decode_call_errorhandler(
5061 errors, &errorHandler,
5062 "utf32", errmsg,
5063 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005064 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066 }
5067
5068 if (byteorder)
5069 *byteorder = bo;
5070
5071 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005073
5074 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005075 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076 goto onError;
5077
5078 Py_XDECREF(errorHandler);
5079 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005080 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081
Benjamin Peterson29060642009-01-31 22:14:21 +00005082 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 Py_DECREF(unicode);
5084 Py_XDECREF(errorHandler);
5085 Py_XDECREF(exc);
5086 return NULL;
5087}
5088
5089PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005090_PyUnicode_EncodeUTF32(PyObject *str,
5091 const char *errors,
5092 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005094 int kind;
5095 void *data;
5096 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005097 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005099 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100 /* Offsets from p for storing byte pairs in the right order. */
5101#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5102 int iorder[] = {0, 1, 2, 3};
5103#else
5104 int iorder[] = {3, 2, 1, 0};
5105#endif
5106
Benjamin Peterson29060642009-01-31 22:14:21 +00005107#define STORECHAR(CH) \
5108 do { \
5109 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5110 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5111 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5112 p[iorder[0]] = (CH) & 0xff; \
5113 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114 } while(0)
5115
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005116 if (!PyUnicode_Check(str)) {
5117 PyErr_BadArgument();
5118 return NULL;
5119 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005120 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005121 return NULL;
5122 kind = PyUnicode_KIND(str);
5123 data = PyUnicode_DATA(str);
5124 len = PyUnicode_GET_LENGTH(str);
5125
5126 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005127 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005128 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005129 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005130 if (v == NULL)
5131 return NULL;
5132
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005133 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005134 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005135 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005136 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005137 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138
5139 if (byteorder == -1) {
5140 /* force LE */
5141 iorder[0] = 0;
5142 iorder[1] = 1;
5143 iorder[2] = 2;
5144 iorder[3] = 3;
5145 }
5146 else if (byteorder == 1) {
5147 /* force BE */
5148 iorder[0] = 3;
5149 iorder[1] = 2;
5150 iorder[2] = 1;
5151 iorder[3] = 0;
5152 }
5153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005154 for (i = 0; i < len; i++)
5155 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005156
5157 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005158 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005159#undef STORECHAR
5160}
5161
Alexander Belopolsky40018472011-02-26 01:02:56 +00005162PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005163PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5164 Py_ssize_t size,
5165 const char *errors,
5166 int byteorder)
5167{
5168 PyObject *result;
5169 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5170 if (tmp == NULL)
5171 return NULL;
5172 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5173 Py_DECREF(tmp);
5174 return result;
5175}
5176
5177PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005178PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179{
Victor Stinnerb960b342011-11-20 19:12:52 +01005180 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005181}
5182
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183/* --- UTF-16 Codec ------------------------------------------------------- */
5184
Tim Peters772747b2001-08-09 22:21:55 +00005185PyObject *
5186PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005187 Py_ssize_t size,
5188 const char *errors,
5189 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005190{
Walter Dörwald69652032004-09-07 20:24:22 +00005191 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5192}
5193
5194PyObject *
5195PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005196 Py_ssize_t size,
5197 const char *errors,
5198 int *byteorder,
5199 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005200{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005201 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005202 Py_ssize_t startinpos;
5203 Py_ssize_t endinpos;
5204 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005205 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005206 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005207 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005208 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005209 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005210 PyObject *errorHandler = NULL;
5211 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
Tim Peters772747b2001-08-09 22:21:55 +00005213 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005214 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
5216 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005217 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005219 /* Check for BOM marks (U+FEFF) in the input and adjust current
5220 byte order setting accordingly. In native mode, the leading BOM
5221 mark is skipped, in all other modes, it is copied to the output
5222 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005223 if (bo == 0 && size >= 2) {
5224 const Py_UCS4 bom = (q[1] << 8) | q[0];
5225 if (bom == 0xFEFF) {
5226 q += 2;
5227 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005228 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005229 else if (bom == 0xFFFE) {
5230 q += 2;
5231 bo = 1;
5232 }
5233 if (byteorder)
5234 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005236
Antoine Pitrou63065d72012-05-15 23:48:04 +02005237 if (q == e) {
5238 if (consumed)
5239 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005240 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005241 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005242
Antoine Pitrouab868312009-01-10 15:40:25 +00005243#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005244 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005245#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005246 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005247#endif
Tim Peters772747b2001-08-09 22:21:55 +00005248
Antoine Pitrou63065d72012-05-15 23:48:04 +02005249 /* Note: size will always be longer than the resulting Unicode
5250 character count */
5251 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5252 if (!unicode)
5253 return NULL;
5254
5255 outpos = 0;
5256 while (1) {
5257 Py_UCS4 ch = 0;
5258 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005259 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005260 if (kind == PyUnicode_1BYTE_KIND) {
5261 if (PyUnicode_IS_ASCII(unicode))
5262 ch = asciilib_utf16_decode(&q, e,
5263 PyUnicode_1BYTE_DATA(unicode), &outpos,
5264 native_ordering);
5265 else
5266 ch = ucs1lib_utf16_decode(&q, e,
5267 PyUnicode_1BYTE_DATA(unicode), &outpos,
5268 native_ordering);
5269 } else if (kind == PyUnicode_2BYTE_KIND) {
5270 ch = ucs2lib_utf16_decode(&q, e,
5271 PyUnicode_2BYTE_DATA(unicode), &outpos,
5272 native_ordering);
5273 } else {
5274 assert(kind == PyUnicode_4BYTE_KIND);
5275 ch = ucs4lib_utf16_decode(&q, e,
5276 PyUnicode_4BYTE_DATA(unicode), &outpos,
5277 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005278 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005279 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005280
Antoine Pitrou63065d72012-05-15 23:48:04 +02005281 switch (ch)
5282 {
5283 case 0:
5284 /* remaining byte at the end? (size should be even) */
5285 if (q == e || consumed)
5286 goto End;
5287 errmsg = "truncated data";
5288 startinpos = ((const char *)q) - starts;
5289 endinpos = ((const char *)e) - starts;
5290 break;
5291 /* The remaining input chars are ignored if the callback
5292 chooses to skip the input */
5293 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005294 q -= 2;
5295 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005296 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005297 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005298 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005299 endinpos = ((const char *)e) - starts;
5300 break;
5301 case 2:
5302 errmsg = "illegal encoding";
5303 startinpos = ((const char *)q) - 2 - starts;
5304 endinpos = startinpos + 2;
5305 break;
5306 case 3:
5307 errmsg = "illegal UTF-16 surrogate";
5308 startinpos = ((const char *)q) - 4 - starts;
5309 endinpos = startinpos + 2;
5310 break;
5311 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005312 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5313 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005314 continue;
5315 }
5316
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005318 errors,
5319 &errorHandler,
5320 "utf16", errmsg,
5321 &starts,
5322 (const char **)&e,
5323 &startinpos,
5324 &endinpos,
5325 &exc,
5326 (const char **)&q,
5327 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005328 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005330 }
5331
Antoine Pitrou63065d72012-05-15 23:48:04 +02005332End:
Walter Dörwald69652032004-09-07 20:24:22 +00005333 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005335
Guido van Rossumd57fd912000-03-10 22:53:23 +00005336 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005337 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005338 goto onError;
5339
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005340 Py_XDECREF(errorHandler);
5341 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005342 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005345 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005346 Py_XDECREF(errorHandler);
5347 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005348 return NULL;
5349}
5350
Tim Peters772747b2001-08-09 22:21:55 +00005351PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005352_PyUnicode_EncodeUTF16(PyObject *str,
5353 const char *errors,
5354 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005355{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005356 enum PyUnicode_Kind kind;
5357 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005358 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005359 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005360 unsigned short *out;
5361 Py_ssize_t bytesize;
5362 Py_ssize_t pairs;
5363#ifdef WORDS_BIGENDIAN
5364 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005365#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005366 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005367#endif
5368
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005369 if (!PyUnicode_Check(str)) {
5370 PyErr_BadArgument();
5371 return NULL;
5372 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005373 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005374 return NULL;
5375 kind = PyUnicode_KIND(str);
5376 data = PyUnicode_DATA(str);
5377 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005378
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005379 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005380 if (kind == PyUnicode_4BYTE_KIND) {
5381 const Py_UCS4 *in = (const Py_UCS4 *)data;
5382 const Py_UCS4 *end = in + len;
5383 while (in < end)
5384 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005385 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005386 }
5387 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005388 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005389 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005390 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005391 if (v == NULL)
5392 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005393
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005394 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005395 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005396 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005397 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005398 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005399 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005400 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005401
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005402 switch (kind) {
5403 case PyUnicode_1BYTE_KIND: {
5404 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5405 break;
Tim Peters772747b2001-08-09 22:21:55 +00005406 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005407 case PyUnicode_2BYTE_KIND: {
5408 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5409 break;
Tim Peters772747b2001-08-09 22:21:55 +00005410 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005411 case PyUnicode_4BYTE_KIND: {
5412 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5413 break;
5414 }
5415 default:
5416 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005417 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005418
5419 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005420 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421}
5422
Alexander Belopolsky40018472011-02-26 01:02:56 +00005423PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005424PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5425 Py_ssize_t size,
5426 const char *errors,
5427 int byteorder)
5428{
5429 PyObject *result;
5430 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5431 if (tmp == NULL)
5432 return NULL;
5433 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5434 Py_DECREF(tmp);
5435 return result;
5436}
5437
5438PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005439PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005440{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005441 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442}
5443
5444/* --- Unicode Escape Codec ----------------------------------------------- */
5445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005446/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5447 if all the escapes in the string make it still a valid ASCII string.
5448 Returns -1 if any escapes were found which cause the string to
5449 pop out of ASCII range. Otherwise returns the length of the
5450 required buffer to hold the string.
5451 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005452static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005453length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5454{
5455 const unsigned char *p = (const unsigned char *)s;
5456 const unsigned char *end = p + size;
5457 Py_ssize_t length = 0;
5458
5459 if (size < 0)
5460 return -1;
5461
5462 for (; p < end; ++p) {
5463 if (*p > 127) {
5464 /* Non-ASCII */
5465 return -1;
5466 }
5467 else if (*p != '\\') {
5468 /* Normal character */
5469 ++length;
5470 }
5471 else {
5472 /* Backslash-escape, check next char */
5473 ++p;
5474 /* Escape sequence reaches till end of string or
5475 non-ASCII follow-up. */
5476 if (p >= end || *p > 127)
5477 return -1;
5478 switch (*p) {
5479 case '\n':
5480 /* backslash + \n result in zero characters */
5481 break;
5482 case '\\': case '\'': case '\"':
5483 case 'b': case 'f': case 't':
5484 case 'n': case 'r': case 'v': case 'a':
5485 ++length;
5486 break;
5487 case '0': case '1': case '2': case '3':
5488 case '4': case '5': case '6': case '7':
5489 case 'x': case 'u': case 'U': case 'N':
5490 /* these do not guarantee ASCII characters */
5491 return -1;
5492 default:
5493 /* count the backslash + the other character */
5494 length += 2;
5495 }
5496 }
5497 }
5498 return length;
5499}
5500
Fredrik Lundh06d12682001-01-24 07:59:11 +00005501static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005502
Alexander Belopolsky40018472011-02-26 01:02:56 +00005503PyObject *
5504PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005505 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005506 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005507{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005508 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005509 Py_ssize_t startinpos;
5510 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005511 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005512 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005513 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005514 char* message;
5515 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005516 PyObject *errorHandler = NULL;
5517 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005518 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005519 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005520
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005521 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005522
5523 /* After length_of_escaped_ascii_string() there are two alternatives,
5524 either the string is pure ASCII with named escapes like \n, etc.
5525 and we determined it's exact size (common case)
5526 or it contains \x, \u, ... escape sequences. then we create a
5527 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005528 if (len >= 0) {
5529 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005530 if (!v)
5531 goto onError;
5532 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005533 }
5534 else {
5535 /* Escaped strings will always be longer than the resulting
5536 Unicode string, so we start with size here and then reduce the
5537 length after conversion to the true value.
5538 (but if the error callback returns a long replacement string
5539 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005540 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005541 if (!v)
5542 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005543 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544 }
5545
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005547 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005548 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005549 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005550
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551 while (s < end) {
5552 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005553 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005554 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005555
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005556 /* The only case in which i == ascii_length is a backslash
5557 followed by a newline. */
5558 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005559
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560 /* Non-escape characters are interpreted as Unicode ordinals */
5561 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005562 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5563 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564 continue;
5565 }
5566
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005567 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568 /* \ - Escapes */
5569 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005570 c = *s++;
5571 if (s > end)
5572 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005573
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005574 /* The only case in which i == ascii_length is a backslash
5575 followed by a newline. */
5576 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005577
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005578 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005579
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005581#define WRITECHAR(ch) \
5582 do { \
5583 if (unicode_putchar(&v, &i, ch) < 0) \
5584 goto onError; \
5585 }while(0)
5586
Guido van Rossumd57fd912000-03-10 22:53:23 +00005587 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588 case '\\': WRITECHAR('\\'); break;
5589 case '\'': WRITECHAR('\''); break;
5590 case '\"': WRITECHAR('\"'); break;
5591 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005592 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005593 case 'f': WRITECHAR('\014'); break;
5594 case 't': WRITECHAR('\t'); break;
5595 case 'n': WRITECHAR('\n'); break;
5596 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005597 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005598 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005599 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005600 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601
Benjamin Peterson29060642009-01-31 22:14:21 +00005602 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005603 case '0': case '1': case '2': case '3':
5604 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005605 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005606 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005607 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005608 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005609 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005611 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612 break;
5613
Benjamin Peterson29060642009-01-31 22:14:21 +00005614 /* hex escapes */
5615 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005616 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005617 digits = 2;
5618 message = "truncated \\xXX escape";
5619 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620
Benjamin Peterson29060642009-01-31 22:14:21 +00005621 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005623 digits = 4;
5624 message = "truncated \\uXXXX escape";
5625 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005628 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005629 digits = 8;
5630 message = "truncated \\UXXXXXXXX escape";
5631 hexescape:
5632 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005633 if (s+digits>end) {
5634 endinpos = size;
5635 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005636 errors, &errorHandler,
5637 "unicodeescape", "end of string in escape sequence",
5638 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005639 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005640 goto onError;
5641 goto nextByte;
5642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005643 for (j = 0; j < digits; ++j) {
5644 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005645 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005646 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005647 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005648 errors, &errorHandler,
5649 "unicodeescape", message,
5650 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005651 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005652 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005653 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005654 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005655 }
5656 chr = (chr<<4) & ~0xF;
5657 if (c >= '0' && c <= '9')
5658 chr += c - '0';
5659 else if (c >= 'a' && c <= 'f')
5660 chr += 10 + c - 'a';
5661 else
5662 chr += 10 + c - 'A';
5663 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005664 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005665 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 /* _decoding_error will have already written into the
5667 target buffer. */
5668 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005669 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005670 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005671 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005672 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005673 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005675 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005676 errors, &errorHandler,
5677 "unicodeescape", "illegal Unicode character",
5678 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005679 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005680 goto onError;
5681 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005682 break;
5683
Benjamin Peterson29060642009-01-31 22:14:21 +00005684 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005685 case 'N':
5686 message = "malformed \\N character escape";
5687 if (ucnhash_CAPI == NULL) {
5688 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005689 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5690 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005691 if (ucnhash_CAPI == NULL)
5692 goto ucnhashError;
5693 }
5694 if (*s == '{') {
5695 const char *start = s+1;
5696 /* look for the closing brace */
5697 while (*s != '}' && s < end)
5698 s++;
5699 if (s > start && s < end && *s == '}') {
5700 /* found a name. look it up in the unicode database */
5701 message = "unknown Unicode character name";
5702 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005703 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005704 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005705 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005706 goto store;
5707 }
5708 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005709 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005710 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 errors, &errorHandler,
5712 "unicodeescape", message,
5713 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005714 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005715 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005716 break;
5717
5718 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005719 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005720 message = "\\ at end of string";
5721 s--;
5722 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005723 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 errors, &errorHandler,
5725 "unicodeescape", message,
5726 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005727 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005728 goto onError;
5729 }
5730 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005731 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005732 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005733 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005734 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005736 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005739#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005740
Victor Stinner16e6a802011-12-12 13:24:15 +01005741 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005742 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005743 Py_XDECREF(errorHandler);
5744 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005745 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005746
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005748 PyErr_SetString(
5749 PyExc_UnicodeError,
5750 "\\N escapes not supported (can't load unicodedata module)"
5751 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005752 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005753 Py_XDECREF(errorHandler);
5754 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005755 return NULL;
5756
Benjamin Peterson29060642009-01-31 22:14:21 +00005757 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005758 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 Py_XDECREF(errorHandler);
5760 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761 return NULL;
5762}
5763
5764/* Return a Unicode-Escape string version of the Unicode object.
5765
5766 If quotes is true, the string is enclosed in u"" or u'' quotes as
5767 appropriate.
5768
5769*/
5770
Alexander Belopolsky40018472011-02-26 01:02:56 +00005771PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005772PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005774 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005775 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005776 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005777 int kind;
5778 void *data;
5779 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780
Ezio Melottie7f90372012-10-05 03:33:31 +03005781 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005782 escape.
5783
Ezio Melottie7f90372012-10-05 03:33:31 +03005784 For UCS1 strings it's '\xxx', 4 bytes per source character.
5785 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5786 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005787 */
5788
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005789 if (!PyUnicode_Check(unicode)) {
5790 PyErr_BadArgument();
5791 return NULL;
5792 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005793 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005794 return NULL;
5795 len = PyUnicode_GET_LENGTH(unicode);
5796 kind = PyUnicode_KIND(unicode);
5797 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005798 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005799 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5800 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5801 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5802 }
5803
5804 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005805 return PyBytes_FromStringAndSize(NULL, 0);
5806
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005807 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005808 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005809
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005810 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005811 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005812 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005813 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005814 if (repr == NULL)
5815 return NULL;
5816
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005817 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005819 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005820 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005821
Walter Dörwald79e913e2007-05-12 11:08:06 +00005822 /* Escape backslashes */
5823 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005824 *p++ = '\\';
5825 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005826 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005827 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005828
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005829 /* Map 21-bit characters to '\U00xxxxxx' */
5830 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005831 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005832 *p++ = '\\';
5833 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005834 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5835 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5836 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5837 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5838 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5839 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5840 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5841 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005842 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005843 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005844
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005846 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005847 *p++ = '\\';
5848 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005849 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5850 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5851 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5852 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005854
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005855 /* Map special whitespace to '\t', \n', '\r' */
5856 else if (ch == '\t') {
5857 *p++ = '\\';
5858 *p++ = 't';
5859 }
5860 else if (ch == '\n') {
5861 *p++ = '\\';
5862 *p++ = 'n';
5863 }
5864 else if (ch == '\r') {
5865 *p++ = '\\';
5866 *p++ = 'r';
5867 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005868
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005869 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005870 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005872 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005873 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5874 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005875 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005876
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 /* Copy everything else as-is */
5878 else
5879 *p++ = (char) ch;
5880 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005882 assert(p - PyBytes_AS_STRING(repr) > 0);
5883 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5884 return NULL;
5885 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886}
5887
Alexander Belopolsky40018472011-02-26 01:02:56 +00005888PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5890 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005892 PyObject *result;
5893 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5894 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005896 result = PyUnicode_AsUnicodeEscapeString(tmp);
5897 Py_DECREF(tmp);
5898 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899}
5900
5901/* --- Raw Unicode Escape Codec ------------------------------------------- */
5902
Alexander Belopolsky40018472011-02-26 01:02:56 +00005903PyObject *
5904PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005905 Py_ssize_t size,
5906 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005909 Py_ssize_t startinpos;
5910 Py_ssize_t endinpos;
5911 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005912 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 const char *end;
5914 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005915 PyObject *errorHandler = NULL;
5916 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005917
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 /* Escaped strings will always be longer than the resulting
5919 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005920 length after conversion to the true value. (But decoding error
5921 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005922 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005924 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005926 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005927 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 end = s + size;
5929 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 unsigned char c;
5931 Py_UCS4 x;
5932 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005933 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 /* Non-escape characters are interpreted as Unicode ordinals */
5936 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005937 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5938 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005940 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 startinpos = s-starts;
5942
5943 /* \u-escapes are only interpreted iff the number of leading
5944 backslashes if odd */
5945 bs = s;
5946 for (;s < end;) {
5947 if (*s != '\\')
5948 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005949 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5950 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 }
5952 if (((s - bs) & 1) == 0 ||
5953 s >= end ||
5954 (*s != 'u' && *s != 'U')) {
5955 continue;
5956 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005957 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 count = *s=='u' ? 4 : 8;
5959 s++;
5960
5961 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 for (x = 0, i = 0; i < count; ++i, ++s) {
5963 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005964 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 endinpos = s-starts;
5966 if (unicode_decode_call_errorhandler(
5967 errors, &errorHandler,
5968 "rawunicodeescape", "truncated \\uXXXX",
5969 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005970 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005971 goto onError;
5972 goto nextByte;
5973 }
5974 x = (x<<4) & ~0xF;
5975 if (c >= '0' && c <= '9')
5976 x += c - '0';
5977 else if (c >= 'a' && c <= 'f')
5978 x += 10 + c - 'a';
5979 else
5980 x += 10 + c - 'A';
5981 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005982 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005983 if (unicode_putchar(&v, &outpos, x) < 0)
5984 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005985 } else {
5986 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005987 if (unicode_decode_call_errorhandler(
5988 errors, &errorHandler,
5989 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005991 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005992 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005993 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 nextByte:
5995 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005997 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005999 Py_XDECREF(errorHandler);
6000 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006001 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006002
Benjamin Peterson29060642009-01-31 22:14:21 +00006003 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006005 Py_XDECREF(errorHandler);
6006 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007 return NULL;
6008}
6009
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006010
Alexander Belopolsky40018472011-02-26 01:02:56 +00006011PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006012PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006014 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 char *p;
6016 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006017 Py_ssize_t expandsize, pos;
6018 int kind;
6019 void *data;
6020 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006022 if (!PyUnicode_Check(unicode)) {
6023 PyErr_BadArgument();
6024 return NULL;
6025 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006026 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006027 return NULL;
6028 kind = PyUnicode_KIND(unicode);
6029 data = PyUnicode_DATA(unicode);
6030 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006031 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6032 bytes, and 1 byte characters 4. */
6033 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006034
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006035 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006036 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006037
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 if (repr == NULL)
6040 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006041 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006042 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006044 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006045 for (pos = 0; pos < len; pos++) {
6046 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006047 /* Map 32-bit characters to '\Uxxxxxxxx' */
6048 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006049 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006050 *p++ = '\\';
6051 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006052 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6053 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6054 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6055 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6056 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6057 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6058 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6059 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006060 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006062 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 *p++ = '\\';
6064 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006065 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6066 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6067 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6068 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 /* Copy everything else as-is */
6071 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 *p++ = (char) ch;
6073 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006074
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006075 assert(p > q);
6076 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006077 return NULL;
6078 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079}
6080
Alexander Belopolsky40018472011-02-26 01:02:56 +00006081PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006082PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6083 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006085 PyObject *result;
6086 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6087 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006088 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006089 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6090 Py_DECREF(tmp);
6091 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092}
6093
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006094/* --- Unicode Internal Codec ------------------------------------------- */
6095
Alexander Belopolsky40018472011-02-26 01:02:56 +00006096PyObject *
6097_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006098 Py_ssize_t size,
6099 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006100{
6101 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006102 Py_ssize_t startinpos;
6103 Py_ssize_t endinpos;
6104 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006105 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006106 const char *end;
6107 const char *reason;
6108 PyObject *errorHandler = NULL;
6109 PyObject *exc = NULL;
6110
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006111 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006112 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006113 1))
6114 return NULL;
6115
Thomas Wouters89f507f2006-12-13 04:49:30 +00006116 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006117 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006118 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006120 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006121 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006122 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006123 end = s + size;
6124
6125 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006126 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006127 Py_UCS4 ch;
6128 /* We copy the raw representation one byte at a time because the
6129 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006130 ((char *) &uch)[0] = s[0];
6131 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006132#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006133 ((char *) &uch)[2] = s[2];
6134 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006135#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006136 ch = uch;
6137
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006138 /* We have to sanity check the raw data, otherwise doom looms for
6139 some malformed UCS-4 data. */
6140 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006141#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006142 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006143#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006144 end-s < Py_UNICODE_SIZE
6145 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006146 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006147 startinpos = s - starts;
6148 if (end-s < Py_UNICODE_SIZE) {
6149 endinpos = end-starts;
6150 reason = "truncated input";
6151 }
6152 else {
6153 endinpos = s - starts + Py_UNICODE_SIZE;
6154 reason = "illegal code point (> 0x10FFFF)";
6155 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006156 if (unicode_decode_call_errorhandler(
6157 errors, &errorHandler,
6158 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006159 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006160 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006161 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006162 continue;
6163 }
6164
6165 s += Py_UNICODE_SIZE;
6166#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006167 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006168 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006169 Py_UNICODE uch2;
6170 ((char *) &uch2)[0] = s[0];
6171 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006172 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006173 {
Victor Stinner551ac952011-11-29 22:58:13 +01006174 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006175 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006176 }
6177 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006178#endif
6179
6180 if (unicode_putchar(&v, &outpos, ch) < 0)
6181 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006182 }
6183
Victor Stinner16e6a802011-12-12 13:24:15 +01006184 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006185 goto onError;
6186 Py_XDECREF(errorHandler);
6187 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006188 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006189
Benjamin Peterson29060642009-01-31 22:14:21 +00006190 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006191 Py_XDECREF(v);
6192 Py_XDECREF(errorHandler);
6193 Py_XDECREF(exc);
6194 return NULL;
6195}
6196
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197/* --- Latin-1 Codec ------------------------------------------------------ */
6198
Alexander Belopolsky40018472011-02-26 01:02:56 +00006199PyObject *
6200PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006201 Py_ssize_t size,
6202 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006204 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006205 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206}
6207
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006208/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006209static void
6210make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006211 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006212 PyObject *unicode,
6213 Py_ssize_t startpos, Py_ssize_t endpos,
6214 const char *reason)
6215{
6216 if (*exceptionObject == NULL) {
6217 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006218 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006219 encoding, unicode, startpos, endpos, reason);
6220 }
6221 else {
6222 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6223 goto onError;
6224 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6225 goto onError;
6226 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6227 goto onError;
6228 return;
6229 onError:
6230 Py_DECREF(*exceptionObject);
6231 *exceptionObject = NULL;
6232 }
6233}
6234
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006235/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006236static void
6237raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006238 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006239 PyObject *unicode,
6240 Py_ssize_t startpos, Py_ssize_t endpos,
6241 const char *reason)
6242{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006243 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006244 encoding, unicode, startpos, endpos, reason);
6245 if (*exceptionObject != NULL)
6246 PyCodec_StrictErrors(*exceptionObject);
6247}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006248
6249/* error handling callback helper:
6250 build arguments, call the callback and check the arguments,
6251 put the result into newpos and return the replacement string, which
6252 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006253static PyObject *
6254unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006255 PyObject **errorHandler,
6256 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006257 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006258 Py_ssize_t startpos, Py_ssize_t endpos,
6259 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006260{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006261 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006262 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006263 PyObject *restuple;
6264 PyObject *resunicode;
6265
6266 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006268 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006270 }
6271
Benjamin Petersonbac79492012-01-14 13:34:47 -05006272 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006273 return NULL;
6274 len = PyUnicode_GET_LENGTH(unicode);
6275
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006276 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006277 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006278 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280
6281 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006283 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006284 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006285 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006286 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 Py_DECREF(restuple);
6288 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006289 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006290 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 &resunicode, newpos)) {
6292 Py_DECREF(restuple);
6293 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006294 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006295 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6296 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6297 Py_DECREF(restuple);
6298 return NULL;
6299 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006300 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006301 *newpos = len + *newpos;
6302 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6304 Py_DECREF(restuple);
6305 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006306 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006307 Py_INCREF(resunicode);
6308 Py_DECREF(restuple);
6309 return resunicode;
6310}
6311
Alexander Belopolsky40018472011-02-26 01:02:56 +00006312static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006313unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006314 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006315 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006316{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006317 /* input state */
6318 Py_ssize_t pos=0, size;
6319 int kind;
6320 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006321 /* output object */
6322 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006323 /* pointer into the output */
6324 char *str;
6325 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006326 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006327 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6328 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006329 PyObject *errorHandler = NULL;
6330 PyObject *exc = NULL;
6331 /* the following variable is used for caching string comparisons
6332 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6333 int known_errorHandler = -1;
6334
Benjamin Petersonbac79492012-01-14 13:34:47 -05006335 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006336 return NULL;
6337 size = PyUnicode_GET_LENGTH(unicode);
6338 kind = PyUnicode_KIND(unicode);
6339 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340 /* allocate enough for a simple encoding without
6341 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006342 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006343 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006344 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006345 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006346 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006347 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006348 ressize = size;
6349
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006350 while (pos < size) {
6351 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006352
Benjamin Peterson29060642009-01-31 22:14:21 +00006353 /* can we encode this? */
6354 if (c<limit) {
6355 /* no overflow check, because we know that the space is enough */
6356 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006358 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006359 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 Py_ssize_t requiredsize;
6361 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006362 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006364 Py_ssize_t collstart = pos;
6365 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006367 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 ++collend;
6369 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6370 if (known_errorHandler==-1) {
6371 if ((errors==NULL) || (!strcmp(errors, "strict")))
6372 known_errorHandler = 1;
6373 else if (!strcmp(errors, "replace"))
6374 known_errorHandler = 2;
6375 else if (!strcmp(errors, "ignore"))
6376 known_errorHandler = 3;
6377 else if (!strcmp(errors, "xmlcharrefreplace"))
6378 known_errorHandler = 4;
6379 else
6380 known_errorHandler = 0;
6381 }
6382 switch (known_errorHandler) {
6383 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006384 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006385 goto onError;
6386 case 2: /* replace */
6387 while (collstart++<collend)
6388 *str++ = '?'; /* fall through */
6389 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006390 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 break;
6392 case 4: /* xmlcharrefreplace */
6393 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006394 /* determine replacement size */
6395 for (i = collstart, repsize = 0; i < collend; ++i) {
6396 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6397 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006398 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006399 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006401 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006404 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006405 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006407 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006409 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006410 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006411 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006412 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006414 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 if (requiredsize > ressize) {
6416 if (requiredsize<2*ressize)
6417 requiredsize = 2*ressize;
6418 if (_PyBytes_Resize(&res, requiredsize))
6419 goto onError;
6420 str = PyBytes_AS_STRING(res) + respos;
6421 ressize = requiredsize;
6422 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006423 /* generate replacement */
6424 for (i = collstart; i < collend; ++i) {
6425 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006427 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 break;
6429 default:
6430 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006431 encoding, reason, unicode, &exc,
6432 collstart, collend, &newpos);
6433 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006434 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006435 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006436 if (PyBytes_Check(repunicode)) {
6437 /* Directly copy bytes result to output. */
6438 repsize = PyBytes_Size(repunicode);
6439 if (repsize > 1) {
6440 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006441 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006442 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6443 Py_DECREF(repunicode);
6444 goto onError;
6445 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006446 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006447 ressize += repsize-1;
6448 }
6449 memcpy(str, PyBytes_AsString(repunicode), repsize);
6450 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006452 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006453 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006454 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 /* need more space? (at least enough for what we
6456 have+the replacement+the rest of the string, so
6457 we won't have to check space for encodable characters) */
6458 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 repsize = PyUnicode_GET_LENGTH(repunicode);
6460 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 if (requiredsize > ressize) {
6462 if (requiredsize<2*ressize)
6463 requiredsize = 2*ressize;
6464 if (_PyBytes_Resize(&res, requiredsize)) {
6465 Py_DECREF(repunicode);
6466 goto onError;
6467 }
6468 str = PyBytes_AS_STRING(res) + respos;
6469 ressize = requiredsize;
6470 }
6471 /* check if there is anything unencodable in the replacement
6472 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006473 for (i = 0; repsize-->0; ++i, ++str) {
6474 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006476 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006477 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 Py_DECREF(repunicode);
6479 goto onError;
6480 }
6481 *str = (char)c;
6482 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006484 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006485 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006486 }
6487 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006488 /* Resize if we allocated to much */
6489 size = str - PyBytes_AS_STRING(res);
6490 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006491 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006492 if (_PyBytes_Resize(&res, size) < 0)
6493 goto onError;
6494 }
6495
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006496 Py_XDECREF(errorHandler);
6497 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006498 return res;
6499
6500 onError:
6501 Py_XDECREF(res);
6502 Py_XDECREF(errorHandler);
6503 Py_XDECREF(exc);
6504 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006505}
6506
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006508PyObject *
6509PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006510 Py_ssize_t size,
6511 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006513 PyObject *result;
6514 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6515 if (unicode == NULL)
6516 return NULL;
6517 result = unicode_encode_ucs1(unicode, errors, 256);
6518 Py_DECREF(unicode);
6519 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006520}
6521
Alexander Belopolsky40018472011-02-26 01:02:56 +00006522PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006523_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524{
6525 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 PyErr_BadArgument();
6527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006528 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006529 if (PyUnicode_READY(unicode) == -1)
6530 return NULL;
6531 /* Fast path: if it is a one-byte string, construct
6532 bytes object directly. */
6533 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6534 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6535 PyUnicode_GET_LENGTH(unicode));
6536 /* Non-Latin-1 characters present. Defer to above function to
6537 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006538 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006539}
6540
6541PyObject*
6542PyUnicode_AsLatin1String(PyObject *unicode)
6543{
6544 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006545}
6546
6547/* --- 7-bit ASCII Codec -------------------------------------------------- */
6548
Alexander Belopolsky40018472011-02-26 01:02:56 +00006549PyObject *
6550PyUnicode_DecodeASCII(const char *s,
6551 Py_ssize_t size,
6552 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006553{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006554 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006555 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006556 int kind;
6557 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006558 Py_ssize_t startinpos;
6559 Py_ssize_t endinpos;
6560 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006561 const char *e;
6562 PyObject *errorHandler = NULL;
6563 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006564
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006566 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006567
Guido van Rossumd57fd912000-03-10 22:53:23 +00006568 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006569 if (size == 1 && (unsigned char)s[0] < 128)
6570 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006571
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006572 unicode = PyUnicode_New(size, 127);
6573 if (unicode == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006574 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006575
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006577 data = PyUnicode_1BYTE_DATA(unicode);
6578 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6579 if (outpos == size)
6580 return unicode;
6581
6582 s += outpos;
6583 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 register unsigned char c = (unsigned char)*s;
6586 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006587 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 ++s;
6589 }
6590 else {
6591 startinpos = s-starts;
6592 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 if (unicode_decode_call_errorhandler(
6594 errors, &errorHandler,
6595 "ascii", "ordinal not in range(128)",
6596 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006597 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006599 kind = PyUnicode_KIND(unicode);
6600 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006602 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006603 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006604 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006605 Py_XDECREF(errorHandler);
6606 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006607 assert(_PyUnicode_CheckConsistency(unicode, 1));
6608 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006609
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006611 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006612 Py_XDECREF(errorHandler);
6613 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006614 return NULL;
6615}
6616
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006618PyObject *
6619PyUnicode_EncodeASCII(const Py_UNICODE *p,
6620 Py_ssize_t size,
6621 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006623 PyObject *result;
6624 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6625 if (unicode == NULL)
6626 return NULL;
6627 result = unicode_encode_ucs1(unicode, errors, 128);
6628 Py_DECREF(unicode);
6629 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006630}
6631
Alexander Belopolsky40018472011-02-26 01:02:56 +00006632PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006633_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006634{
6635 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 PyErr_BadArgument();
6637 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006639 if (PyUnicode_READY(unicode) == -1)
6640 return NULL;
6641 /* Fast path: if it is an ASCII-only string, construct bytes object
6642 directly. Else defer to above function to raise the exception. */
6643 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6644 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6645 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006647}
6648
6649PyObject *
6650PyUnicode_AsASCIIString(PyObject *unicode)
6651{
6652 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653}
6654
Victor Stinner99b95382011-07-04 14:23:54 +02006655#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006656
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006657/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006658
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006659#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006660#define NEED_RETRY
6661#endif
6662
Victor Stinner3a50e702011-10-18 21:21:00 +02006663#ifndef WC_ERR_INVALID_CHARS
6664# define WC_ERR_INVALID_CHARS 0x0080
6665#endif
6666
6667static char*
6668code_page_name(UINT code_page, PyObject **obj)
6669{
6670 *obj = NULL;
6671 if (code_page == CP_ACP)
6672 return "mbcs";
6673 if (code_page == CP_UTF7)
6674 return "CP_UTF7";
6675 if (code_page == CP_UTF8)
6676 return "CP_UTF8";
6677
6678 *obj = PyBytes_FromFormat("cp%u", code_page);
6679 if (*obj == NULL)
6680 return NULL;
6681 return PyBytes_AS_STRING(*obj);
6682}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006683
Alexander Belopolsky40018472011-02-26 01:02:56 +00006684static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006685is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006686{
6687 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006688 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006689
Victor Stinner3a50e702011-10-18 21:21:00 +02006690 if (!IsDBCSLeadByteEx(code_page, *curr))
6691 return 0;
6692
6693 prev = CharPrevExA(code_page, s, curr, 0);
6694 if (prev == curr)
6695 return 1;
6696 /* FIXME: This code is limited to "true" double-byte encodings,
6697 as it assumes an incomplete character consists of a single
6698 byte. */
6699 if (curr - prev == 2)
6700 return 1;
6701 if (!IsDBCSLeadByteEx(code_page, *prev))
6702 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006703 return 0;
6704}
6705
Victor Stinner3a50e702011-10-18 21:21:00 +02006706static DWORD
6707decode_code_page_flags(UINT code_page)
6708{
6709 if (code_page == CP_UTF7) {
6710 /* The CP_UTF7 decoder only supports flags=0 */
6711 return 0;
6712 }
6713 else
6714 return MB_ERR_INVALID_CHARS;
6715}
6716
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006717/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006718 * Decode a byte string from a Windows code page into unicode object in strict
6719 * mode.
6720 *
6721 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6722 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006723 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006724static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006725decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006726 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006727 const char *in,
6728 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006729{
Victor Stinner3a50e702011-10-18 21:21:00 +02006730 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006731 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006732 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006733
6734 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006735 assert(insize > 0);
6736 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6737 if (outsize <= 0)
6738 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006739
6740 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006742 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006743 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 if (*v == NULL)
6745 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006746 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006747 }
6748 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006750 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006751 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006753 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006754 }
6755
6756 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006757 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6758 if (outsize <= 0)
6759 goto error;
6760 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006761
Victor Stinner3a50e702011-10-18 21:21:00 +02006762error:
6763 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6764 return -2;
6765 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006766 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006767}
6768
Victor Stinner3a50e702011-10-18 21:21:00 +02006769/*
6770 * Decode a byte string from a code page into unicode object with an error
6771 * handler.
6772 *
6773 * Returns consumed size if succeed, or raise a WindowsError or
6774 * UnicodeDecodeError exception and returns -1 on error.
6775 */
6776static int
6777decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006778 PyObject **v,
6779 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006780 const char *errors)
6781{
6782 const char *startin = in;
6783 const char *endin = in + size;
6784 const DWORD flags = decode_code_page_flags(code_page);
6785 /* Ideally, we should get reason from FormatMessage. This is the Windows
6786 2000 English version of the message. */
6787 const char *reason = "No mapping for the Unicode character exists "
6788 "in the target code page.";
6789 /* each step cannot decode more than 1 character, but a character can be
6790 represented as a surrogate pair */
6791 wchar_t buffer[2], *startout, *out;
6792 int insize, outsize;
6793 PyObject *errorHandler = NULL;
6794 PyObject *exc = NULL;
6795 PyObject *encoding_obj = NULL;
6796 char *encoding;
6797 DWORD err;
6798 int ret = -1;
6799
6800 assert(size > 0);
6801
6802 encoding = code_page_name(code_page, &encoding_obj);
6803 if (encoding == NULL)
6804 return -1;
6805
6806 if (errors == NULL || strcmp(errors, "strict") == 0) {
6807 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6808 UnicodeDecodeError. */
6809 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6810 if (exc != NULL) {
6811 PyCodec_StrictErrors(exc);
6812 Py_CLEAR(exc);
6813 }
6814 goto error;
6815 }
6816
6817 if (*v == NULL) {
6818 /* Create unicode object */
6819 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6820 PyErr_NoMemory();
6821 goto error;
6822 }
Victor Stinnerab595942011-12-17 04:59:06 +01006823 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006824 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006825 if (*v == NULL)
6826 goto error;
6827 startout = PyUnicode_AS_UNICODE(*v);
6828 }
6829 else {
6830 /* Extend unicode object */
6831 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6832 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6833 PyErr_NoMemory();
6834 goto error;
6835 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006836 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006837 goto error;
6838 startout = PyUnicode_AS_UNICODE(*v) + n;
6839 }
6840
6841 /* Decode the byte string character per character */
6842 out = startout;
6843 while (in < endin)
6844 {
6845 /* Decode a character */
6846 insize = 1;
6847 do
6848 {
6849 outsize = MultiByteToWideChar(code_page, flags,
6850 in, insize,
6851 buffer, Py_ARRAY_LENGTH(buffer));
6852 if (outsize > 0)
6853 break;
6854 err = GetLastError();
6855 if (err != ERROR_NO_UNICODE_TRANSLATION
6856 && err != ERROR_INSUFFICIENT_BUFFER)
6857 {
6858 PyErr_SetFromWindowsErr(0);
6859 goto error;
6860 }
6861 insize++;
6862 }
6863 /* 4=maximum length of a UTF-8 sequence */
6864 while (insize <= 4 && (in + insize) <= endin);
6865
6866 if (outsize <= 0) {
6867 Py_ssize_t startinpos, endinpos, outpos;
6868
6869 startinpos = in - startin;
6870 endinpos = startinpos + 1;
6871 outpos = out - PyUnicode_AS_UNICODE(*v);
6872 if (unicode_decode_call_errorhandler(
6873 errors, &errorHandler,
6874 encoding, reason,
6875 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006876 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006877 {
6878 goto error;
6879 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006880 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006881 }
6882 else {
6883 in += insize;
6884 memcpy(out, buffer, outsize * sizeof(wchar_t));
6885 out += outsize;
6886 }
6887 }
6888
6889 /* write a NUL character at the end */
6890 *out = 0;
6891
6892 /* Extend unicode object */
6893 outsize = out - startout;
6894 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006895 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006896 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006897 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006898
6899error:
6900 Py_XDECREF(encoding_obj);
6901 Py_XDECREF(errorHandler);
6902 Py_XDECREF(exc);
6903 return ret;
6904}
6905
Victor Stinner3a50e702011-10-18 21:21:00 +02006906static PyObject *
6907decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006908 const char *s, Py_ssize_t size,
6909 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910{
Victor Stinner76a31a62011-11-04 00:05:13 +01006911 PyObject *v = NULL;
6912 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006913
Victor Stinner3a50e702011-10-18 21:21:00 +02006914 if (code_page < 0) {
6915 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6916 return NULL;
6917 }
6918
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006919 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006920 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921
Victor Stinner76a31a62011-11-04 00:05:13 +01006922 do
6923 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006924#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006925 if (size > INT_MAX) {
6926 chunk_size = INT_MAX;
6927 final = 0;
6928 done = 0;
6929 }
6930 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006931#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006932 {
6933 chunk_size = (int)size;
6934 final = (consumed == NULL);
6935 done = 1;
6936 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937
Victor Stinner76a31a62011-11-04 00:05:13 +01006938 /* Skip trailing lead-byte unless 'final' is set */
6939 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6940 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006941
Victor Stinner76a31a62011-11-04 00:05:13 +01006942 if (chunk_size == 0 && done) {
6943 if (v != NULL)
6944 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02006945 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01006946 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006947
Victor Stinner76a31a62011-11-04 00:05:13 +01006948
6949 converted = decode_code_page_strict(code_page, &v,
6950 s, chunk_size);
6951 if (converted == -2)
6952 converted = decode_code_page_errors(code_page, &v,
6953 s, chunk_size,
6954 errors);
6955 assert(converted != 0);
6956
6957 if (converted < 0) {
6958 Py_XDECREF(v);
6959 return NULL;
6960 }
6961
6962 if (consumed)
6963 *consumed += converted;
6964
6965 s += converted;
6966 size -= converted;
6967 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006968
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006969 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006970}
6971
Alexander Belopolsky40018472011-02-26 01:02:56 +00006972PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006973PyUnicode_DecodeCodePageStateful(int code_page,
6974 const char *s,
6975 Py_ssize_t size,
6976 const char *errors,
6977 Py_ssize_t *consumed)
6978{
6979 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6980}
6981
6982PyObject *
6983PyUnicode_DecodeMBCSStateful(const char *s,
6984 Py_ssize_t size,
6985 const char *errors,
6986 Py_ssize_t *consumed)
6987{
6988 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6989}
6990
6991PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006992PyUnicode_DecodeMBCS(const char *s,
6993 Py_ssize_t size,
6994 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006995{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006996 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6997}
6998
Victor Stinner3a50e702011-10-18 21:21:00 +02006999static DWORD
7000encode_code_page_flags(UINT code_page, const char *errors)
7001{
7002 if (code_page == CP_UTF8) {
7003 if (winver.dwMajorVersion >= 6)
7004 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7005 and later */
7006 return WC_ERR_INVALID_CHARS;
7007 else
7008 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7009 return 0;
7010 }
7011 else if (code_page == CP_UTF7) {
7012 /* CP_UTF7 only supports flags=0 */
7013 return 0;
7014 }
7015 else {
7016 if (errors != NULL && strcmp(errors, "replace") == 0)
7017 return 0;
7018 else
7019 return WC_NO_BEST_FIT_CHARS;
7020 }
7021}
7022
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007023/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007024 * Encode a Unicode string to a Windows code page into a byte string in strict
7025 * mode.
7026 *
7027 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7028 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007030static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007031encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007032 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034{
Victor Stinner554f3f02010-06-16 23:33:54 +00007035 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007036 BOOL *pusedDefaultChar = &usedDefaultChar;
7037 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007038 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007039 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007040 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007041 const DWORD flags = encode_code_page_flags(code_page, NULL);
7042 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007043 /* Create a substring so that we can get the UTF-16 representation
7044 of just the slice under consideration. */
7045 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046
Martin v. Löwis3d325192011-11-04 18:23:06 +01007047 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007048
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007050 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007052 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007053
Victor Stinner2fc507f2011-11-04 20:06:39 +01007054 substring = PyUnicode_Substring(unicode, offset, offset+len);
7055 if (substring == NULL)
7056 return -1;
7057 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7058 if (p == NULL) {
7059 Py_DECREF(substring);
7060 return -1;
7061 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007062
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007063 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 outsize = WideCharToMultiByte(code_page, flags,
7065 p, size,
7066 NULL, 0,
7067 NULL, pusedDefaultChar);
7068 if (outsize <= 0)
7069 goto error;
7070 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007071 if (pusedDefaultChar && *pusedDefaultChar) {
7072 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007074 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007075
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007077 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007078 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007079 if (*outbytes == NULL) {
7080 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007081 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007082 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084 }
7085 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007087 const Py_ssize_t n = PyBytes_Size(*outbytes);
7088 if (outsize > PY_SSIZE_T_MAX - n) {
7089 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007090 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007093 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7094 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007096 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098 }
7099
7100 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 outsize = WideCharToMultiByte(code_page, flags,
7102 p, size,
7103 out, outsize,
7104 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007105 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007106 if (outsize <= 0)
7107 goto error;
7108 if (pusedDefaultChar && *pusedDefaultChar)
7109 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007111
Victor Stinner3a50e702011-10-18 21:21:00 +02007112error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007113 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007114 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7115 return -2;
7116 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007117 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007118}
7119
Victor Stinner3a50e702011-10-18 21:21:00 +02007120/*
7121 * Encode a Unicode string to a Windows code page into a byte string using a
7122 * error handler.
7123 *
7124 * Returns consumed characters if succeed, or raise a WindowsError and returns
7125 * -1 on other error.
7126 */
7127static int
7128encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007129 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007130 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007131{
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007133 Py_ssize_t pos = unicode_offset;
7134 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 /* Ideally, we should get reason from FormatMessage. This is the Windows
7136 2000 English version of the message. */
7137 const char *reason = "invalid character";
7138 /* 4=maximum length of a UTF-8 sequence */
7139 char buffer[4];
7140 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7141 Py_ssize_t outsize;
7142 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 PyObject *errorHandler = NULL;
7144 PyObject *exc = NULL;
7145 PyObject *encoding_obj = NULL;
7146 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007147 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007148 PyObject *rep;
7149 int ret = -1;
7150
7151 assert(insize > 0);
7152
7153 encoding = code_page_name(code_page, &encoding_obj);
7154 if (encoding == NULL)
7155 return -1;
7156
7157 if (errors == NULL || strcmp(errors, "strict") == 0) {
7158 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7159 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007160 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007161 if (exc != NULL) {
7162 PyCodec_StrictErrors(exc);
7163 Py_DECREF(exc);
7164 }
7165 Py_XDECREF(encoding_obj);
7166 return -1;
7167 }
7168
7169 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7170 pusedDefaultChar = &usedDefaultChar;
7171 else
7172 pusedDefaultChar = NULL;
7173
7174 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7175 PyErr_NoMemory();
7176 goto error;
7177 }
7178 outsize = insize * Py_ARRAY_LENGTH(buffer);
7179
7180 if (*outbytes == NULL) {
7181 /* Create string object */
7182 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7183 if (*outbytes == NULL)
7184 goto error;
7185 out = PyBytes_AS_STRING(*outbytes);
7186 }
7187 else {
7188 /* Extend string object */
7189 Py_ssize_t n = PyBytes_Size(*outbytes);
7190 if (n > PY_SSIZE_T_MAX - outsize) {
7191 PyErr_NoMemory();
7192 goto error;
7193 }
7194 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7195 goto error;
7196 out = PyBytes_AS_STRING(*outbytes) + n;
7197 }
7198
7199 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007200 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007202 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7203 wchar_t chars[2];
7204 int charsize;
7205 if (ch < 0x10000) {
7206 chars[0] = (wchar_t)ch;
7207 charsize = 1;
7208 }
7209 else {
7210 ch -= 0x10000;
7211 chars[0] = 0xd800 + (ch >> 10);
7212 chars[1] = 0xdc00 + (ch & 0x3ff);
7213 charsize = 2;
7214 }
7215
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007217 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 buffer, Py_ARRAY_LENGTH(buffer),
7219 NULL, pusedDefaultChar);
7220 if (outsize > 0) {
7221 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7222 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007223 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 memcpy(out, buffer, outsize);
7225 out += outsize;
7226 continue;
7227 }
7228 }
7229 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7230 PyErr_SetFromWindowsErr(0);
7231 goto error;
7232 }
7233
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 rep = unicode_encode_call_errorhandler(
7235 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007236 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007237 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 if (rep == NULL)
7239 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007240 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007241
7242 if (PyBytes_Check(rep)) {
7243 outsize = PyBytes_GET_SIZE(rep);
7244 if (outsize != 1) {
7245 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7246 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7247 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7248 Py_DECREF(rep);
7249 goto error;
7250 }
7251 out = PyBytes_AS_STRING(*outbytes) + offset;
7252 }
7253 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7254 out += outsize;
7255 }
7256 else {
7257 Py_ssize_t i;
7258 enum PyUnicode_Kind kind;
7259 void *data;
7260
Benjamin Petersonbac79492012-01-14 13:34:47 -05007261 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007262 Py_DECREF(rep);
7263 goto error;
7264 }
7265
7266 outsize = PyUnicode_GET_LENGTH(rep);
7267 if (outsize != 1) {
7268 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7269 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7270 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7271 Py_DECREF(rep);
7272 goto error;
7273 }
7274 out = PyBytes_AS_STRING(*outbytes) + offset;
7275 }
7276 kind = PyUnicode_KIND(rep);
7277 data = PyUnicode_DATA(rep);
7278 for (i=0; i < outsize; i++) {
7279 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7280 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007281 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007282 encoding, unicode,
7283 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 "unable to encode error handler result to ASCII");
7285 Py_DECREF(rep);
7286 goto error;
7287 }
7288 *out = (unsigned char)ch;
7289 out++;
7290 }
7291 }
7292 Py_DECREF(rep);
7293 }
7294 /* write a NUL byte */
7295 *out = 0;
7296 outsize = out - PyBytes_AS_STRING(*outbytes);
7297 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7298 if (_PyBytes_Resize(outbytes, outsize) < 0)
7299 goto error;
7300 ret = 0;
7301
7302error:
7303 Py_XDECREF(encoding_obj);
7304 Py_XDECREF(errorHandler);
7305 Py_XDECREF(exc);
7306 return ret;
7307}
7308
Victor Stinner3a50e702011-10-18 21:21:00 +02007309static PyObject *
7310encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007311 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 const char *errors)
7313{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007314 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007316 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007317 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007318
Benjamin Petersonbac79492012-01-14 13:34:47 -05007319 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007320 return NULL;
7321 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007322
Victor Stinner3a50e702011-10-18 21:21:00 +02007323 if (code_page < 0) {
7324 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7325 return NULL;
7326 }
7327
Martin v. Löwis3d325192011-11-04 18:23:06 +01007328 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007329 return PyBytes_FromStringAndSize(NULL, 0);
7330
Victor Stinner7581cef2011-11-03 22:32:33 +01007331 offset = 0;
7332 do
7333 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007334#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007335 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007336 chunks. */
7337 if (len > INT_MAX/2) {
7338 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 done = 0;
7340 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007341 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007343 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007344 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 done = 1;
7346 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007347
Victor Stinner76a31a62011-11-04 00:05:13 +01007348 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007349 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007350 errors);
7351 if (ret == -2)
7352 ret = encode_code_page_errors(code_page, &outbytes,
7353 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007354 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007355 if (ret < 0) {
7356 Py_XDECREF(outbytes);
7357 return NULL;
7358 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007359
Victor Stinner7581cef2011-11-03 22:32:33 +01007360 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007361 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007362 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007363
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 return outbytes;
7365}
7366
7367PyObject *
7368PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7369 Py_ssize_t size,
7370 const char *errors)
7371{
Victor Stinner7581cef2011-11-03 22:32:33 +01007372 PyObject *unicode, *res;
7373 unicode = PyUnicode_FromUnicode(p, size);
7374 if (unicode == NULL)
7375 return NULL;
7376 res = encode_code_page(CP_ACP, unicode, errors);
7377 Py_DECREF(unicode);
7378 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007379}
7380
7381PyObject *
7382PyUnicode_EncodeCodePage(int code_page,
7383 PyObject *unicode,
7384 const char *errors)
7385{
Victor Stinner7581cef2011-11-03 22:32:33 +01007386 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007387}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007388
Alexander Belopolsky40018472011-02-26 01:02:56 +00007389PyObject *
7390PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007391{
7392 if (!PyUnicode_Check(unicode)) {
7393 PyErr_BadArgument();
7394 return NULL;
7395 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007396 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007397}
7398
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007399#undef NEED_RETRY
7400
Victor Stinner99b95382011-07-04 14:23:54 +02007401#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007402
Guido van Rossumd57fd912000-03-10 22:53:23 +00007403/* --- Character Mapping Codec -------------------------------------------- */
7404
Alexander Belopolsky40018472011-02-26 01:02:56 +00007405PyObject *
7406PyUnicode_DecodeCharmap(const char *s,
7407 Py_ssize_t size,
7408 PyObject *mapping,
7409 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007411 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007412 Py_ssize_t startinpos;
7413 Py_ssize_t endinpos;
7414 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007415 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007416 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007417 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007418 PyObject *errorHandler = NULL;
7419 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007420
Guido van Rossumd57fd912000-03-10 22:53:23 +00007421 /* Default to Latin-1 */
7422 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007423 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007425 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007426 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007427 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007428 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007429 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007430 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007431 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007432 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007433 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007434 enum PyUnicode_Kind mapkind;
7435 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007436 Py_UCS4 x;
7437
Benjamin Petersonbac79492012-01-14 13:34:47 -05007438 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007439 return NULL;
7440
7441 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007442 mapdata = PyUnicode_DATA(mapping);
7443 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007444 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007445 unsigned char ch;
7446 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7447 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7448 if (outkind == PyUnicode_1BYTE_KIND) {
7449 void *outdata = PyUnicode_DATA(v);
7450 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7451 while (s < e) {
7452 unsigned char ch = *s;
7453 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7454 if (x > maxchar)
7455 goto Error;
7456 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7457 ++s;
7458 }
7459 break;
7460 }
7461 else if (outkind == PyUnicode_2BYTE_KIND) {
7462 void *outdata = PyUnicode_DATA(v);
7463 while (s < e) {
7464 unsigned char ch = *s;
7465 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7466 if (x == 0xFFFE)
7467 goto Error;
7468 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7469 ++s;
7470 }
7471 break;
7472 }
7473 }
7474 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007477 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007478 else
7479 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007480Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007481 if (x == 0xfffe)
7482 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007483 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 startinpos = s-starts;
7485 endinpos = startinpos+1;
7486 if (unicode_decode_call_errorhandler(
7487 errors, &errorHandler,
7488 "charmap", "character maps to <undefined>",
7489 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007490 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007491 goto onError;
7492 }
7493 continue;
7494 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007495
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007496 if (unicode_putchar(&v, &outpos, x) < 0)
7497 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007498 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007499 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007500 }
7501 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007502 while (s < e) {
7503 unsigned char ch = *s;
7504 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007505
Benjamin Peterson29060642009-01-31 22:14:21 +00007506 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7507 w = PyLong_FromLong((long)ch);
7508 if (w == NULL)
7509 goto onError;
7510 x = PyObject_GetItem(mapping, w);
7511 Py_DECREF(w);
7512 if (x == NULL) {
7513 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7514 /* No mapping found means: mapping is undefined. */
7515 PyErr_Clear();
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007516 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007517 } else
7518 goto onError;
7519 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007520
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 /* Apply mapping */
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007522 if (x == Py_None)
7523 goto Undefined;
Benjamin Peterson29060642009-01-31 22:14:21 +00007524 if (PyLong_Check(x)) {
7525 long value = PyLong_AS_LONG(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007526 if (value == 0xFFFE)
7527 goto Undefined;
Antoine Pitroua1f76552012-09-23 20:00:04 +02007528 if (value < 0 || value > MAX_UNICODE) {
7529 PyErr_Format(PyExc_TypeError,
7530 "character mapping must be in range(0x%lx)",
7531 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007532 Py_DECREF(x);
7533 goto onError;
7534 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007535 if (unicode_putchar(&v, &outpos, value) < 0)
7536 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007538 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007539 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007540
Benjamin Petersonbac79492012-01-14 13:34:47 -05007541 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007542 goto onError;
7543 targetsize = PyUnicode_GET_LENGTH(x);
7544
7545 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007546 /* 1-1 mapping */
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007547 Py_UCS4 value = PyUnicode_READ_CHAR(x, 0);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007548 if (value == 0xFFFE)
7549 goto Undefined;
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007550 if (unicode_putchar(&v, &outpos, value) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007551 goto onError;
7552 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 else if (targetsize > 1) {
7554 /* 1-n mapping */
7555 if (targetsize > extrachars) {
7556 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007557 Py_ssize_t needed = (targetsize - extrachars) + \
7558 (targetsize << 2);
7559 extrachars += needed;
7560 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007561 if (unicode_resize(&v,
7562 PyUnicode_GET_LENGTH(v) + needed) < 0)
7563 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007564 Py_DECREF(x);
7565 goto onError;
7566 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007568 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007569 goto onError;
7570 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7571 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007572 extrachars -= targetsize;
7573 }
7574 /* 1-0 mapping: skip the character */
7575 }
7576 else {
7577 /* wrong return value */
7578 PyErr_SetString(PyExc_TypeError,
7579 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007580 Py_DECREF(x);
7581 goto onError;
7582 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007583 Py_DECREF(x);
7584 ++s;
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007585 continue;
7586Undefined:
7587 /* undefined mapping */
7588 Py_XDECREF(x);
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007589 startinpos = s-starts;
7590 endinpos = startinpos+1;
7591 if (unicode_decode_call_errorhandler(
7592 errors, &errorHandler,
7593 "charmap", "character maps to <undefined>",
7594 &starts, &e, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka45d16d92013-01-15 15:01:20 +02007595 &v, &outpos)) {
Serhiy Storchaka4fb8cae2013-01-15 14:43:21 +02007596 goto onError;
7597 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007598 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007599 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007600 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007601 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007602 Py_XDECREF(errorHandler);
7603 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007604 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007605
Benjamin Peterson29060642009-01-31 22:14:21 +00007606 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007607 Py_XDECREF(errorHandler);
7608 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007609 Py_XDECREF(v);
7610 return NULL;
7611}
7612
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007613/* Charmap encoding: the lookup table */
7614
Alexander Belopolsky40018472011-02-26 01:02:56 +00007615struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007616 PyObject_HEAD
7617 unsigned char level1[32];
7618 int count2, count3;
7619 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007620};
7621
7622static PyObject*
7623encoding_map_size(PyObject *obj, PyObject* args)
7624{
7625 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007626 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007627 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007628}
7629
7630static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007631 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007632 PyDoc_STR("Return the size (in bytes) of this object") },
7633 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007634};
7635
7636static void
7637encoding_map_dealloc(PyObject* o)
7638{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007639 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007640}
7641
7642static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007643 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007644 "EncodingMap", /*tp_name*/
7645 sizeof(struct encoding_map), /*tp_basicsize*/
7646 0, /*tp_itemsize*/
7647 /* methods */
7648 encoding_map_dealloc, /*tp_dealloc*/
7649 0, /*tp_print*/
7650 0, /*tp_getattr*/
7651 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007652 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007653 0, /*tp_repr*/
7654 0, /*tp_as_number*/
7655 0, /*tp_as_sequence*/
7656 0, /*tp_as_mapping*/
7657 0, /*tp_hash*/
7658 0, /*tp_call*/
7659 0, /*tp_str*/
7660 0, /*tp_getattro*/
7661 0, /*tp_setattro*/
7662 0, /*tp_as_buffer*/
7663 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7664 0, /*tp_doc*/
7665 0, /*tp_traverse*/
7666 0, /*tp_clear*/
7667 0, /*tp_richcompare*/
7668 0, /*tp_weaklistoffset*/
7669 0, /*tp_iter*/
7670 0, /*tp_iternext*/
7671 encoding_map_methods, /*tp_methods*/
7672 0, /*tp_members*/
7673 0, /*tp_getset*/
7674 0, /*tp_base*/
7675 0, /*tp_dict*/
7676 0, /*tp_descr_get*/
7677 0, /*tp_descr_set*/
7678 0, /*tp_dictoffset*/
7679 0, /*tp_init*/
7680 0, /*tp_alloc*/
7681 0, /*tp_new*/
7682 0, /*tp_free*/
7683 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007684};
7685
7686PyObject*
7687PyUnicode_BuildEncodingMap(PyObject* string)
7688{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007689 PyObject *result;
7690 struct encoding_map *mresult;
7691 int i;
7692 int need_dict = 0;
7693 unsigned char level1[32];
7694 unsigned char level2[512];
7695 unsigned char *mlevel1, *mlevel2, *mlevel3;
7696 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007697 int kind;
7698 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007699 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007700 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007702 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007703 PyErr_BadArgument();
7704 return NULL;
7705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007706 kind = PyUnicode_KIND(string);
7707 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007708 length = PyUnicode_GET_LENGTH(string);
7709 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007710 memset(level1, 0xFF, sizeof level1);
7711 memset(level2, 0xFF, sizeof level2);
7712
7713 /* If there isn't a one-to-one mapping of NULL to \0,
7714 or if there are non-BMP characters, we need to use
7715 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007716 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007717 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007718 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007719 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007720 ch = PyUnicode_READ(kind, data, i);
7721 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007722 need_dict = 1;
7723 break;
7724 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007725 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007726 /* unmapped character */
7727 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007728 l1 = ch >> 11;
7729 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007730 if (level1[l1] == 0xFF)
7731 level1[l1] = count2++;
7732 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007733 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007734 }
7735
7736 if (count2 >= 0xFF || count3 >= 0xFF)
7737 need_dict = 1;
7738
7739 if (need_dict) {
7740 PyObject *result = PyDict_New();
7741 PyObject *key, *value;
7742 if (!result)
7743 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007744 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007745 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007746 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007747 if (!key || !value)
7748 goto failed1;
7749 if (PyDict_SetItem(result, key, value) == -1)
7750 goto failed1;
7751 Py_DECREF(key);
7752 Py_DECREF(value);
7753 }
7754 return result;
7755 failed1:
7756 Py_XDECREF(key);
7757 Py_XDECREF(value);
7758 Py_DECREF(result);
7759 return NULL;
7760 }
7761
7762 /* Create a three-level trie */
7763 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7764 16*count2 + 128*count3 - 1);
7765 if (!result)
7766 return PyErr_NoMemory();
7767 PyObject_Init(result, &EncodingMapType);
7768 mresult = (struct encoding_map*)result;
7769 mresult->count2 = count2;
7770 mresult->count3 = count3;
7771 mlevel1 = mresult->level1;
7772 mlevel2 = mresult->level23;
7773 mlevel3 = mresult->level23 + 16*count2;
7774 memcpy(mlevel1, level1, 32);
7775 memset(mlevel2, 0xFF, 16*count2);
7776 memset(mlevel3, 0, 128*count3);
7777 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007778 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007779 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007780 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7781 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007782 /* unmapped character */
7783 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007784 o1 = ch>>11;
7785 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007786 i2 = 16*mlevel1[o1] + o2;
7787 if (mlevel2[i2] == 0xFF)
7788 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007789 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007790 i3 = 128*mlevel2[i2] + o3;
7791 mlevel3[i3] = i;
7792 }
7793 return result;
7794}
7795
7796static int
Victor Stinner22168992011-11-20 17:09:18 +01007797encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007798{
7799 struct encoding_map *map = (struct encoding_map*)mapping;
7800 int l1 = c>>11;
7801 int l2 = (c>>7) & 0xF;
7802 int l3 = c & 0x7F;
7803 int i;
7804
Victor Stinner22168992011-11-20 17:09:18 +01007805 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007807 if (c == 0)
7808 return 0;
7809 /* level 1*/
7810 i = map->level1[l1];
7811 if (i == 0xFF) {
7812 return -1;
7813 }
7814 /* level 2*/
7815 i = map->level23[16*i+l2];
7816 if (i == 0xFF) {
7817 return -1;
7818 }
7819 /* level 3 */
7820 i = map->level23[16*map->count2 + 128*i + l3];
7821 if (i == 0) {
7822 return -1;
7823 }
7824 return i;
7825}
7826
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007827/* Lookup the character ch in the mapping. If the character
7828 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007829 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007830static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007831charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007832{
Christian Heimes217cfd12007-12-02 14:31:20 +00007833 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007834 PyObject *x;
7835
7836 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007837 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007838 x = PyObject_GetItem(mapping, w);
7839 Py_DECREF(w);
7840 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7842 /* No mapping found means: mapping is undefined. */
7843 PyErr_Clear();
7844 x = Py_None;
7845 Py_INCREF(x);
7846 return x;
7847 } else
7848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007849 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007850 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007852 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007853 long value = PyLong_AS_LONG(x);
7854 if (value < 0 || value > 255) {
7855 PyErr_SetString(PyExc_TypeError,
7856 "character mapping must be in range(256)");
7857 Py_DECREF(x);
7858 return NULL;
7859 }
7860 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007861 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007862 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007863 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007864 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 /* wrong return value */
7866 PyErr_Format(PyExc_TypeError,
7867 "character mapping must return integer, bytes or None, not %.400s",
7868 x->ob_type->tp_name);
7869 Py_DECREF(x);
7870 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007871 }
7872}
7873
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007875charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007876{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007877 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7878 /* exponentially overallocate to minimize reallocations */
7879 if (requiredsize < 2*outsize)
7880 requiredsize = 2*outsize;
7881 if (_PyBytes_Resize(outobj, requiredsize))
7882 return -1;
7883 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884}
7885
Benjamin Peterson14339b62009-01-31 16:36:08 +00007886typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007888} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007889/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007890 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007891 space is available. Return a new reference to the object that
7892 was put in the output buffer, or Py_None, if the mapping was undefined
7893 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007894 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007895static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007896charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007897 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007898{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899 PyObject *rep;
7900 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007901 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007902
Christian Heimes90aa7642007-12-19 02:45:37 +00007903 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007905 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007906 if (res == -1)
7907 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007908 if (outsize<requiredsize)
7909 if (charmapencode_resize(outobj, outpos, requiredsize))
7910 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007911 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007912 outstart[(*outpos)++] = (char)res;
7913 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007914 }
7915
7916 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007919 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007920 Py_DECREF(rep);
7921 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007922 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007923 if (PyLong_Check(rep)) {
7924 Py_ssize_t requiredsize = *outpos+1;
7925 if (outsize<requiredsize)
7926 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7927 Py_DECREF(rep);
7928 return enc_EXCEPTION;
7929 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007930 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007931 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007932 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007933 else {
7934 const char *repchars = PyBytes_AS_STRING(rep);
7935 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7936 Py_ssize_t requiredsize = *outpos+repsize;
7937 if (outsize<requiredsize)
7938 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7939 Py_DECREF(rep);
7940 return enc_EXCEPTION;
7941 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007942 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007943 memcpy(outstart + *outpos, repchars, repsize);
7944 *outpos += repsize;
7945 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007946 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947 Py_DECREF(rep);
7948 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007949}
7950
7951/* handle an error in PyUnicode_EncodeCharmap
7952 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007953static int
7954charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007955 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007956 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007957 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007958 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007959{
7960 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007961 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007962 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007963 enum PyUnicode_Kind kind;
7964 void *data;
7965 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007966 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007967 Py_ssize_t collstartpos = *inpos;
7968 Py_ssize_t collendpos = *inpos+1;
7969 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007970 char *encoding = "charmap";
7971 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007972 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007973 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007974 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007975
Benjamin Petersonbac79492012-01-14 13:34:47 -05007976 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007977 return -1;
7978 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007979 /* find all unencodable characters */
7980 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007981 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007982 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007983 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007984 val = encoding_map_lookup(ch, mapping);
7985 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 break;
7987 ++collendpos;
7988 continue;
7989 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007990
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007991 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7992 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 if (rep==NULL)
7994 return -1;
7995 else if (rep!=Py_None) {
7996 Py_DECREF(rep);
7997 break;
7998 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007999 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008001 }
8002 /* cache callback name lookup
8003 * (if not done yet, i.e. it's the first error) */
8004 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 if ((errors==NULL) || (!strcmp(errors, "strict")))
8006 *known_errorHandler = 1;
8007 else if (!strcmp(errors, "replace"))
8008 *known_errorHandler = 2;
8009 else if (!strcmp(errors, "ignore"))
8010 *known_errorHandler = 3;
8011 else if (!strcmp(errors, "xmlcharrefreplace"))
8012 *known_errorHandler = 4;
8013 else
8014 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008015 }
8016 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008017 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008018 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008019 return -1;
8020 case 2: /* replace */
8021 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 x = charmapencode_output('?', mapping, res, respos);
8023 if (x==enc_EXCEPTION) {
8024 return -1;
8025 }
8026 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008027 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 return -1;
8029 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008030 }
8031 /* fall through */
8032 case 3: /* ignore */
8033 *inpos = collendpos;
8034 break;
8035 case 4: /* xmlcharrefreplace */
8036 /* generate replacement (temporarily (mis)uses p) */
8037 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 char buffer[2+29+1+1];
8039 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008040 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 for (cp = buffer; *cp; ++cp) {
8042 x = charmapencode_output(*cp, mapping, res, respos);
8043 if (x==enc_EXCEPTION)
8044 return -1;
8045 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008046 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 return -1;
8048 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008049 }
8050 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008051 *inpos = collendpos;
8052 break;
8053 default:
8054 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008055 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008059 if (PyBytes_Check(repunicode)) {
8060 /* Directly copy bytes result to output. */
8061 Py_ssize_t outsize = PyBytes_Size(*res);
8062 Py_ssize_t requiredsize;
8063 repsize = PyBytes_Size(repunicode);
8064 requiredsize = *respos + repsize;
8065 if (requiredsize > outsize)
8066 /* Make room for all additional bytes. */
8067 if (charmapencode_resize(res, respos, requiredsize)) {
8068 Py_DECREF(repunicode);
8069 return -1;
8070 }
8071 memcpy(PyBytes_AsString(*res) + *respos,
8072 PyBytes_AsString(repunicode), repsize);
8073 *respos += repsize;
8074 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008075 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008076 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008077 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008078 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008079 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008080 Py_DECREF(repunicode);
8081 return -1;
8082 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008083 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008084 data = PyUnicode_DATA(repunicode);
8085 kind = PyUnicode_KIND(repunicode);
8086 for (index = 0; index < repsize; index++) {
8087 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8088 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008090 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 return -1;
8092 }
8093 else if (x==enc_FAILED) {
8094 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008095 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008096 return -1;
8097 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008098 }
8099 *inpos = newpos;
8100 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008101 }
8102 return 0;
8103}
8104
Alexander Belopolsky40018472011-02-26 01:02:56 +00008105PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008106_PyUnicode_EncodeCharmap(PyObject *unicode,
8107 PyObject *mapping,
8108 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008109{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110 /* output object */
8111 PyObject *res = NULL;
8112 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008113 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008114 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008115 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008116 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117 PyObject *errorHandler = NULL;
8118 PyObject *exc = NULL;
8119 /* the following variable is used for caching string comparisons
8120 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8121 * 3=ignore, 4=xmlcharrefreplace */
8122 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008123
Benjamin Petersonbac79492012-01-14 13:34:47 -05008124 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008125 return NULL;
8126 size = PyUnicode_GET_LENGTH(unicode);
8127
Guido van Rossumd57fd912000-03-10 22:53:23 +00008128 /* Default to Latin-1 */
8129 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008130 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008131
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132 /* allocate enough for a simple encoding without
8133 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008134 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135 if (res == NULL)
8136 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008137 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008139
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008140 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008141 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008143 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 if (x==enc_EXCEPTION) /* error */
8145 goto onError;
8146 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008147 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 &exc,
8149 &known_errorHandler, &errorHandler, errors,
8150 &res, &respos)) {
8151 goto onError;
8152 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008153 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 else
8155 /* done with this character => adjust input position */
8156 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008157 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008158
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008159 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008160 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008161 if (_PyBytes_Resize(&res, respos) < 0)
8162 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008163
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008164 Py_XDECREF(exc);
8165 Py_XDECREF(errorHandler);
8166 return res;
8167
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008169 Py_XDECREF(res);
8170 Py_XDECREF(exc);
8171 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008172 return NULL;
8173}
8174
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008175/* Deprecated */
8176PyObject *
8177PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8178 Py_ssize_t size,
8179 PyObject *mapping,
8180 const char *errors)
8181{
8182 PyObject *result;
8183 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8184 if (unicode == NULL)
8185 return NULL;
8186 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8187 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008188 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008189}
8190
Alexander Belopolsky40018472011-02-26 01:02:56 +00008191PyObject *
8192PyUnicode_AsCharmapString(PyObject *unicode,
8193 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194{
8195 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 PyErr_BadArgument();
8197 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008198 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008199 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008200}
8201
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008202/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008203static void
8204make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008205 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008206 Py_ssize_t startpos, Py_ssize_t endpos,
8207 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008208{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008209 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008210 *exceptionObject = _PyUnicodeTranslateError_Create(
8211 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008212 }
8213 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8215 goto onError;
8216 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8217 goto onError;
8218 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8219 goto onError;
8220 return;
8221 onError:
8222 Py_DECREF(*exceptionObject);
8223 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008224 }
8225}
8226
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008228static void
8229raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008230 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008231 Py_ssize_t startpos, Py_ssize_t endpos,
8232 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233{
8234 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008235 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238}
8239
8240/* error handling callback helper:
8241 build arguments, call the callback and check the arguments,
8242 put the result into newpos and return the replacement string, which
8243 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008244static PyObject *
8245unicode_translate_call_errorhandler(const char *errors,
8246 PyObject **errorHandler,
8247 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008248 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008249 Py_ssize_t startpos, Py_ssize_t endpos,
8250 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008251{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008252 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008254 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 PyObject *restuple;
8256 PyObject *resunicode;
8257
8258 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 }
8263
8264 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008265 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268
8269 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008273 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008274 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 Py_DECREF(restuple);
8276 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008277 }
8278 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 &resunicode, &i_newpos)) {
8280 Py_DECREF(restuple);
8281 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008283 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008284 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008285 else
8286 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008287 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8289 Py_DECREF(restuple);
8290 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008291 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 Py_INCREF(resunicode);
8293 Py_DECREF(restuple);
8294 return resunicode;
8295}
8296
8297/* Lookup the character ch in the mapping and put the result in result,
8298 which must be decrefed by the caller.
8299 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008300static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008301charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302{
Christian Heimes217cfd12007-12-02 14:31:20 +00008303 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304 PyObject *x;
8305
8306 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 x = PyObject_GetItem(mapping, w);
8309 Py_DECREF(w);
8310 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8312 /* No mapping found means: use 1:1 mapping. */
8313 PyErr_Clear();
8314 *result = NULL;
8315 return 0;
8316 } else
8317 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008318 }
8319 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 *result = x;
8321 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008323 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 long value = PyLong_AS_LONG(x);
8325 long max = PyUnicode_GetMax();
8326 if (value < 0 || value > max) {
8327 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008328 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 Py_DECREF(x);
8330 return -1;
8331 }
8332 *result = x;
8333 return 0;
8334 }
8335 else if (PyUnicode_Check(x)) {
8336 *result = x;
8337 return 0;
8338 }
8339 else {
8340 /* wrong return value */
8341 PyErr_SetString(PyExc_TypeError,
8342 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008343 Py_DECREF(x);
8344 return -1;
8345 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346}
8347/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008348 if not reallocate and adjust various state variables.
8349 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008350static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008351charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008354 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008355 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008356 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 /* exponentially overallocate to minimize reallocations */
8358 if (requiredsize < 2 * oldsize)
8359 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008360 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8361 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008363 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365 }
8366 return 0;
8367}
8368/* lookup the character, put the result in the output string and adjust
8369 various state variables. Return a new reference to the object that
8370 was put in the output buffer in *result, or Py_None, if the mapping was
8371 undefined (in which case no character was written).
8372 The called must decref result.
8373 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008374static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008375charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8376 PyObject *mapping, Py_UCS4 **output,
8377 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008378 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008380 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8381 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 }
8387 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008389 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008391 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 }
8393 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008394 Py_ssize_t repsize;
8395 if (PyUnicode_READY(*res) == -1)
8396 return -1;
8397 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 if (repsize==1) {
8399 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008400 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 }
8402 else if (repsize!=0) {
8403 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008404 Py_ssize_t requiredsize = *opos +
8405 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008407 Py_ssize_t i;
8408 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008410 for(i = 0; i < repsize; i++)
8411 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008413 }
8414 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416 return 0;
8417}
8418
Alexander Belopolsky40018472011-02-26 01:02:56 +00008419PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008420_PyUnicode_TranslateCharmap(PyObject *input,
8421 PyObject *mapping,
8422 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 /* input object */
8425 char *idata;
8426 Py_ssize_t size, i;
8427 int kind;
8428 /* output buffer */
8429 Py_UCS4 *output = NULL;
8430 Py_ssize_t osize;
8431 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008433 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 char *reason = "character maps to <undefined>";
8435 PyObject *errorHandler = NULL;
8436 PyObject *exc = NULL;
8437 /* the following variable is used for caching string comparisons
8438 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8439 * 3=ignore, 4=xmlcharrefreplace */
8440 int known_errorHandler = -1;
8441
Guido van Rossumd57fd912000-03-10 22:53:23 +00008442 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 PyErr_BadArgument();
8444 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447 if (PyUnicode_READY(input) == -1)
8448 return NULL;
8449 idata = (char*)PyUnicode_DATA(input);
8450 kind = PyUnicode_KIND(input);
8451 size = PyUnicode_GET_LENGTH(input);
8452 i = 0;
8453
8454 if (size == 0) {
8455 Py_INCREF(input);
8456 return input;
8457 }
8458
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459 /* allocate enough for a simple 1:1 translation without
8460 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 osize = size;
8462 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8463 opos = 0;
8464 if (output == NULL) {
8465 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008469 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 /* try to encode it */
8471 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008472 if (charmaptranslate_output(input, i, mapping,
8473 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 Py_XDECREF(x);
8475 goto onError;
8476 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008477 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 else { /* untranslatable character */
8481 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8482 Py_ssize_t repsize;
8483 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008486 Py_ssize_t collstart = i;
8487 Py_ssize_t collend = i+1;
8488 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008489
Benjamin Peterson29060642009-01-31 22:14:21 +00008490 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008491 while (collend < size) {
8492 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 goto onError;
8494 Py_XDECREF(x);
8495 if (x!=Py_None)
8496 break;
8497 ++collend;
8498 }
8499 /* cache callback name lookup
8500 * (if not done yet, i.e. it's the first error) */
8501 if (known_errorHandler==-1) {
8502 if ((errors==NULL) || (!strcmp(errors, "strict")))
8503 known_errorHandler = 1;
8504 else if (!strcmp(errors, "replace"))
8505 known_errorHandler = 2;
8506 else if (!strcmp(errors, "ignore"))
8507 known_errorHandler = 3;
8508 else if (!strcmp(errors, "xmlcharrefreplace"))
8509 known_errorHandler = 4;
8510 else
8511 known_errorHandler = 0;
8512 }
8513 switch (known_errorHandler) {
8514 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 raise_translate_exception(&exc, input, collstart,
8516 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008517 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 case 2: /* replace */
8519 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 for (coll = collstart; coll<collend; coll++)
8521 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 /* fall through */
8523 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008524 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 break;
8526 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 /* generate replacement (temporarily (mis)uses i) */
8528 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 char buffer[2+29+1+1];
8530 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8532 if (charmaptranslate_makespace(&output, &osize,
8533 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 goto onError;
8535 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 break;
8540 default:
8541 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 reason, input, &exc,
8543 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008544 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008546 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008547 Py_DECREF(repunicode);
8548 goto onError;
8549 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 repsize = PyUnicode_GET_LENGTH(repunicode);
8552 if (charmaptranslate_makespace(&output, &osize,
8553 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 Py_DECREF(repunicode);
8555 goto onError;
8556 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008557 for (uni2 = 0; repsize-->0; ++uni2)
8558 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8559 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008561 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008562 }
8563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008564 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8565 if (!res)
8566 goto onError;
8567 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 Py_XDECREF(exc);
8569 Py_XDECREF(errorHandler);
8570 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008571
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 Py_XDECREF(exc);
8575 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576 return NULL;
8577}
8578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579/* Deprecated. Use PyUnicode_Translate instead. */
8580PyObject *
8581PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8582 Py_ssize_t size,
8583 PyObject *mapping,
8584 const char *errors)
8585{
Christian Heimes5f520f42012-09-11 14:03:25 +02008586 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8588 if (!unicode)
8589 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008590 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8591 Py_DECREF(unicode);
8592 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593}
8594
Alexander Belopolsky40018472011-02-26 01:02:56 +00008595PyObject *
8596PyUnicode_Translate(PyObject *str,
8597 PyObject *mapping,
8598 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599{
8600 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008601
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602 str = PyUnicode_FromObject(str);
8603 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008604 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606 Py_DECREF(str);
8607 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608}
Tim Petersced69f82003-09-16 20:30:58 +00008609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008611fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612{
8613 /* No need to call PyUnicode_READY(self) because this function is only
8614 called as a callback from fixup() which does it already. */
8615 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8616 const int kind = PyUnicode_KIND(self);
8617 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008618 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008619 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 Py_ssize_t i;
8621
8622 for (i = 0; i < len; ++i) {
8623 ch = PyUnicode_READ(kind, data, i);
8624 fixed = 0;
8625 if (ch > 127) {
8626 if (Py_UNICODE_ISSPACE(ch))
8627 fixed = ' ';
8628 else {
8629 const int decimal = Py_UNICODE_TODECIMAL(ch);
8630 if (decimal >= 0)
8631 fixed = '0' + decimal;
8632 }
8633 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008634 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008635 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 PyUnicode_WRITE(kind, data, i, fixed);
8637 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008638 else
8639 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 }
8642
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008643 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008644}
8645
8646PyObject *
8647_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8648{
8649 if (!PyUnicode_Check(unicode)) {
8650 PyErr_BadInternalCall();
8651 return NULL;
8652 }
8653 if (PyUnicode_READY(unicode) == -1)
8654 return NULL;
8655 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8656 /* If the string is already ASCII, just return the same string */
8657 Py_INCREF(unicode);
8658 return unicode;
8659 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008660 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661}
8662
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008663PyObject *
8664PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8665 Py_ssize_t length)
8666{
Victor Stinnerf0124502011-11-21 23:12:56 +01008667 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008668 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008669 Py_UCS4 maxchar;
8670 enum PyUnicode_Kind kind;
8671 void *data;
8672
Victor Stinner99d7ad02012-02-22 13:37:39 +01008673 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008674 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008675 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008676 if (ch > 127) {
8677 int decimal = Py_UNICODE_TODECIMAL(ch);
8678 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008679 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008680 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008681 }
8682 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008683
8684 /* Copy to a new string */
8685 decimal = PyUnicode_New(length, maxchar);
8686 if (decimal == NULL)
8687 return decimal;
8688 kind = PyUnicode_KIND(decimal);
8689 data = PyUnicode_DATA(decimal);
8690 /* Iterate over code points */
8691 for (i = 0; i < length; i++) {
8692 Py_UNICODE ch = s[i];
8693 if (ch > 127) {
8694 int decimal = Py_UNICODE_TODECIMAL(ch);
8695 if (decimal >= 0)
8696 ch = '0' + decimal;
8697 }
8698 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008700 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008701}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008702/* --- Decimal Encoder ---------------------------------------------------- */
8703
Alexander Belopolsky40018472011-02-26 01:02:56 +00008704int
8705PyUnicode_EncodeDecimal(Py_UNICODE *s,
8706 Py_ssize_t length,
8707 char *output,
8708 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008709{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008710 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008711 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008712 enum PyUnicode_Kind kind;
8713 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008714
8715 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 PyErr_BadArgument();
8717 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008718 }
8719
Victor Stinner42bf7752011-11-21 22:52:58 +01008720 unicode = PyUnicode_FromUnicode(s, length);
8721 if (unicode == NULL)
8722 return -1;
8723
Benjamin Petersonbac79492012-01-14 13:34:47 -05008724 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008725 Py_DECREF(unicode);
8726 return -1;
8727 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008728 kind = PyUnicode_KIND(unicode);
8729 data = PyUnicode_DATA(unicode);
8730
Victor Stinnerb84d7232011-11-22 01:50:07 +01008731 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008732 PyObject *exc;
8733 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008735 Py_ssize_t startpos;
8736
8737 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008738
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008740 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008741 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008743 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 decimal = Py_UNICODE_TODECIMAL(ch);
8745 if (decimal >= 0) {
8746 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008747 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 continue;
8749 }
8750 if (0 < ch && ch < 256) {
8751 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008752 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 continue;
8754 }
Victor Stinner6345be92011-11-25 20:09:01 +01008755
Victor Stinner42bf7752011-11-21 22:52:58 +01008756 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008757 exc = NULL;
8758 raise_encode_exception(&exc, "decimal", unicode,
8759 startpos, startpos+1,
8760 "invalid decimal Unicode string");
8761 Py_XDECREF(exc);
8762 Py_DECREF(unicode);
8763 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008764 }
8765 /* 0-terminate the output string */
8766 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008767 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008768 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008769}
8770
Guido van Rossumd57fd912000-03-10 22:53:23 +00008771/* --- Helpers ------------------------------------------------------------ */
8772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008774any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775 Py_ssize_t start,
8776 Py_ssize_t end)
8777{
8778 int kind1, kind2, kind;
8779 void *buf1, *buf2;
8780 Py_ssize_t len1, len2, result;
8781
8782 kind1 = PyUnicode_KIND(s1);
8783 kind2 = PyUnicode_KIND(s2);
8784 kind = kind1 > kind2 ? kind1 : kind2;
8785 buf1 = PyUnicode_DATA(s1);
8786 buf2 = PyUnicode_DATA(s2);
8787 if (kind1 != kind)
8788 buf1 = _PyUnicode_AsKind(s1, kind);
8789 if (!buf1)
8790 return -2;
8791 if (kind2 != kind)
8792 buf2 = _PyUnicode_AsKind(s2, kind);
8793 if (!buf2) {
8794 if (kind1 != kind) PyMem_Free(buf1);
8795 return -2;
8796 }
8797 len1 = PyUnicode_GET_LENGTH(s1);
8798 len2 = PyUnicode_GET_LENGTH(s2);
8799
Victor Stinner794d5672011-10-10 03:21:36 +02008800 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008801 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008802 case PyUnicode_1BYTE_KIND:
8803 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8804 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8805 else
8806 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8807 break;
8808 case PyUnicode_2BYTE_KIND:
8809 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8810 break;
8811 case PyUnicode_4BYTE_KIND:
8812 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8813 break;
8814 default:
8815 assert(0); result = -2;
8816 }
8817 }
8818 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008819 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008820 case PyUnicode_1BYTE_KIND:
8821 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8822 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8823 else
8824 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8825 break;
8826 case PyUnicode_2BYTE_KIND:
8827 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8828 break;
8829 case PyUnicode_4BYTE_KIND:
8830 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8831 break;
8832 default:
8833 assert(0); result = -2;
8834 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835 }
8836
8837 if (kind1 != kind)
8838 PyMem_Free(buf1);
8839 if (kind2 != kind)
8840 PyMem_Free(buf2);
8841
8842 return result;
8843}
8844
8845Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008846_PyUnicode_InsertThousandsGrouping(
8847 PyObject *unicode, Py_ssize_t index,
8848 Py_ssize_t n_buffer,
8849 void *digits, Py_ssize_t n_digits,
8850 Py_ssize_t min_width,
8851 const char *grouping, PyObject *thousands_sep,
8852 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008853{
Victor Stinner41a863c2012-02-24 00:37:51 +01008854 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008855 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008856 Py_ssize_t thousands_sep_len;
8857 Py_ssize_t len;
8858
8859 if (unicode != NULL) {
8860 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008861 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008862 }
8863 else {
8864 kind = PyUnicode_1BYTE_KIND;
8865 data = NULL;
8866 }
8867 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8868 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8869 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8870 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008871 if (thousands_sep_kind < kind) {
8872 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8873 if (!thousands_sep_data)
8874 return -1;
8875 }
8876 else {
8877 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8878 if (!data)
8879 return -1;
8880 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008881 }
8882
Benjamin Petersonead6b532011-12-20 17:23:42 -06008883 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008885 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008886 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008887 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008888 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008889 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008890 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008891 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008892 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008893 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008894 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008895 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008896 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008897 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008898 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008899 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008900 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008903 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008904 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008905 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008906 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008907 break;
8908 default:
8909 assert(0);
8910 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008911 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008912 if (unicode != NULL && thousands_sep_kind != kind) {
8913 if (thousands_sep_kind < kind)
8914 PyMem_Free(thousands_sep_data);
8915 else
8916 PyMem_Free(data);
8917 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008918 if (unicode == NULL) {
8919 *maxchar = 127;
8920 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008921 *maxchar = MAX_MAXCHAR(*maxchar,
8922 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008923 }
8924 }
8925 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926}
8927
8928
Thomas Wouters477c8d52006-05-27 19:21:47 +00008929/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008930#define ADJUST_INDICES(start, end, len) \
8931 if (end > len) \
8932 end = len; \
8933 else if (end < 0) { \
8934 end += len; \
8935 if (end < 0) \
8936 end = 0; \
8937 } \
8938 if (start < 0) { \
8939 start += len; \
8940 if (start < 0) \
8941 start = 0; \
8942 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008943
Alexander Belopolsky40018472011-02-26 01:02:56 +00008944Py_ssize_t
8945PyUnicode_Count(PyObject *str,
8946 PyObject *substr,
8947 Py_ssize_t start,
8948 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008949{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008950 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008951 PyObject* str_obj;
8952 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008953 int kind1, kind2, kind;
8954 void *buf1 = NULL, *buf2 = NULL;
8955 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008956
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008957 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008958 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008959 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008960 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008961 if (!sub_obj) {
8962 Py_DECREF(str_obj);
8963 return -1;
8964 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008965 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008966 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008967 Py_DECREF(str_obj);
8968 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008969 }
Tim Petersced69f82003-09-16 20:30:58 +00008970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971 kind1 = PyUnicode_KIND(str_obj);
8972 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008973 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008974 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008976 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008977 if (kind2 > kind) {
8978 Py_DECREF(sub_obj);
8979 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008980 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008981 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008982 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008984 if (!buf2)
8985 goto onError;
8986 len1 = PyUnicode_GET_LENGTH(str_obj);
8987 len2 = PyUnicode_GET_LENGTH(sub_obj);
8988
8989 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008990 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008991 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008992 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8993 result = asciilib_count(
8994 ((Py_UCS1*)buf1) + start, end - start,
8995 buf2, len2, PY_SSIZE_T_MAX
8996 );
8997 else
8998 result = ucs1lib_count(
8999 ((Py_UCS1*)buf1) + start, end - start,
9000 buf2, len2, PY_SSIZE_T_MAX
9001 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002 break;
9003 case PyUnicode_2BYTE_KIND:
9004 result = ucs2lib_count(
9005 ((Py_UCS2*)buf1) + start, end - start,
9006 buf2, len2, PY_SSIZE_T_MAX
9007 );
9008 break;
9009 case PyUnicode_4BYTE_KIND:
9010 result = ucs4lib_count(
9011 ((Py_UCS4*)buf1) + start, end - start,
9012 buf2, len2, PY_SSIZE_T_MAX
9013 );
9014 break;
9015 default:
9016 assert(0); result = 0;
9017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009018
9019 Py_DECREF(sub_obj);
9020 Py_DECREF(str_obj);
9021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009022 if (kind2 != kind)
9023 PyMem_Free(buf2);
9024
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026 onError:
9027 Py_DECREF(sub_obj);
9028 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009029 if (kind2 != kind && buf2)
9030 PyMem_Free(buf2);
9031 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009032}
9033
Alexander Belopolsky40018472011-02-26 01:02:56 +00009034Py_ssize_t
9035PyUnicode_Find(PyObject *str,
9036 PyObject *sub,
9037 Py_ssize_t start,
9038 Py_ssize_t end,
9039 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009041 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009042
Guido van Rossumd57fd912000-03-10 22:53:23 +00009043 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009044 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009045 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009046 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009047 if (!sub) {
9048 Py_DECREF(str);
9049 return -2;
9050 }
9051 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9052 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009053 Py_DECREF(str);
9054 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009055 }
Tim Petersced69f82003-09-16 20:30:58 +00009056
Victor Stinner794d5672011-10-10 03:21:36 +02009057 result = any_find_slice(direction,
9058 str, sub, start, end
9059 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009060
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009062 Py_DECREF(sub);
9063
Guido van Rossumd57fd912000-03-10 22:53:23 +00009064 return result;
9065}
9066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067Py_ssize_t
9068PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9069 Py_ssize_t start, Py_ssize_t end,
9070 int direction)
9071{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009073 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 if (PyUnicode_READY(str) == -1)
9075 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009076 if (start < 0 || end < 0) {
9077 PyErr_SetString(PyExc_IndexError, "string index out of range");
9078 return -2;
9079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 if (end > PyUnicode_GET_LENGTH(str))
9081 end = PyUnicode_GET_LENGTH(str);
9082 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009083 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9084 kind, end-start, ch, direction);
9085 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009087 else
9088 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089}
9090
Alexander Belopolsky40018472011-02-26 01:02:56 +00009091static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009092tailmatch(PyObject *self,
9093 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009094 Py_ssize_t start,
9095 Py_ssize_t end,
9096 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 int kind_self;
9099 int kind_sub;
9100 void *data_self;
9101 void *data_sub;
9102 Py_ssize_t offset;
9103 Py_ssize_t i;
9104 Py_ssize_t end_sub;
9105
9106 if (PyUnicode_READY(self) == -1 ||
9107 PyUnicode_READY(substring) == -1)
9108 return 0;
9109
9110 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111 return 1;
9112
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9114 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009115 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009116 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 kind_self = PyUnicode_KIND(self);
9119 data_self = PyUnicode_DATA(self);
9120 kind_sub = PyUnicode_KIND(substring);
9121 data_sub = PyUnicode_DATA(substring);
9122 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9123
9124 if (direction > 0)
9125 offset = end;
9126 else
9127 offset = start;
9128
9129 if (PyUnicode_READ(kind_self, data_self, offset) ==
9130 PyUnicode_READ(kind_sub, data_sub, 0) &&
9131 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9132 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9133 /* If both are of the same kind, memcmp is sufficient */
9134 if (kind_self == kind_sub) {
9135 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009136 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137 data_sub,
9138 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009139 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140 }
9141 /* otherwise we have to compare each character by first accesing it */
9142 else {
9143 /* We do not need to compare 0 and len(substring)-1 because
9144 the if statement above ensured already that they are equal
9145 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009146 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009147 for (i = 1; i < end_sub; ++i) {
9148 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9149 PyUnicode_READ(kind_sub, data_sub, i))
9150 return 0;
9151 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009152 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009153 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154 }
9155
9156 return 0;
9157}
9158
Alexander Belopolsky40018472011-02-26 01:02:56 +00009159Py_ssize_t
9160PyUnicode_Tailmatch(PyObject *str,
9161 PyObject *substr,
9162 Py_ssize_t start,
9163 Py_ssize_t end,
9164 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009166 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009167
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168 str = PyUnicode_FromObject(str);
9169 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009170 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171 substr = PyUnicode_FromObject(substr);
9172 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009173 Py_DECREF(str);
9174 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009175 }
Tim Petersced69f82003-09-16 20:30:58 +00009176
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009177 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009178 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179 Py_DECREF(str);
9180 Py_DECREF(substr);
9181 return result;
9182}
9183
Guido van Rossumd57fd912000-03-10 22:53:23 +00009184/* Apply fixfct filter to the Unicode object self and return a
9185 reference to the modified object */
9186
Alexander Belopolsky40018472011-02-26 01:02:56 +00009187static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009188fixup(PyObject *self,
9189 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009190{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 PyObject *u;
9192 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009193 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009194
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009195 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009196 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009197 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009198 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009200 /* fix functions return the new maximum character in a string,
9201 if the kind of the resulting unicode object does not change,
9202 everything is fine. Otherwise we need to change the string kind
9203 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009204 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009205
9206 if (maxchar_new == 0) {
9207 /* no changes */;
9208 if (PyUnicode_CheckExact(self)) {
9209 Py_DECREF(u);
9210 Py_INCREF(self);
9211 return self;
9212 }
9213 else
9214 return u;
9215 }
9216
Victor Stinnere6abb482012-05-02 01:15:40 +02009217 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218
Victor Stinnereaab6042011-12-11 22:22:39 +01009219 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009221
9222 /* In case the maximum character changed, we need to
9223 convert the string to the new category. */
9224 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9225 if (v == NULL) {
9226 Py_DECREF(u);
9227 return NULL;
9228 }
9229 if (maxchar_new > maxchar_old) {
9230 /* If the maxchar increased so that the kind changed, not all
9231 characters are representable anymore and we need to fix the
9232 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009233 _PyUnicode_FastCopyCharacters(v, 0,
9234 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009235 maxchar_old = fixfct(v);
9236 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237 }
9238 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009239 _PyUnicode_FastCopyCharacters(v, 0,
9240 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009241 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009242 Py_DECREF(u);
9243 assert(_PyUnicode_CheckConsistency(v, 1));
9244 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009245}
9246
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009247static PyObject *
9248ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009249{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009250 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9251 char *resdata, *data = PyUnicode_DATA(self);
9252 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009253
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009254 res = PyUnicode_New(len, 127);
9255 if (res == NULL)
9256 return NULL;
9257 resdata = PyUnicode_DATA(res);
9258 if (lower)
9259 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009261 _Py_bytes_upper(resdata, data, len);
9262 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263}
9264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009266handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009267{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009268 Py_ssize_t j;
9269 int final_sigma;
9270 Py_UCS4 c;
9271 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009272
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009273 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9274
9275 where ! is a negation and \p{xxx} is a character with property xxx.
9276 */
9277 for (j = i - 1; j >= 0; j--) {
9278 c = PyUnicode_READ(kind, data, j);
9279 if (!_PyUnicode_IsCaseIgnorable(c))
9280 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009281 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009282 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9283 if (final_sigma) {
9284 for (j = i + 1; j < length; j++) {
9285 c = PyUnicode_READ(kind, data, j);
9286 if (!_PyUnicode_IsCaseIgnorable(c))
9287 break;
9288 }
9289 final_sigma = j == length || !_PyUnicode_IsCased(c);
9290 }
9291 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292}
9293
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009294static int
9295lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9296 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009298 /* Obscure special case. */
9299 if (c == 0x3A3) {
9300 mapped[0] = handle_capital_sigma(kind, data, length, i);
9301 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009302 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009303 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304}
9305
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009306static Py_ssize_t
9307do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009308{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009309 Py_ssize_t i, k = 0;
9310 int n_res, j;
9311 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009312
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009313 c = PyUnicode_READ(kind, data, 0);
9314 n_res = _PyUnicode_ToUpperFull(c, mapped);
9315 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009316 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009317 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009318 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009319 for (i = 1; i < length; i++) {
9320 c = PyUnicode_READ(kind, data, i);
9321 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9322 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009323 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009324 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009325 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009326 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009327 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009328}
9329
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009330static Py_ssize_t
9331do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9332 Py_ssize_t i, k = 0;
9333
9334 for (i = 0; i < length; i++) {
9335 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9336 int n_res, j;
9337 if (Py_UNICODE_ISUPPER(c)) {
9338 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9339 }
9340 else if (Py_UNICODE_ISLOWER(c)) {
9341 n_res = _PyUnicode_ToUpperFull(c, mapped);
9342 }
9343 else {
9344 n_res = 1;
9345 mapped[0] = c;
9346 }
9347 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009348 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009349 res[k++] = mapped[j];
9350 }
9351 }
9352 return k;
9353}
9354
9355static Py_ssize_t
9356do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9357 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009359 Py_ssize_t i, k = 0;
9360
9361 for (i = 0; i < length; i++) {
9362 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9363 int n_res, j;
9364 if (lower)
9365 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9366 else
9367 n_res = _PyUnicode_ToUpperFull(c, mapped);
9368 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009369 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009370 res[k++] = mapped[j];
9371 }
9372 }
9373 return k;
9374}
9375
9376static Py_ssize_t
9377do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9378{
9379 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9380}
9381
9382static Py_ssize_t
9383do_lower(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, 1);
9386}
9387
Benjamin Petersone51757f2012-01-12 21:10:29 -05009388static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009389do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9390{
9391 Py_ssize_t i, k = 0;
9392
9393 for (i = 0; i < length; i++) {
9394 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9395 Py_UCS4 mapped[3];
9396 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9397 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009398 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009399 res[k++] = mapped[j];
9400 }
9401 }
9402 return k;
9403}
9404
9405static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009406do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9407{
9408 Py_ssize_t i, k = 0;
9409 int previous_is_cased;
9410
9411 previous_is_cased = 0;
9412 for (i = 0; i < length; i++) {
9413 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9414 Py_UCS4 mapped[3];
9415 int n_res, j;
9416
9417 if (previous_is_cased)
9418 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9419 else
9420 n_res = _PyUnicode_ToTitleFull(c, mapped);
9421
9422 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009423 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009424 res[k++] = mapped[j];
9425 }
9426
9427 previous_is_cased = _PyUnicode_IsCased(c);
9428 }
9429 return k;
9430}
9431
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009432static PyObject *
9433case_operation(PyObject *self,
9434 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9435{
9436 PyObject *res = NULL;
9437 Py_ssize_t length, newlength = 0;
9438 int kind, outkind;
9439 void *data, *outdata;
9440 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9441
Benjamin Petersoneea48462012-01-16 14:28:50 -05009442 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009443
9444 kind = PyUnicode_KIND(self);
9445 data = PyUnicode_DATA(self);
9446 length = PyUnicode_GET_LENGTH(self);
9447 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9448 if (tmp == NULL)
9449 return PyErr_NoMemory();
9450 newlength = perform(kind, data, length, tmp, &maxchar);
9451 res = PyUnicode_New(newlength, maxchar);
9452 if (res == NULL)
9453 goto leave;
9454 tmpend = tmp + newlength;
9455 outdata = PyUnicode_DATA(res);
9456 outkind = PyUnicode_KIND(res);
9457 switch (outkind) {
9458 case PyUnicode_1BYTE_KIND:
9459 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9460 break;
9461 case PyUnicode_2BYTE_KIND:
9462 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9463 break;
9464 case PyUnicode_4BYTE_KIND:
9465 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9466 break;
9467 default:
9468 assert(0);
9469 break;
9470 }
9471 leave:
9472 PyMem_FREE(tmp);
9473 return res;
9474}
9475
Tim Peters8ce9f162004-08-27 01:49:32 +00009476PyObject *
9477PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009480 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009482 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009483 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9484 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009485 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009487 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009489 int use_memcpy;
9490 unsigned char *res_data = NULL, *sep_data = NULL;
9491 PyObject *last_obj;
9492 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493
Tim Peters05eba1f2004-08-27 21:32:02 +00009494 fseq = PySequence_Fast(seq, "");
9495 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009496 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009497 }
9498
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009499 /* NOTE: the following code can't call back into Python code,
9500 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009501 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009502
Tim Peters05eba1f2004-08-27 21:32:02 +00009503 seqlen = PySequence_Fast_GET_SIZE(fseq);
9504 /* If empty sequence, return u"". */
9505 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009506 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009507 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009508 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009509
Tim Peters05eba1f2004-08-27 21:32:02 +00009510 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009511 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009512 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009513 if (seqlen == 1) {
9514 if (PyUnicode_CheckExact(items[0])) {
9515 res = items[0];
9516 Py_INCREF(res);
9517 Py_DECREF(fseq);
9518 return res;
9519 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009520 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009521 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009522 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009523 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009524 /* Set up sep and seplen */
9525 if (separator == NULL) {
9526 /* fall back to a blank space separator */
9527 sep = PyUnicode_FromOrdinal(' ');
9528 if (!sep)
9529 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009530 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009531 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009532 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009533 else {
9534 if (!PyUnicode_Check(separator)) {
9535 PyErr_Format(PyExc_TypeError,
9536 "separator: expected str instance,"
9537 " %.80s found",
9538 Py_TYPE(separator)->tp_name);
9539 goto onError;
9540 }
9541 if (PyUnicode_READY(separator))
9542 goto onError;
9543 sep = separator;
9544 seplen = PyUnicode_GET_LENGTH(separator);
9545 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9546 /* inc refcount to keep this code path symmetric with the
9547 above case of a blank separator */
9548 Py_INCREF(sep);
9549 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009550 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009551 }
9552
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009553 /* There are at least two things to join, or else we have a subclass
9554 * of str in the sequence.
9555 * Do a pre-pass to figure out the total amount of space we'll
9556 * need (sz), and see whether all argument are strings.
9557 */
9558 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009559#ifdef Py_DEBUG
9560 use_memcpy = 0;
9561#else
9562 use_memcpy = 1;
9563#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009564 for (i = 0; i < seqlen; i++) {
9565 const Py_ssize_t old_sz = sz;
9566 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 if (!PyUnicode_Check(item)) {
9568 PyErr_Format(PyExc_TypeError,
9569 "sequence item %zd: expected str instance,"
9570 " %.80s found",
9571 i, Py_TYPE(item)->tp_name);
9572 goto onError;
9573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 if (PyUnicode_READY(item) == -1)
9575 goto onError;
9576 sz += PyUnicode_GET_LENGTH(item);
9577 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009578 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009579 if (i != 0)
9580 sz += seplen;
9581 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9582 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009583 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009584 goto onError;
9585 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009586 if (use_memcpy && last_obj != NULL) {
9587 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9588 use_memcpy = 0;
9589 }
9590 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009591 }
Tim Petersced69f82003-09-16 20:30:58 +00009592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009594 if (res == NULL)
9595 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009596
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009597 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009598#ifdef Py_DEBUG
9599 use_memcpy = 0;
9600#else
9601 if (use_memcpy) {
9602 res_data = PyUnicode_1BYTE_DATA(res);
9603 kind = PyUnicode_KIND(res);
9604 if (seplen != 0)
9605 sep_data = PyUnicode_1BYTE_DATA(sep);
9606 }
9607#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009609 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009610 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009611 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009612 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009613 if (use_memcpy) {
9614 Py_MEMCPY(res_data,
9615 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009616 kind * seplen);
9617 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009618 }
9619 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009620 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009621 res_offset += seplen;
9622 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009623 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009624 itemlen = PyUnicode_GET_LENGTH(item);
9625 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009626 if (use_memcpy) {
9627 Py_MEMCPY(res_data,
9628 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009629 kind * itemlen);
9630 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009631 }
9632 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009633 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009634 res_offset += itemlen;
9635 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009636 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009637 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009638 if (use_memcpy)
9639 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009640 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009641 else
9642 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009643
Tim Peters05eba1f2004-08-27 21:32:02 +00009644 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009646 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648
Benjamin Peterson29060642009-01-31 22:14:21 +00009649 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009650 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009652 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653 return NULL;
9654}
9655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656#define FILL(kind, data, value, start, length) \
9657 do { \
9658 Py_ssize_t i_ = 0; \
9659 assert(kind != PyUnicode_WCHAR_KIND); \
9660 switch ((kind)) { \
9661 case PyUnicode_1BYTE_KIND: { \
9662 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009663 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009664 break; \
9665 } \
9666 case PyUnicode_2BYTE_KIND: { \
9667 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9668 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9669 break; \
9670 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009671 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009672 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9673 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9674 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009675 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009676 } \
9677 } \
9678 } while (0)
9679
Victor Stinnerd3f08822012-05-29 12:57:52 +02009680void
9681_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9682 Py_UCS4 fill_char)
9683{
9684 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9685 const void *data = PyUnicode_DATA(unicode);
9686 assert(PyUnicode_IS_READY(unicode));
9687 assert(unicode_modifiable(unicode));
9688 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9689 assert(start >= 0);
9690 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9691 FILL(kind, data, fill_char, start, length);
9692}
9693
Victor Stinner3fe55312012-01-04 00:33:50 +01009694Py_ssize_t
9695PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9696 Py_UCS4 fill_char)
9697{
9698 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009699
9700 if (!PyUnicode_Check(unicode)) {
9701 PyErr_BadInternalCall();
9702 return -1;
9703 }
9704 if (PyUnicode_READY(unicode) == -1)
9705 return -1;
9706 if (unicode_check_modifiable(unicode))
9707 return -1;
9708
Victor Stinnerd3f08822012-05-29 12:57:52 +02009709 if (start < 0) {
9710 PyErr_SetString(PyExc_IndexError, "string index out of range");
9711 return -1;
9712 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009713 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9714 PyErr_SetString(PyExc_ValueError,
9715 "fill character is bigger than "
9716 "the string maximum character");
9717 return -1;
9718 }
9719
9720 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9721 length = Py_MIN(maxlen, length);
9722 if (length <= 0)
9723 return 0;
9724
Victor Stinnerd3f08822012-05-29 12:57:52 +02009725 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009726 return length;
9727}
9728
Victor Stinner9310abb2011-10-05 00:59:23 +02009729static PyObject *
9730pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009731 Py_ssize_t left,
9732 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009734{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 PyObject *u;
9736 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009737 int kind;
9738 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009739
9740 if (left < 0)
9741 left = 0;
9742 if (right < 0)
9743 right = 0;
9744
Victor Stinnerc4b49542011-12-11 22:44:26 +01009745 if (left == 0 && right == 0)
9746 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009748 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9749 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009750 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9751 return NULL;
9752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009754 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009756 if (!u)
9757 return NULL;
9758
9759 kind = PyUnicode_KIND(u);
9760 data = PyUnicode_DATA(u);
9761 if (left)
9762 FILL(kind, data, fill, 0, left);
9763 if (right)
9764 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009765 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009766 assert(_PyUnicode_CheckConsistency(u, 1));
9767 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768}
9769
Alexander Belopolsky40018472011-02-26 01:02:56 +00009770PyObject *
9771PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009773 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774
9775 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009776 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009777 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009778 if (PyUnicode_READY(string) == -1) {
9779 Py_DECREF(string);
9780 return NULL;
9781 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782
Benjamin Petersonead6b532011-12-20 17:23:42 -06009783 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009785 if (PyUnicode_IS_ASCII(string))
9786 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009787 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009788 PyUnicode_GET_LENGTH(string), keepends);
9789 else
9790 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009791 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009792 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009793 break;
9794 case PyUnicode_2BYTE_KIND:
9795 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009796 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 PyUnicode_GET_LENGTH(string), keepends);
9798 break;
9799 case PyUnicode_4BYTE_KIND:
9800 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009801 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009802 PyUnicode_GET_LENGTH(string), keepends);
9803 break;
9804 default:
9805 assert(0);
9806 list = 0;
9807 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808 Py_DECREF(string);
9809 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009810}
9811
Alexander Belopolsky40018472011-02-26 01:02:56 +00009812static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009813split(PyObject *self,
9814 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009815 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009816{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009817 int kind1, kind2, kind;
9818 void *buf1, *buf2;
9819 Py_ssize_t len1, len2;
9820 PyObject* out;
9821
Guido van Rossumd57fd912000-03-10 22:53:23 +00009822 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009823 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 if (PyUnicode_READY(self) == -1)
9826 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009829 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009830 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009831 if (PyUnicode_IS_ASCII(self))
9832 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009833 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009834 PyUnicode_GET_LENGTH(self), maxcount
9835 );
9836 else
9837 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009838 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009839 PyUnicode_GET_LENGTH(self), maxcount
9840 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 case PyUnicode_2BYTE_KIND:
9842 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009843 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 PyUnicode_GET_LENGTH(self), maxcount
9845 );
9846 case PyUnicode_4BYTE_KIND:
9847 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009848 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 PyUnicode_GET_LENGTH(self), maxcount
9850 );
9851 default:
9852 assert(0);
9853 return NULL;
9854 }
9855
9856 if (PyUnicode_READY(substring) == -1)
9857 return NULL;
9858
9859 kind1 = PyUnicode_KIND(self);
9860 kind2 = PyUnicode_KIND(substring);
9861 kind = kind1 > kind2 ? kind1 : kind2;
9862 buf1 = PyUnicode_DATA(self);
9863 buf2 = PyUnicode_DATA(substring);
9864 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009865 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 if (!buf1)
9867 return NULL;
9868 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009869 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 if (!buf2) {
9871 if (kind1 != kind) PyMem_Free(buf1);
9872 return NULL;
9873 }
9874 len1 = PyUnicode_GET_LENGTH(self);
9875 len2 = PyUnicode_GET_LENGTH(substring);
9876
Benjamin Petersonead6b532011-12-20 17:23:42 -06009877 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009878 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009879 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9880 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009881 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009882 else
9883 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009884 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009885 break;
9886 case PyUnicode_2BYTE_KIND:
9887 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009888 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 break;
9890 case PyUnicode_4BYTE_KIND:
9891 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009892 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 break;
9894 default:
9895 out = NULL;
9896 }
9897 if (kind1 != kind)
9898 PyMem_Free(buf1);
9899 if (kind2 != kind)
9900 PyMem_Free(buf2);
9901 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009902}
9903
Alexander Belopolsky40018472011-02-26 01:02:56 +00009904static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009905rsplit(PyObject *self,
9906 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009907 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 int kind1, kind2, kind;
9910 void *buf1, *buf2;
9911 Py_ssize_t len1, len2;
9912 PyObject* out;
9913
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009914 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009915 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 if (PyUnicode_READY(self) == -1)
9918 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009921 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009923 if (PyUnicode_IS_ASCII(self))
9924 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009925 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009926 PyUnicode_GET_LENGTH(self), maxcount
9927 );
9928 else
9929 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009930 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009931 PyUnicode_GET_LENGTH(self), maxcount
9932 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 case PyUnicode_2BYTE_KIND:
9934 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009935 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009936 PyUnicode_GET_LENGTH(self), maxcount
9937 );
9938 case PyUnicode_4BYTE_KIND:
9939 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009940 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009941 PyUnicode_GET_LENGTH(self), maxcount
9942 );
9943 default:
9944 assert(0);
9945 return NULL;
9946 }
9947
9948 if (PyUnicode_READY(substring) == -1)
9949 return NULL;
9950
9951 kind1 = PyUnicode_KIND(self);
9952 kind2 = PyUnicode_KIND(substring);
9953 kind = kind1 > kind2 ? kind1 : kind2;
9954 buf1 = PyUnicode_DATA(self);
9955 buf2 = PyUnicode_DATA(substring);
9956 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009957 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 if (!buf1)
9959 return NULL;
9960 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009961 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 if (!buf2) {
9963 if (kind1 != kind) PyMem_Free(buf1);
9964 return NULL;
9965 }
9966 len1 = PyUnicode_GET_LENGTH(self);
9967 len2 = PyUnicode_GET_LENGTH(substring);
9968
Benjamin Petersonead6b532011-12-20 17:23:42 -06009969 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009971 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9972 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009973 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009974 else
9975 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009976 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009977 break;
9978 case PyUnicode_2BYTE_KIND:
9979 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009980 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 break;
9982 case PyUnicode_4BYTE_KIND:
9983 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009984 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009985 break;
9986 default:
9987 out = NULL;
9988 }
9989 if (kind1 != kind)
9990 PyMem_Free(buf1);
9991 if (kind2 != kind)
9992 PyMem_Free(buf2);
9993 return out;
9994}
9995
9996static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009997anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9998 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010000 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010002 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10003 return asciilib_find(buf1, len1, buf2, len2, offset);
10004 else
10005 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 case PyUnicode_2BYTE_KIND:
10007 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10008 case PyUnicode_4BYTE_KIND:
10009 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10010 }
10011 assert(0);
10012 return -1;
10013}
10014
10015static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010016anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10017 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010019 switch (kind) {
10020 case PyUnicode_1BYTE_KIND:
10021 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10022 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10023 else
10024 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10025 case PyUnicode_2BYTE_KIND:
10026 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10027 case PyUnicode_4BYTE_KIND:
10028 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10029 }
10030 assert(0);
10031 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010032}
10033
Alexander Belopolsky40018472011-02-26 01:02:56 +000010034static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035replace(PyObject *self, PyObject *str1,
10036 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010037{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 PyObject *u;
10039 char *sbuf = PyUnicode_DATA(self);
10040 char *buf1 = PyUnicode_DATA(str1);
10041 char *buf2 = PyUnicode_DATA(str2);
10042 int srelease = 0, release1 = 0, release2 = 0;
10043 int skind = PyUnicode_KIND(self);
10044 int kind1 = PyUnicode_KIND(str1);
10045 int kind2 = PyUnicode_KIND(str2);
10046 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10047 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10048 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010049 int mayshrink;
10050 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010051
10052 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010053 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010055 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056
Victor Stinner59de0ee2011-10-07 10:01:28 +020010057 if (str1 == str2)
10058 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 if (skind < kind1)
10060 /* substring too wide to be present */
10061 goto nothing;
10062
Victor Stinner49a0a212011-10-12 23:46:10 +020010063 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10064 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10065 /* Replacing str1 with str2 may cause a maxchar reduction in the
10066 result string. */
10067 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010068 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010071 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010073 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010075 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010076 Py_UCS4 u1, u2;
10077 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010078 Py_ssize_t index, pos;
10079 char *src;
10080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010081 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010082 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10083 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010084 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010087 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010089 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010091
10092 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10093 index = 0;
10094 src = sbuf;
10095 while (--maxcount)
10096 {
10097 pos++;
10098 src += pos * PyUnicode_KIND(self);
10099 slen -= pos;
10100 index += pos;
10101 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10102 if (pos < 0)
10103 break;
10104 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10105 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010106 }
10107 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 int rkind = skind;
10109 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010110 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 if (kind1 < rkind) {
10113 /* widen substring */
10114 buf1 = _PyUnicode_AsKind(str1, rkind);
10115 if (!buf1) goto error;
10116 release1 = 1;
10117 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010118 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010119 if (i < 0)
10120 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 if (rkind > kind2) {
10122 /* widen replacement */
10123 buf2 = _PyUnicode_AsKind(str2, rkind);
10124 if (!buf2) goto error;
10125 release2 = 1;
10126 }
10127 else if (rkind < kind2) {
10128 /* widen self and buf1 */
10129 rkind = kind2;
10130 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010131 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 sbuf = _PyUnicode_AsKind(self, rkind);
10133 if (!sbuf) goto error;
10134 srelease = 1;
10135 buf1 = _PyUnicode_AsKind(str1, rkind);
10136 if (!buf1) goto error;
10137 release1 = 1;
10138 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010139 u = PyUnicode_New(slen, maxchar);
10140 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010142 assert(PyUnicode_KIND(u) == rkind);
10143 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010144
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010145 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010146 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010147 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010149 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010151
10152 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010153 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010154 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010155 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010156 if (i == -1)
10157 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010158 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010160 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010162 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010163 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010164 }
10165 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010167 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 int rkind = skind;
10169 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010172 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 buf1 = _PyUnicode_AsKind(str1, rkind);
10174 if (!buf1) goto error;
10175 release1 = 1;
10176 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010177 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010178 if (n == 0)
10179 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010181 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 buf2 = _PyUnicode_AsKind(str2, rkind);
10183 if (!buf2) goto error;
10184 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010185 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010187 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 rkind = kind2;
10189 sbuf = _PyUnicode_AsKind(self, rkind);
10190 if (!sbuf) goto error;
10191 srelease = 1;
10192 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010193 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 buf1 = _PyUnicode_AsKind(str1, rkind);
10195 if (!buf1) goto error;
10196 release1 = 1;
10197 }
10198 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10199 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010200 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 PyErr_SetString(PyExc_OverflowError,
10202 "replace string is too long");
10203 goto error;
10204 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010205 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010206 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010207 _Py_INCREF_UNICODE_EMPTY();
10208 if (!unicode_empty)
10209 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010210 u = unicode_empty;
10211 goto done;
10212 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010213 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 PyErr_SetString(PyExc_OverflowError,
10215 "replace string is too long");
10216 goto error;
10217 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010218 u = PyUnicode_New(new_size, maxchar);
10219 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010221 assert(PyUnicode_KIND(u) == rkind);
10222 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 ires = i = 0;
10224 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010225 while (n-- > 0) {
10226 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010227 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010228 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010230 if (j == -1)
10231 break;
10232 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010233 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010234 memcpy(res + rkind * ires,
10235 sbuf + rkind * i,
10236 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010238 }
10239 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010241 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010243 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010249 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010250 memcpy(res + rkind * ires,
10251 sbuf + rkind * i,
10252 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010253 }
10254 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010255 /* interleave */
10256 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010257 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010259 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 if (--n <= 0)
10262 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010263 memcpy(res + rkind * ires,
10264 sbuf + rkind * i,
10265 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 ires++;
10267 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010268 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010269 memcpy(res + rkind * ires,
10270 sbuf + rkind * i,
10271 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010272 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010273 }
10274
10275 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010276 unicode_adjust_maxchar(&u);
10277 if (u == NULL)
10278 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010280
10281 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 if (srelease)
10283 PyMem_FREE(sbuf);
10284 if (release1)
10285 PyMem_FREE(buf1);
10286 if (release2)
10287 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010288 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010290
Benjamin Peterson29060642009-01-31 22:14:21 +000010291 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010292 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 if (srelease)
10294 PyMem_FREE(sbuf);
10295 if (release1)
10296 PyMem_FREE(buf1);
10297 if (release2)
10298 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010299 return unicode_result_unchanged(self);
10300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 error:
10302 if (srelease && sbuf)
10303 PyMem_FREE(sbuf);
10304 if (release1 && buf1)
10305 PyMem_FREE(buf1);
10306 if (release2 && buf2)
10307 PyMem_FREE(buf2);
10308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309}
10310
10311/* --- Unicode Object Methods --------------------------------------------- */
10312
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010313PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010314 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010315\n\
10316Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010317characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318
10319static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010320unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010322 if (PyUnicode_READY(self) == -1)
10323 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010324 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325}
10326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010327PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010328 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010329\n\
10330Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010331have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010332
10333static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010334unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010335{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010336 if (PyUnicode_READY(self) == -1)
10337 return NULL;
10338 if (PyUnicode_GET_LENGTH(self) == 0)
10339 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010340 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341}
10342
Benjamin Petersond5890c82012-01-14 13:23:30 -050010343PyDoc_STRVAR(casefold__doc__,
10344 "S.casefold() -> str\n\
10345\n\
10346Return a version of S suitable for caseless comparisons.");
10347
10348static PyObject *
10349unicode_casefold(PyObject *self)
10350{
10351 if (PyUnicode_READY(self) == -1)
10352 return NULL;
10353 if (PyUnicode_IS_ASCII(self))
10354 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010355 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010356}
10357
10358
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010359/* Argument converter. Coerces to a single unicode character */
10360
10361static int
10362convert_uc(PyObject *obj, void *addr)
10363{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010365 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010366
Benjamin Peterson14339b62009-01-31 16:36:08 +000010367 uniobj = PyUnicode_FromObject(obj);
10368 if (uniobj == NULL) {
10369 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010370 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010371 return 0;
10372 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010374 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010375 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010376 Py_DECREF(uniobj);
10377 return 0;
10378 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010380 Py_DECREF(uniobj);
10381 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010382}
10383
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010384PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010385 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010387Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010388done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389
10390static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010391unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010393 Py_ssize_t marg, left;
10394 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 Py_UCS4 fillchar = ' ';
10396
Victor Stinnere9a29352011-10-01 02:14:59 +020010397 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399
Benjamin Petersonbac79492012-01-14 13:34:47 -050010400 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401 return NULL;
10402
Victor Stinnerc4b49542011-12-11 22:44:26 +010010403 if (PyUnicode_GET_LENGTH(self) >= width)
10404 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010405
Victor Stinnerc4b49542011-12-11 22:44:26 +010010406 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010407 left = marg / 2 + (marg & width & 1);
10408
Victor Stinner9310abb2011-10-05 00:59:23 +020010409 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410}
10411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412/* This function assumes that str1 and str2 are readied by the caller. */
10413
Marc-André Lemburge5034372000-08-08 08:04:29 +000010414static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010415unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010416{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 int kind1, kind2;
10418 void *data1, *data2;
10419 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 kind1 = PyUnicode_KIND(str1);
10422 kind2 = PyUnicode_KIND(str2);
10423 data1 = PyUnicode_DATA(str1);
10424 data2 = PyUnicode_DATA(str2);
10425 len1 = PyUnicode_GET_LENGTH(str1);
10426 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 for (i = 0; i < len1 && i < len2; ++i) {
10429 Py_UCS4 c1, c2;
10430 c1 = PyUnicode_READ(kind1, data1, i);
10431 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010432
10433 if (c1 != c2)
10434 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010435 }
10436
10437 return (len1 < len2) ? -1 : (len1 != len2);
10438}
10439
Alexander Belopolsky40018472011-02-26 01:02:56 +000010440int
10441PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010442{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10444 if (PyUnicode_READY(left) == -1 ||
10445 PyUnicode_READY(right) == -1)
10446 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010447 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010449 PyErr_Format(PyExc_TypeError,
10450 "Can't compare %.100s and %.100s",
10451 left->ob_type->tp_name,
10452 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453 return -1;
10454}
10455
Martin v. Löwis5b222132007-06-10 09:51:05 +000010456int
10457PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10458{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 Py_ssize_t i;
10460 int kind;
10461 void *data;
10462 Py_UCS4 chr;
10463
Victor Stinner910337b2011-10-03 03:20:16 +020010464 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 if (PyUnicode_READY(uni) == -1)
10466 return -1;
10467 kind = PyUnicode_KIND(uni);
10468 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010469 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10471 if (chr != str[i])
10472 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010473 /* This check keeps Python strings that end in '\0' from comparing equal
10474 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010476 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010477 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010478 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010479 return 0;
10480}
10481
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010482
Benjamin Peterson29060642009-01-31 22:14:21 +000010483#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010484 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010485
Alexander Belopolsky40018472011-02-26 01:02:56 +000010486PyObject *
10487PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010488{
10489 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010490
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010491 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10492 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 if (PyUnicode_READY(left) == -1 ||
10494 PyUnicode_READY(right) == -1)
10495 return NULL;
10496 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10497 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010498 if (op == Py_EQ) {
10499 Py_INCREF(Py_False);
10500 return Py_False;
10501 }
10502 if (op == Py_NE) {
10503 Py_INCREF(Py_True);
10504 return Py_True;
10505 }
10506 }
10507 if (left == right)
10508 result = 0;
10509 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010510 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010511
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010512 /* Convert the return value to a Boolean */
10513 switch (op) {
10514 case Py_EQ:
10515 v = TEST_COND(result == 0);
10516 break;
10517 case Py_NE:
10518 v = TEST_COND(result != 0);
10519 break;
10520 case Py_LE:
10521 v = TEST_COND(result <= 0);
10522 break;
10523 case Py_GE:
10524 v = TEST_COND(result >= 0);
10525 break;
10526 case Py_LT:
10527 v = TEST_COND(result == -1);
10528 break;
10529 case Py_GT:
10530 v = TEST_COND(result == 1);
10531 break;
10532 default:
10533 PyErr_BadArgument();
10534 return NULL;
10535 }
10536 Py_INCREF(v);
10537 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010538 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010539
Brian Curtindfc80e32011-08-10 20:28:54 -050010540 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010541}
10542
Alexander Belopolsky40018472011-02-26 01:02:56 +000010543int
10544PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010545{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010546 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 int kind1, kind2, kind;
10548 void *buf1, *buf2;
10549 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010550 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010551
10552 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010553 sub = PyUnicode_FromObject(element);
10554 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010555 PyErr_Format(PyExc_TypeError,
10556 "'in <string>' requires string as left operand, not %s",
10557 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010558 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010559 }
10560
Thomas Wouters477c8d52006-05-27 19:21:47 +000010561 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010562 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010563 Py_DECREF(sub);
10564 return -1;
10565 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010566 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10567 Py_DECREF(sub);
10568 Py_DECREF(str);
10569 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 kind1 = PyUnicode_KIND(str);
10572 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010573 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 buf1 = PyUnicode_DATA(str);
10575 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010576 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010577 if (kind2 > kind) {
10578 Py_DECREF(sub);
10579 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010580 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010581 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010582 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 if (!buf2) {
10585 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010586 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 return -1;
10588 }
10589 len1 = PyUnicode_GET_LENGTH(str);
10590 len2 = PyUnicode_GET_LENGTH(sub);
10591
Benjamin Petersonead6b532011-12-20 17:23:42 -060010592 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 case PyUnicode_1BYTE_KIND:
10594 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10595 break;
10596 case PyUnicode_2BYTE_KIND:
10597 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10598 break;
10599 case PyUnicode_4BYTE_KIND:
10600 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10601 break;
10602 default:
10603 result = -1;
10604 assert(0);
10605 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010606
10607 Py_DECREF(str);
10608 Py_DECREF(sub);
10609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 if (kind2 != kind)
10611 PyMem_Free(buf2);
10612
Guido van Rossum403d68b2000-03-13 15:55:09 +000010613 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010614}
10615
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616/* Concat to string or Unicode object giving a new Unicode object. */
10617
Alexander Belopolsky40018472011-02-26 01:02:56 +000010618PyObject *
10619PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010622 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010623 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624
10625 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010628 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010631 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632
10633 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010634 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010635 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010638 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010639 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641 }
10642
Victor Stinner488fa492011-12-12 00:01:39 +010010643 u_len = PyUnicode_GET_LENGTH(u);
10644 v_len = PyUnicode_GET_LENGTH(v);
10645 if (u_len > PY_SSIZE_T_MAX - v_len) {
10646 PyErr_SetString(PyExc_OverflowError,
10647 "strings are too large to concat");
10648 goto onError;
10649 }
10650 new_len = u_len + v_len;
10651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010653 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010654 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010657 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010659 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010660 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10661 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662 Py_DECREF(u);
10663 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010664 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010666
Benjamin Peterson29060642009-01-31 22:14:21 +000010667 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668 Py_XDECREF(u);
10669 Py_XDECREF(v);
10670 return NULL;
10671}
10672
Walter Dörwald1ab83302007-05-18 17:15:44 +000010673void
Victor Stinner23e56682011-10-03 03:54:37 +020010674PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010675{
Victor Stinner23e56682011-10-03 03:54:37 +020010676 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010677 Py_UCS4 maxchar, maxchar2;
10678 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010679
10680 if (p_left == NULL) {
10681 if (!PyErr_Occurred())
10682 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010683 return;
10684 }
Victor Stinner23e56682011-10-03 03:54:37 +020010685 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010686 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010687 if (!PyErr_Occurred())
10688 PyErr_BadInternalCall();
10689 goto error;
10690 }
10691
Benjamin Petersonbac79492012-01-14 13:34:47 -050010692 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010693 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010694 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010695 goto error;
10696
Victor Stinner488fa492011-12-12 00:01:39 +010010697 /* Shortcuts */
10698 if (left == unicode_empty) {
10699 Py_DECREF(left);
10700 Py_INCREF(right);
10701 *p_left = right;
10702 return;
10703 }
10704 if (right == unicode_empty)
10705 return;
10706
10707 left_len = PyUnicode_GET_LENGTH(left);
10708 right_len = PyUnicode_GET_LENGTH(right);
10709 if (left_len > PY_SSIZE_T_MAX - right_len) {
10710 PyErr_SetString(PyExc_OverflowError,
10711 "strings are too large to concat");
10712 goto error;
10713 }
10714 new_len = left_len + right_len;
10715
10716 if (unicode_modifiable(left)
10717 && PyUnicode_CheckExact(right)
10718 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010719 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10720 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010721 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010722 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010723 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10724 {
10725 /* append inplace */
10726 if (unicode_resize(p_left, new_len) != 0) {
10727 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10728 * deallocated so it cannot be put back into
10729 * 'variable'. The MemoryError is raised when there
10730 * is no value in 'variable', which might (very
10731 * remotely) be a cause of incompatibilities.
10732 */
10733 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010734 }
Victor Stinner488fa492011-12-12 00:01:39 +010010735 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010736 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010737 }
Victor Stinner488fa492011-12-12 00:01:39 +010010738 else {
10739 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10740 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010741 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010742
Victor Stinner488fa492011-12-12 00:01:39 +010010743 /* Concat the two Unicode strings */
10744 res = PyUnicode_New(new_len, maxchar);
10745 if (res == NULL)
10746 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010747 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10748 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010749 Py_DECREF(left);
10750 *p_left = res;
10751 }
10752 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010753 return;
10754
10755error:
Victor Stinner488fa492011-12-12 00:01:39 +010010756 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010757}
10758
10759void
10760PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10761{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010762 PyUnicode_Append(pleft, right);
10763 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010764}
10765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010766PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010767 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010769Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010770string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010771interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772
10773static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010774unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010775{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010776 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010777 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010778 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 int kind1, kind2, kind;
10781 void *buf1, *buf2;
10782 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783
Jesus Ceaac451502011-04-20 17:09:23 +020010784 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10785 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 kind1 = PyUnicode_KIND(self);
10789 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010790 if (kind2 > kind1)
10791 return PyLong_FromLong(0);
10792 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 buf1 = PyUnicode_DATA(self);
10794 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010796 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 if (!buf2) {
10798 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 return NULL;
10800 }
10801 len1 = PyUnicode_GET_LENGTH(self);
10802 len2 = PyUnicode_GET_LENGTH(substring);
10803
10804 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010805 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 case PyUnicode_1BYTE_KIND:
10807 iresult = ucs1lib_count(
10808 ((Py_UCS1*)buf1) + start, end - start,
10809 buf2, len2, PY_SSIZE_T_MAX
10810 );
10811 break;
10812 case PyUnicode_2BYTE_KIND:
10813 iresult = ucs2lib_count(
10814 ((Py_UCS2*)buf1) + start, end - start,
10815 buf2, len2, PY_SSIZE_T_MAX
10816 );
10817 break;
10818 case PyUnicode_4BYTE_KIND:
10819 iresult = ucs4lib_count(
10820 ((Py_UCS4*)buf1) + start, end - start,
10821 buf2, len2, PY_SSIZE_T_MAX
10822 );
10823 break;
10824 default:
10825 assert(0); iresult = 0;
10826 }
10827
10828 result = PyLong_FromSsize_t(iresult);
10829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010830 if (kind2 != kind)
10831 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832
10833 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010834
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835 return result;
10836}
10837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010838PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010839 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010841Encode S using the codec registered for encoding. Default encoding\n\
10842is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010843handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010844a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10845'xmlcharrefreplace' as well as any other name registered with\n\
10846codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847
10848static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010849unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010851 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 char *encoding = NULL;
10853 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010854
Benjamin Peterson308d6372009-09-18 21:42:35 +000010855 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10856 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010858 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010859}
10860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010861PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010862 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863\n\
10864Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010865If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010866
10867static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010868unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010870 Py_ssize_t i, j, line_pos, src_len, incr;
10871 Py_UCS4 ch;
10872 PyObject *u;
10873 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010875 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010876 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877
10878 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010879 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880
Antoine Pitrou22425222011-10-04 19:10:51 +020010881 if (PyUnicode_READY(self) == -1)
10882 return NULL;
10883
Thomas Wouters7e474022000-07-16 12:04:32 +000010884 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 src_len = PyUnicode_GET_LENGTH(self);
10886 i = j = line_pos = 0;
10887 kind = PyUnicode_KIND(self);
10888 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010889 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 for (; i < src_len; i++) {
10891 ch = PyUnicode_READ(kind, src_data, i);
10892 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010893 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010895 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010896 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010897 goto overflow;
10898 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010899 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010900 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010901 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010902 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010903 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010904 goto overflow;
10905 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010907 if (ch == '\n' || ch == '\r')
10908 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010910 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010911 if (!found)
10912 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010913
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010915 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916 if (!u)
10917 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010918 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919
Antoine Pitroue71d5742011-10-04 15:55:09 +020010920 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921
Antoine Pitroue71d5742011-10-04 15:55:09 +020010922 for (; i < src_len; i++) {
10923 ch = PyUnicode_READ(kind, src_data, i);
10924 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010925 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010926 incr = tabsize - (line_pos % tabsize);
10927 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010928 FILL(kind, dest_data, ' ', j, incr);
10929 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010931 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010932 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010933 line_pos++;
10934 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010935 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010936 if (ch == '\n' || ch == '\r')
10937 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010939 }
10940 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010941 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010942
Antoine Pitroue71d5742011-10-04 15:55:09 +020010943 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010944 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10945 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946}
10947
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010948PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010949 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950\n\
10951Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010952such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953arguments start and end are interpreted as in slice notation.\n\
10954\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010955Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956
10957static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010958unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010960 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010961 Py_ssize_t start;
10962 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010963 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964
Jesus Ceaac451502011-04-20 17:09:23 +020010965 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10966 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 if (PyUnicode_READY(self) == -1)
10970 return NULL;
10971 if (PyUnicode_READY(substring) == -1)
10972 return NULL;
10973
Victor Stinner7931d9a2011-11-04 00:22:48 +010010974 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975
10976 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978 if (result == -2)
10979 return NULL;
10980
Christian Heimes217cfd12007-12-02 14:31:20 +000010981 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982}
10983
10984static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010985unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010987 void *data;
10988 enum PyUnicode_Kind kind;
10989 Py_UCS4 ch;
10990 PyObject *res;
10991
10992 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10993 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010994 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010995 }
10996 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10997 PyErr_SetString(PyExc_IndexError, "string index out of range");
10998 return NULL;
10999 }
11000 kind = PyUnicode_KIND(self);
11001 data = PyUnicode_DATA(self);
11002 ch = PyUnicode_READ(kind, data, index);
11003 if (ch < 256)
11004 return get_latin1_char(ch);
11005
11006 res = PyUnicode_New(1, ch);
11007 if (res == NULL)
11008 return NULL;
11009 kind = PyUnicode_KIND(res);
11010 data = PyUnicode_DATA(res);
11011 PyUnicode_WRITE(kind, data, 0, ch);
11012 assert(_PyUnicode_CheckConsistency(res, 1));
11013 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014}
11015
Guido van Rossumc2504932007-09-18 19:42:40 +000011016/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011017 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011018static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011019unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020{
Guido van Rossumc2504932007-09-18 19:42:40 +000011021 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011022 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011023
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011024#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011025 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011026#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011027 if (_PyUnicode_HASH(self) != -1)
11028 return _PyUnicode_HASH(self);
11029 if (PyUnicode_READY(self) == -1)
11030 return -1;
11031 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011032 /*
11033 We make the hash of the empty string be 0, rather than using
11034 (prefix ^ suffix), since this slightly obfuscates the hash secret
11035 */
11036 if (len == 0) {
11037 _PyUnicode_HASH(self) = 0;
11038 return 0;
11039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011040
11041 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011042#define HASH(P) \
11043 x ^= (Py_uhash_t) *P << 7; \
11044 while (--len >= 0) \
11045 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046
Georg Brandl2fb477c2012-02-21 00:33:36 +010011047 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048 switch (PyUnicode_KIND(self)) {
11049 case PyUnicode_1BYTE_KIND: {
11050 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11051 HASH(c);
11052 break;
11053 }
11054 case PyUnicode_2BYTE_KIND: {
11055 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11056 HASH(s);
11057 break;
11058 }
11059 default: {
11060 Py_UCS4 *l;
11061 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11062 "Impossible switch case in unicode_hash");
11063 l = PyUnicode_4BYTE_DATA(self);
11064 HASH(l);
11065 break;
11066 }
11067 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011068 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11069 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011070
Guido van Rossumc2504932007-09-18 19:42:40 +000011071 if (x == -1)
11072 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011074 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011076#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011078PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011079 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011081Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082
11083static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011084unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011086 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011087 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011088 Py_ssize_t start;
11089 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090
Jesus Ceaac451502011-04-20 17:09:23 +020011091 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11092 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011095 if (PyUnicode_READY(self) == -1)
11096 return NULL;
11097 if (PyUnicode_READY(substring) == -1)
11098 return NULL;
11099
Victor Stinner7931d9a2011-11-04 00:22:48 +010011100 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101
11102 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 if (result == -2)
11105 return NULL;
11106
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107 if (result < 0) {
11108 PyErr_SetString(PyExc_ValueError, "substring not found");
11109 return NULL;
11110 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011111
Christian Heimes217cfd12007-12-02 14:31:20 +000011112 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113}
11114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011115PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011116 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011118Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011119at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120
11121static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011122unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124 Py_ssize_t i, length;
11125 int kind;
11126 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127 int cased;
11128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 if (PyUnicode_READY(self) == -1)
11130 return NULL;
11131 length = PyUnicode_GET_LENGTH(self);
11132 kind = PyUnicode_KIND(self);
11133 data = PyUnicode_DATA(self);
11134
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 if (length == 1)
11137 return PyBool_FromLong(
11138 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011140 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011142 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011143
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 for (i = 0; i < length; i++) {
11146 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011147
Benjamin Peterson29060642009-01-31 22:14:21 +000011148 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11149 return PyBool_FromLong(0);
11150 else if (!cased && Py_UNICODE_ISLOWER(ch))
11151 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011152 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011153 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154}
11155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011156PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011157 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011159Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011160at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161
11162static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011163unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 Py_ssize_t i, length;
11166 int kind;
11167 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168 int cased;
11169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (PyUnicode_READY(self) == -1)
11171 return NULL;
11172 length = PyUnicode_GET_LENGTH(self);
11173 kind = PyUnicode_KIND(self);
11174 data = PyUnicode_DATA(self);
11175
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011177 if (length == 1)
11178 return PyBool_FromLong(
11179 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011181 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011183 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011184
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 for (i = 0; i < length; i++) {
11187 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011188
Benjamin Peterson29060642009-01-31 22:14:21 +000011189 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11190 return PyBool_FromLong(0);
11191 else if (!cased && Py_UNICODE_ISUPPER(ch))
11192 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011194 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195}
11196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011197PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011200Return True if S is a titlecased string and there is at least one\n\
11201character in S, i.e. upper- and titlecase characters may only\n\
11202follow uncased characters and lowercase characters only cased ones.\n\
11203Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011206unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011208 Py_ssize_t i, length;
11209 int kind;
11210 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211 int cased, previous_is_cased;
11212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 if (PyUnicode_READY(self) == -1)
11214 return NULL;
11215 length = PyUnicode_GET_LENGTH(self);
11216 kind = PyUnicode_KIND(self);
11217 data = PyUnicode_DATA(self);
11218
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 if (length == 1) {
11221 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11222 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11223 (Py_UNICODE_ISUPPER(ch) != 0));
11224 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011226 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011228 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011229
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 cased = 0;
11231 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 for (i = 0; i < length; i++) {
11233 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011234
Benjamin Peterson29060642009-01-31 22:14:21 +000011235 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11236 if (previous_is_cased)
11237 return PyBool_FromLong(0);
11238 previous_is_cased = 1;
11239 cased = 1;
11240 }
11241 else if (Py_UNICODE_ISLOWER(ch)) {
11242 if (!previous_is_cased)
11243 return PyBool_FromLong(0);
11244 previous_is_cased = 1;
11245 cased = 1;
11246 }
11247 else
11248 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011250 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251}
11252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011253PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011256Return True if all characters in S are whitespace\n\
11257and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011258
11259static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011260unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011262 Py_ssize_t i, length;
11263 int kind;
11264 void *data;
11265
11266 if (PyUnicode_READY(self) == -1)
11267 return NULL;
11268 length = PyUnicode_GET_LENGTH(self);
11269 kind = PyUnicode_KIND(self);
11270 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011273 if (length == 1)
11274 return PyBool_FromLong(
11275 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011277 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011279 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011281 for (i = 0; i < length; i++) {
11282 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011283 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011286 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287}
11288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011289PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011291\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011292Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011294
11295static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011296unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011297{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 Py_ssize_t i, length;
11299 int kind;
11300 void *data;
11301
11302 if (PyUnicode_READY(self) == -1)
11303 return NULL;
11304 length = PyUnicode_GET_LENGTH(self);
11305 kind = PyUnicode_KIND(self);
11306 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011307
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011308 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 if (length == 1)
11310 return PyBool_FromLong(
11311 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312
11313 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011315 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011317 for (i = 0; i < length; i++) {
11318 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011320 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011321 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322}
11323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011324PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011325 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011326\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011327Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011328and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011329
11330static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011331unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011332{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 int kind;
11334 void *data;
11335 Py_ssize_t len, i;
11336
11337 if (PyUnicode_READY(self) == -1)
11338 return NULL;
11339
11340 kind = PyUnicode_KIND(self);
11341 data = PyUnicode_DATA(self);
11342 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011343
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011344 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (len == 1) {
11346 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11347 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11348 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011349
11350 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 for (i = 0; i < len; i++) {
11355 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011356 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011357 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011358 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011359 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360}
11361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011362PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011365Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011366False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367
11368static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011369unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 Py_ssize_t i, length;
11372 int kind;
11373 void *data;
11374
11375 if (PyUnicode_READY(self) == -1)
11376 return NULL;
11377 length = PyUnicode_GET_LENGTH(self);
11378 kind = PyUnicode_KIND(self);
11379 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 if (length == 1)
11383 return PyBool_FromLong(
11384 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011386 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011388 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 for (i = 0; i < length; i++) {
11391 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011392 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011394 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395}
11396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011397PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011400Return True if all characters in S are digits\n\
11401and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402
11403static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011404unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011406 Py_ssize_t i, length;
11407 int kind;
11408 void *data;
11409
11410 if (PyUnicode_READY(self) == -1)
11411 return NULL;
11412 length = PyUnicode_GET_LENGTH(self);
11413 kind = PyUnicode_KIND(self);
11414 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011417 if (length == 1) {
11418 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11419 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11420 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011422 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011424 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011426 for (i = 0; i < length; i++) {
11427 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011430 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431}
11432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011433PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011436Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011437False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438
11439static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011440unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 Py_ssize_t i, length;
11443 int kind;
11444 void *data;
11445
11446 if (PyUnicode_READY(self) == -1)
11447 return NULL;
11448 length = PyUnicode_GET_LENGTH(self);
11449 kind = PyUnicode_KIND(self);
11450 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 if (length == 1)
11454 return PyBool_FromLong(
11455 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011457 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 for (i = 0; i < length; i++) {
11462 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011463 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011465 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466}
11467
Martin v. Löwis47383402007-08-15 07:32:56 +000011468int
11469PyUnicode_IsIdentifier(PyObject *self)
11470{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 int kind;
11472 void *data;
11473 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011474 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (PyUnicode_READY(self) == -1) {
11477 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 }
11480
11481 /* Special case for empty strings */
11482 if (PyUnicode_GET_LENGTH(self) == 0)
11483 return 0;
11484 kind = PyUnicode_KIND(self);
11485 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011486
11487 /* PEP 3131 says that the first character must be in
11488 XID_Start and subsequent characters in XID_Continue,
11489 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011490 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011491 letters, digits, underscore). However, given the current
11492 definition of XID_Start and XID_Continue, it is sufficient
11493 to check just for these, except that _ must be allowed
11494 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011496 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011497 return 0;
11498
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011499 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011502 return 1;
11503}
11504
11505PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011507\n\
11508Return True if S is a valid identifier according\n\
11509to the language definition.");
11510
11511static PyObject*
11512unicode_isidentifier(PyObject *self)
11513{
11514 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11515}
11516
Georg Brandl559e5d72008-06-11 18:37:52 +000011517PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011518 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011519\n\
11520Return True if all characters in S are considered\n\
11521printable in repr() or S is empty, False otherwise.");
11522
11523static PyObject*
11524unicode_isprintable(PyObject *self)
11525{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 Py_ssize_t i, length;
11527 int kind;
11528 void *data;
11529
11530 if (PyUnicode_READY(self) == -1)
11531 return NULL;
11532 length = PyUnicode_GET_LENGTH(self);
11533 kind = PyUnicode_KIND(self);
11534 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011535
11536 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 if (length == 1)
11538 return PyBool_FromLong(
11539 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 for (i = 0; i < length; i++) {
11542 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011543 Py_RETURN_FALSE;
11544 }
11545 }
11546 Py_RETURN_TRUE;
11547}
11548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011549PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011550 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551\n\
11552Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011553iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554
11555static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011556unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011558 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559}
11560
Martin v. Löwis18e16552006-02-15 17:27:45 +000011561static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011562unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 if (PyUnicode_READY(self) == -1)
11565 return -1;
11566 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567}
11568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011569PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011572Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011573done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574
11575static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011576unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011578 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 Py_UCS4 fillchar = ' ';
11580
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011581 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582 return NULL;
11583
Benjamin Petersonbac79492012-01-14 13:34:47 -050011584 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011585 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586
Victor Stinnerc4b49542011-12-11 22:44:26 +010011587 if (PyUnicode_GET_LENGTH(self) >= width)
11588 return unicode_result_unchanged(self);
11589
11590 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011596Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
11598static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011599unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011601 if (PyUnicode_READY(self) == -1)
11602 return NULL;
11603 if (PyUnicode_IS_ASCII(self))
11604 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011605 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606}
11607
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011608#define LEFTSTRIP 0
11609#define RIGHTSTRIP 1
11610#define BOTHSTRIP 2
11611
11612/* Arrays indexed by above */
11613static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11614
11615#define STRIPNAME(i) (stripformat[i]+3)
11616
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011617/* externally visible for str.strip(unicode) */
11618PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011619_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 void *data;
11622 int kind;
11623 Py_ssize_t i, j, len;
11624 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11627 return NULL;
11628
11629 kind = PyUnicode_KIND(self);
11630 data = PyUnicode_DATA(self);
11631 len = PyUnicode_GET_LENGTH(self);
11632 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11633 PyUnicode_DATA(sepobj),
11634 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011635
Benjamin Peterson14339b62009-01-31 16:36:08 +000011636 i = 0;
11637 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 while (i < len &&
11639 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011640 i++;
11641 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011642 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011643
Benjamin Peterson14339b62009-01-31 16:36:08 +000011644 j = len;
11645 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011646 do {
11647 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 } while (j >= i &&
11649 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011651 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011652
Victor Stinner7931d9a2011-11-04 00:22:48 +010011653 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654}
11655
11656PyObject*
11657PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11658{
11659 unsigned char *data;
11660 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011661 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662
Victor Stinnerde636f32011-10-01 03:55:54 +020011663 if (PyUnicode_READY(self) == -1)
11664 return NULL;
11665
Victor Stinner684d5fd2012-05-03 02:32:34 +020011666 length = PyUnicode_GET_LENGTH(self);
11667 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011668
Victor Stinner684d5fd2012-05-03 02:32:34 +020011669 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011670 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671
Victor Stinnerde636f32011-10-01 03:55:54 +020011672 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011673 PyErr_SetString(PyExc_IndexError, "string index out of range");
11674 return NULL;
11675 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011676 if (start >= length || end < start)
11677 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011678
Victor Stinner684d5fd2012-05-03 02:32:34 +020011679 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011680 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011681 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011682 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011683 }
11684 else {
11685 kind = PyUnicode_KIND(self);
11686 data = PyUnicode_1BYTE_DATA(self);
11687 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011688 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011689 length);
11690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692
11693static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011694do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 int kind;
11697 void *data;
11698 Py_ssize_t len, i, j;
11699
11700 if (PyUnicode_READY(self) == -1)
11701 return NULL;
11702
11703 kind = PyUnicode_KIND(self);
11704 data = PyUnicode_DATA(self);
11705 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011706
Benjamin Peterson14339b62009-01-31 16:36:08 +000011707 i = 0;
11708 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011710 i++;
11711 }
11712 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011713
Benjamin Peterson14339b62009-01-31 16:36:08 +000011714 j = len;
11715 if (striptype != LEFTSTRIP) {
11716 do {
11717 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011719 j++;
11720 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011721
Victor Stinner7931d9a2011-11-04 00:22:48 +010011722 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723}
11724
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011725
11726static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011727do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011728{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011729 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11732 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011733
Benjamin Peterson14339b62009-01-31 16:36:08 +000011734 if (sep != NULL && sep != Py_None) {
11735 if (PyUnicode_Check(sep))
11736 return _PyUnicode_XStrip(self, striptype, sep);
11737 else {
11738 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011739 "%s arg must be None or str",
11740 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011741 return NULL;
11742 }
11743 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011744
Benjamin Peterson14339b62009-01-31 16:36:08 +000011745 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746}
11747
11748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011749PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011750 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011751\n\
11752Return a copy of the string S with leading and trailing\n\
11753whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011754If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755
11756static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011757unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011758{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011759 if (PyTuple_GET_SIZE(args) == 0)
11760 return do_strip(self, BOTHSTRIP); /* Common case */
11761 else
11762 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011763}
11764
11765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011766PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011767 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768\n\
11769Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011770If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771
11772static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011773unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011775 if (PyTuple_GET_SIZE(args) == 0)
11776 return do_strip(self, LEFTSTRIP); /* Common case */
11777 else
11778 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011779}
11780
11781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011782PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784\n\
11785Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011786If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787
11788static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011789unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 if (PyTuple_GET_SIZE(args) == 0)
11792 return do_strip(self, RIGHTSTRIP); /* Common case */
11793 else
11794 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795}
11796
11797
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011799unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011801 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803
Serhiy Storchaka05997252013-01-26 12:14:02 +020011804 if (len < 1)
11805 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806
Victor Stinnerc4b49542011-12-11 22:44:26 +010011807 /* no repeat, return original string */
11808 if (len == 1)
11809 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011810
Benjamin Petersonbac79492012-01-14 13:34:47 -050011811 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812 return NULL;
11813
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011814 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011815 PyErr_SetString(PyExc_OverflowError,
11816 "repeated string is too long");
11817 return NULL;
11818 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011820
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011821 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822 if (!u)
11823 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011824 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 if (PyUnicode_GET_LENGTH(str) == 1) {
11827 const int kind = PyUnicode_KIND(str);
11828 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011829 if (kind == PyUnicode_1BYTE_KIND) {
11830 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011831 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011832 }
11833 else if (kind == PyUnicode_2BYTE_KIND) {
11834 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011835 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011836 ucs2[n] = fill_char;
11837 } else {
11838 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11839 assert(kind == PyUnicode_4BYTE_KIND);
11840 for (n = 0; n < len; ++n)
11841 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011842 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 }
11844 else {
11845 /* number of characters copied this far */
11846 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011847 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 char *to = (char *) PyUnicode_DATA(u);
11849 Py_MEMCPY(to, PyUnicode_DATA(str),
11850 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011851 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 n = (done <= nchars-done) ? done : nchars-done;
11853 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011854 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856 }
11857
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011858 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011859 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860}
11861
Alexander Belopolsky40018472011-02-26 01:02:56 +000011862PyObject *
11863PyUnicode_Replace(PyObject *obj,
11864 PyObject *subobj,
11865 PyObject *replobj,
11866 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011867{
11868 PyObject *self;
11869 PyObject *str1;
11870 PyObject *str2;
11871 PyObject *result;
11872
11873 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011874 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011875 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011877 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 Py_DECREF(self);
11879 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880 }
11881 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011882 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011883 Py_DECREF(self);
11884 Py_DECREF(str1);
11885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011887 if (PyUnicode_READY(self) == -1 ||
11888 PyUnicode_READY(str1) == -1 ||
11889 PyUnicode_READY(str2) == -1)
11890 result = NULL;
11891 else
11892 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893 Py_DECREF(self);
11894 Py_DECREF(str1);
11895 Py_DECREF(str2);
11896 return result;
11897}
11898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011899PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011900 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901\n\
11902Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011903old replaced by new. If the optional argument count is\n\
11904given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905
11906static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 PyObject *str1;
11910 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011911 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912 PyObject *result;
11913
Martin v. Löwis18e16552006-02-15 17:27:45 +000011914 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011916 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011917 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011919 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 return NULL;
11921 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011922 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011923 Py_DECREF(str1);
11924 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011925 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011926 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11927 result = NULL;
11928 else
11929 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930
11931 Py_DECREF(str1);
11932 Py_DECREF(str2);
11933 return result;
11934}
11935
Alexander Belopolsky40018472011-02-26 01:02:56 +000011936static PyObject *
11937unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011939 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011940 Py_ssize_t isize;
11941 Py_ssize_t osize, squote, dquote, i, o;
11942 Py_UCS4 max, quote;
11943 int ikind, okind;
11944 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011947 return NULL;
11948
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 isize = PyUnicode_GET_LENGTH(unicode);
11950 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011951
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 /* Compute length of output, quote characters, and
11953 maximum character */
11954 osize = 2; /* quotes */
11955 max = 127;
11956 squote = dquote = 0;
11957 ikind = PyUnicode_KIND(unicode);
11958 for (i = 0; i < isize; i++) {
11959 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11960 switch (ch) {
11961 case '\'': squote++; osize++; break;
11962 case '"': dquote++; osize++; break;
11963 case '\\': case '\t': case '\r': case '\n':
11964 osize += 2; break;
11965 default:
11966 /* Fast-path ASCII */
11967 if (ch < ' ' || ch == 0x7f)
11968 osize += 4; /* \xHH */
11969 else if (ch < 0x7f)
11970 osize++;
11971 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11972 osize++;
11973 max = ch > max ? ch : max;
11974 }
11975 else if (ch < 0x100)
11976 osize += 4; /* \xHH */
11977 else if (ch < 0x10000)
11978 osize += 6; /* \uHHHH */
11979 else
11980 osize += 10; /* \uHHHHHHHH */
11981 }
11982 }
11983
11984 quote = '\'';
11985 if (squote) {
11986 if (dquote)
11987 /* Both squote and dquote present. Use squote,
11988 and escape them */
11989 osize += squote;
11990 else
11991 quote = '"';
11992 }
11993
11994 repr = PyUnicode_New(osize, max);
11995 if (repr == NULL)
11996 return NULL;
11997 okind = PyUnicode_KIND(repr);
11998 odata = PyUnicode_DATA(repr);
11999
12000 PyUnicode_WRITE(okind, odata, 0, quote);
12001 PyUnicode_WRITE(okind, odata, osize-1, quote);
12002
12003 for (i = 0, o = 1; i < isize; i++) {
12004 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012005
12006 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if ((ch == quote) || (ch == '\\')) {
12008 PyUnicode_WRITE(okind, odata, o++, '\\');
12009 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012010 continue;
12011 }
12012
Benjamin Peterson29060642009-01-31 22:14:21 +000012013 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012014 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 PyUnicode_WRITE(okind, odata, o++, '\\');
12016 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012017 }
12018 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 PyUnicode_WRITE(okind, odata, o++, '\\');
12020 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012021 }
12022 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 PyUnicode_WRITE(okind, odata, o++, '\\');
12024 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012025 }
12026
12027 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012028 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 PyUnicode_WRITE(okind, odata, o++, '\\');
12030 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012031 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12032 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012033 }
12034
Georg Brandl559e5d72008-06-11 18:37:52 +000012035 /* Copy ASCII characters as-is */
12036 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012038 }
12039
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012041 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012042 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012043 (categories Z* and C* except ASCII space)
12044 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012046 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012047 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012050 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12051 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012052 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012053 /* Map 16-bit characters to '\uxxxx' */
12054 else if (ch <= 0xffff) {
12055 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12058 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12059 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012060 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012061 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012062 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012063 PyUnicode_WRITE(okind, odata, o++, 'U');
12064 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12069 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12070 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12071 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012072 }
12073 }
12074 /* Copy characters as-is */
12075 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012076 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012077 }
12078 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012081 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012082 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083}
12084
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012085PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012086 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087\n\
12088Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012089such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090arguments start and end are interpreted as in slice notation.\n\
12091\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012092Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093
12094static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012097 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012098 Py_ssize_t start;
12099 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012100 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101
Jesus Ceaac451502011-04-20 17:09:23 +020012102 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12103 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012104 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012106 if (PyUnicode_READY(self) == -1)
12107 return NULL;
12108 if (PyUnicode_READY(substring) == -1)
12109 return NULL;
12110
Victor Stinner7931d9a2011-11-04 00:22:48 +010012111 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012112
12113 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 if (result == -2)
12116 return NULL;
12117
Christian Heimes217cfd12007-12-02 14:31:20 +000012118 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119}
12120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012121PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012122 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012124Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125
12126static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012129 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012130 Py_ssize_t start;
12131 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012132 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133
Jesus Ceaac451502011-04-20 17:09:23 +020012134 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12135 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 if (PyUnicode_READY(self) == -1)
12139 return NULL;
12140 if (PyUnicode_READY(substring) == -1)
12141 return NULL;
12142
Victor Stinner7931d9a2011-11-04 00:22:48 +010012143 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144
12145 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 if (result == -2)
12148 return NULL;
12149
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150 if (result < 0) {
12151 PyErr_SetString(PyExc_ValueError, "substring not found");
12152 return NULL;
12153 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154
Christian Heimes217cfd12007-12-02 14:31:20 +000012155 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156}
12157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012158PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012161Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012162done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163
12164static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012165unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012167 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 Py_UCS4 fillchar = ' ';
12169
Victor Stinnere9a29352011-10-01 02:14:59 +020012170 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012171 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012172
Benjamin Petersonbac79492012-01-14 13:34:47 -050012173 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174 return NULL;
12175
Victor Stinnerc4b49542011-12-11 22:44:26 +010012176 if (PyUnicode_GET_LENGTH(self) >= width)
12177 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178
Victor Stinnerc4b49542011-12-11 22:44:26 +010012179 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180}
12181
Alexander Belopolsky40018472011-02-26 01:02:56 +000012182PyObject *
12183PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184{
12185 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012186
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187 s = PyUnicode_FromObject(s);
12188 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012189 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012190 if (sep != NULL) {
12191 sep = PyUnicode_FromObject(sep);
12192 if (sep == NULL) {
12193 Py_DECREF(s);
12194 return NULL;
12195 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 }
12197
Victor Stinner9310abb2011-10-05 00:59:23 +020012198 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199
12200 Py_DECREF(s);
12201 Py_XDECREF(sep);
12202 return result;
12203}
12204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012205PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012206 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207\n\
12208Return a list of the words in S, using sep as the\n\
12209delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012210splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012211whitespace string is a separator and empty strings are\n\
12212removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
12214static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012215unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012217 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012219 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012221 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12222 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223 return NULL;
12224
12225 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012226 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012228 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012230 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231}
12232
Thomas Wouters477c8d52006-05-27 19:21:47 +000012233PyObject *
12234PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12235{
12236 PyObject* str_obj;
12237 PyObject* sep_obj;
12238 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 int kind1, kind2, kind;
12240 void *buf1 = NULL, *buf2 = NULL;
12241 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012242
12243 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012244 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012245 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012246 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012247 if (!sep_obj) {
12248 Py_DECREF(str_obj);
12249 return NULL;
12250 }
12251 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12252 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012253 Py_DECREF(str_obj);
12254 return NULL;
12255 }
12256
Victor Stinner14f8f022011-10-05 20:58:25 +020012257 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012259 kind = Py_MAX(kind1, kind2);
12260 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012262 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 if (!buf1)
12264 goto onError;
12265 buf2 = PyUnicode_DATA(sep_obj);
12266 if (kind2 != kind)
12267 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12268 if (!buf2)
12269 goto onError;
12270 len1 = PyUnicode_GET_LENGTH(str_obj);
12271 len2 = PyUnicode_GET_LENGTH(sep_obj);
12272
Benjamin Petersonead6b532011-12-20 17:23:42 -060012273 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012274 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012275 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12276 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12277 else
12278 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012279 break;
12280 case PyUnicode_2BYTE_KIND:
12281 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12282 break;
12283 case PyUnicode_4BYTE_KIND:
12284 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12285 break;
12286 default:
12287 assert(0);
12288 out = 0;
12289 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012290
12291 Py_DECREF(sep_obj);
12292 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 if (kind1 != kind)
12294 PyMem_Free(buf1);
12295 if (kind2 != kind)
12296 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012297
12298 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 onError:
12300 Py_DECREF(sep_obj);
12301 Py_DECREF(str_obj);
12302 if (kind1 != kind && buf1)
12303 PyMem_Free(buf1);
12304 if (kind2 != kind && buf2)
12305 PyMem_Free(buf2);
12306 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012307}
12308
12309
12310PyObject *
12311PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12312{
12313 PyObject* str_obj;
12314 PyObject* sep_obj;
12315 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 int kind1, kind2, kind;
12317 void *buf1 = NULL, *buf2 = NULL;
12318 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012319
12320 str_obj = PyUnicode_FromObject(str_in);
12321 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012322 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012323 sep_obj = PyUnicode_FromObject(sep_in);
12324 if (!sep_obj) {
12325 Py_DECREF(str_obj);
12326 return NULL;
12327 }
12328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012329 kind1 = PyUnicode_KIND(str_in);
12330 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012331 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 buf1 = PyUnicode_DATA(str_in);
12333 if (kind1 != kind)
12334 buf1 = _PyUnicode_AsKind(str_in, kind);
12335 if (!buf1)
12336 goto onError;
12337 buf2 = PyUnicode_DATA(sep_obj);
12338 if (kind2 != kind)
12339 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12340 if (!buf2)
12341 goto onError;
12342 len1 = PyUnicode_GET_LENGTH(str_obj);
12343 len2 = PyUnicode_GET_LENGTH(sep_obj);
12344
Benjamin Petersonead6b532011-12-20 17:23:42 -060012345 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012347 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12348 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12349 else
12350 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 break;
12352 case PyUnicode_2BYTE_KIND:
12353 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12354 break;
12355 case PyUnicode_4BYTE_KIND:
12356 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12357 break;
12358 default:
12359 assert(0);
12360 out = 0;
12361 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012362
12363 Py_DECREF(sep_obj);
12364 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 if (kind1 != kind)
12366 PyMem_Free(buf1);
12367 if (kind2 != kind)
12368 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369
12370 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371 onError:
12372 Py_DECREF(sep_obj);
12373 Py_DECREF(str_obj);
12374 if (kind1 != kind && buf1)
12375 PyMem_Free(buf1);
12376 if (kind2 != kind && buf2)
12377 PyMem_Free(buf2);
12378 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012379}
12380
12381PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012382 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012383\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012384Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012385the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012386found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012387
12388static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012389unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012390{
Victor Stinner9310abb2011-10-05 00:59:23 +020012391 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012392}
12393
12394PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012395 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012396\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012397Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012398the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012399separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012400
12401static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012402unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012403{
Victor Stinner9310abb2011-10-05 00:59:23 +020012404 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012405}
12406
Alexander Belopolsky40018472011-02-26 01:02:56 +000012407PyObject *
12408PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012409{
12410 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012411
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012412 s = PyUnicode_FromObject(s);
12413 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012414 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012415 if (sep != NULL) {
12416 sep = PyUnicode_FromObject(sep);
12417 if (sep == NULL) {
12418 Py_DECREF(s);
12419 return NULL;
12420 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012421 }
12422
Victor Stinner9310abb2011-10-05 00:59:23 +020012423 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012424
12425 Py_DECREF(s);
12426 Py_XDECREF(sep);
12427 return result;
12428}
12429
12430PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012431 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012432\n\
12433Return a list of the words in S, using sep as the\n\
12434delimiter string, starting at the end of the string and\n\
12435working to the front. If maxsplit is given, at most maxsplit\n\
12436splits are done. If sep is not specified, any whitespace string\n\
12437is a separator.");
12438
12439static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012440unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012441{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012442 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012443 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012444 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012445
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012446 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12447 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012448 return NULL;
12449
12450 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012451 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012452 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012453 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012454 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012455 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012456}
12457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012458PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012459 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460\n\
12461Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012462Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012463is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464
12465static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012466unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012467{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012468 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012469 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012471 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12472 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473 return NULL;
12474
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012475 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476}
12477
12478static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012479PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012480{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012481 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482}
12483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012484PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012485 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486\n\
12487Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012488and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489
12490static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012491unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012493 if (PyUnicode_READY(self) == -1)
12494 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012495 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496}
12497
Georg Brandlceee0772007-11-27 23:48:05 +000012498PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012499 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012500\n\
12501Return a translation table usable for str.translate().\n\
12502If there is only one argument, it must be a dictionary mapping Unicode\n\
12503ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012504Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012505If there are two arguments, they must be strings of equal length, and\n\
12506in the resulting dictionary, each character in x will be mapped to the\n\
12507character at the same position in y. If there is a third argument, it\n\
12508must be a string, whose characters will be mapped to None in the result.");
12509
12510static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012511unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012512{
12513 PyObject *x, *y = NULL, *z = NULL;
12514 PyObject *new = NULL, *key, *value;
12515 Py_ssize_t i = 0;
12516 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012517
Georg Brandlceee0772007-11-27 23:48:05 +000012518 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12519 return NULL;
12520 new = PyDict_New();
12521 if (!new)
12522 return NULL;
12523 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012524 int x_kind, y_kind, z_kind;
12525 void *x_data, *y_data, *z_data;
12526
Georg Brandlceee0772007-11-27 23:48:05 +000012527 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012528 if (!PyUnicode_Check(x)) {
12529 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12530 "be a string if there is a second argument");
12531 goto err;
12532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012534 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12535 "arguments must have equal length");
12536 goto err;
12537 }
12538 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 x_kind = PyUnicode_KIND(x);
12540 y_kind = PyUnicode_KIND(y);
12541 x_data = PyUnicode_DATA(x);
12542 y_data = PyUnicode_DATA(y);
12543 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12544 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012545 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012546 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012547 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012548 if (!value) {
12549 Py_DECREF(key);
12550 goto err;
12551 }
Georg Brandlceee0772007-11-27 23:48:05 +000012552 res = PyDict_SetItem(new, key, value);
12553 Py_DECREF(key);
12554 Py_DECREF(value);
12555 if (res < 0)
12556 goto err;
12557 }
12558 /* create entries for deleting chars in z */
12559 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 z_kind = PyUnicode_KIND(z);
12561 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012562 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012564 if (!key)
12565 goto err;
12566 res = PyDict_SetItem(new, key, Py_None);
12567 Py_DECREF(key);
12568 if (res < 0)
12569 goto err;
12570 }
12571 }
12572 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 int kind;
12574 void *data;
12575
Georg Brandlceee0772007-11-27 23:48:05 +000012576 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012577 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012578 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12579 "to maketrans it must be a dict");
12580 goto err;
12581 }
12582 /* copy entries into the new dict, converting string keys to int keys */
12583 while (PyDict_Next(x, &i, &key, &value)) {
12584 if (PyUnicode_Check(key)) {
12585 /* convert string keys to integer keys */
12586 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012587 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012588 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12589 "table must be of length 1");
12590 goto err;
12591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 kind = PyUnicode_KIND(key);
12593 data = PyUnicode_DATA(key);
12594 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012595 if (!newkey)
12596 goto err;
12597 res = PyDict_SetItem(new, newkey, value);
12598 Py_DECREF(newkey);
12599 if (res < 0)
12600 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012601 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012602 /* just keep integer keys */
12603 if (PyDict_SetItem(new, key, value) < 0)
12604 goto err;
12605 } else {
12606 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12607 "be strings or integers");
12608 goto err;
12609 }
12610 }
12611 }
12612 return new;
12613 err:
12614 Py_DECREF(new);
12615 return NULL;
12616}
12617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012618PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012619 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620\n\
12621Return a copy of the string S, where all characters have been mapped\n\
12622through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012623Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012624Unmapped characters are left untouched. Characters mapped to None\n\
12625are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626
12627static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012628unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631}
12632
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012633PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012634 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012636Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637
12638static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012639unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012641 if (PyUnicode_READY(self) == -1)
12642 return NULL;
12643 if (PyUnicode_IS_ASCII(self))
12644 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012645 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646}
12647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012648PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012649 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012651Pad a numeric string S with zeros on the left, to fill a field\n\
12652of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653
12654static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012655unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012657 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012658 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012659 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 int kind;
12661 void *data;
12662 Py_UCS4 chr;
12663
Martin v. Löwis18e16552006-02-15 17:27:45 +000012664 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665 return NULL;
12666
Benjamin Petersonbac79492012-01-14 13:34:47 -050012667 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012668 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669
Victor Stinnerc4b49542011-12-11 22:44:26 +010012670 if (PyUnicode_GET_LENGTH(self) >= width)
12671 return unicode_result_unchanged(self);
12672
12673 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674
12675 u = pad(self, fill, 0, '0');
12676
Walter Dörwald068325e2002-04-15 13:36:47 +000012677 if (u == NULL)
12678 return NULL;
12679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 kind = PyUnicode_KIND(u);
12681 data = PyUnicode_DATA(u);
12682 chr = PyUnicode_READ(kind, data, fill);
12683
12684 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 PyUnicode_WRITE(kind, data, 0, chr);
12687 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688 }
12689
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012690 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012691 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693
12694#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012695static PyObject *
12696unicode__decimal2ascii(PyObject *self)
12697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012699}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700#endif
12701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012702PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012703 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012705Return True if S starts with the specified prefix, False otherwise.\n\
12706With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012707With optional end, stop comparing S at that position.\n\
12708prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709
12710static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012711unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012712 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012714 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012715 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012716 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012717 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012718 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719
Jesus Ceaac451502011-04-20 17:09:23 +020012720 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012721 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012722 if (PyTuple_Check(subobj)) {
12723 Py_ssize_t i;
12724 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012725 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012726 if (substring == NULL)
12727 return NULL;
12728 result = tailmatch(self, substring, start, end, -1);
12729 Py_DECREF(substring);
12730 if (result) {
12731 Py_RETURN_TRUE;
12732 }
12733 }
12734 /* nothing matched */
12735 Py_RETURN_FALSE;
12736 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012737 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012738 if (substring == NULL) {
12739 if (PyErr_ExceptionMatches(PyExc_TypeError))
12740 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12741 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012742 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012743 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012744 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012746 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747}
12748
12749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012750PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012753Return True if S ends with the specified suffix, False otherwise.\n\
12754With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012755With optional end, stop comparing S at that position.\n\
12756suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757
12758static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012759unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012760 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012762 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012763 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012764 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012765 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012766 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767
Jesus Ceaac451502011-04-20 17:09:23 +020012768 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012769 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012770 if (PyTuple_Check(subobj)) {
12771 Py_ssize_t i;
12772 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012773 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012774 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012776 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012777 result = tailmatch(self, substring, start, end, +1);
12778 Py_DECREF(substring);
12779 if (result) {
12780 Py_RETURN_TRUE;
12781 }
12782 }
12783 Py_RETURN_FALSE;
12784 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012785 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012786 if (substring == NULL) {
12787 if (PyErr_ExceptionMatches(PyExc_TypeError))
12788 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12789 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012790 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012791 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012792 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012794 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795}
12796
Victor Stinner202fdca2012-05-07 12:47:02 +020012797Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012798_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012799{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012800 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012801 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12802 writer->data = PyUnicode_DATA(writer->buffer);
12803 writer->kind = PyUnicode_KIND(writer->buffer);
12804}
12805
Victor Stinnerd3f08822012-05-29 12:57:52 +020012806void
12807_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012808{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012809 memset(writer, 0, sizeof(*writer));
12810#ifdef Py_DEBUG
12811 writer->kind = 5; /* invalid kind */
12812#endif
12813 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012814 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012815}
12816
Victor Stinnerd3f08822012-05-29 12:57:52 +020012817int
12818_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12819 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012820{
12821 Py_ssize_t newlen;
12822 PyObject *newbuffer;
12823
Victor Stinnerd3f08822012-05-29 12:57:52 +020012824 assert(length > 0);
12825
Victor Stinner202fdca2012-05-07 12:47:02 +020012826 if (length > PY_SSIZE_T_MAX - writer->pos) {
12827 PyErr_NoMemory();
12828 return -1;
12829 }
12830 newlen = writer->pos + length;
12831
Victor Stinnerd3f08822012-05-29 12:57:52 +020012832 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012833 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012834 /* overallocate 25% to limit the number of resize */
12835 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12836 newlen += newlen / 4;
12837 if (newlen < writer->min_length)
12838 newlen = writer->min_length;
12839 }
12840 writer->buffer = PyUnicode_New(newlen, maxchar);
12841 if (writer->buffer == NULL)
12842 return -1;
12843 _PyUnicodeWriter_Update(writer);
12844 return 0;
12845 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012846
Victor Stinnerd3f08822012-05-29 12:57:52 +020012847 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012848 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012849 /* overallocate 25% to limit the number of resize */
12850 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12851 newlen += newlen / 4;
12852 if (newlen < writer->min_length)
12853 newlen = writer->min_length;
12854 }
12855
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012856 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012857 /* resize + widen */
12858 newbuffer = PyUnicode_New(newlen, maxchar);
12859 if (newbuffer == NULL)
12860 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012861 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12862 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012863 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012864 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012865 }
12866 else {
12867 newbuffer = resize_compact(writer->buffer, newlen);
12868 if (newbuffer == NULL)
12869 return -1;
12870 }
12871 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012872 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012873 }
12874 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012875 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012876 newbuffer = PyUnicode_New(writer->size, maxchar);
12877 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012878 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012879 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12880 writer->buffer, 0, writer->pos);
12881 Py_DECREF(writer->buffer);
12882 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012883 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012884 }
12885 return 0;
12886}
12887
Victor Stinnerd3f08822012-05-29 12:57:52 +020012888int
12889_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12890{
12891 Py_UCS4 maxchar;
12892 Py_ssize_t len;
12893
12894 if (PyUnicode_READY(str) == -1)
12895 return -1;
12896 len = PyUnicode_GET_LENGTH(str);
12897 if (len == 0)
12898 return 0;
12899 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12900 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012901 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012902 Py_INCREF(str);
12903 writer->buffer = str;
12904 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012905 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012906 writer->size = 0;
12907 writer->pos += len;
12908 return 0;
12909 }
12910 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12911 return -1;
12912 }
12913 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12914 str, 0, len);
12915 writer->pos += len;
12916 return 0;
12917}
12918
12919PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012920_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012921{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012922 if (writer->pos == 0) {
12923 Py_XDECREF(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020012924 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020012925 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012926 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012927 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12928 return writer->buffer;
12929 }
12930 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12931 PyObject *newbuffer;
12932 newbuffer = resize_compact(writer->buffer, writer->pos);
12933 if (newbuffer == NULL) {
12934 Py_DECREF(writer->buffer);
12935 return NULL;
12936 }
12937 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012938 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012939 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012940 return writer->buffer;
12941}
12942
Victor Stinnerd3f08822012-05-29 12:57:52 +020012943void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012944_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012945{
12946 Py_CLEAR(writer->buffer);
12947}
12948
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012949#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012950
12951PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012952 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012953\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012954Return a formatted version of S, using substitutions from args and kwargs.\n\
12955The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012956
Eric Smith27bbca62010-11-04 17:06:58 +000012957PyDoc_STRVAR(format_map__doc__,
12958 "S.format_map(mapping) -> str\n\
12959\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012960Return a formatted version of S, using substitutions from mapping.\n\
12961The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012962
Eric Smith4a7d76d2008-05-30 18:10:19 +000012963static PyObject *
12964unicode__format__(PyObject* self, PyObject* args)
12965{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012966 PyObject *format_spec;
12967 _PyUnicodeWriter writer;
12968 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012969
12970 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12971 return NULL;
12972
Victor Stinnerd3f08822012-05-29 12:57:52 +020012973 if (PyUnicode_READY(self) == -1)
12974 return NULL;
12975 _PyUnicodeWriter_Init(&writer, 0);
12976 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12977 self, format_spec, 0,
12978 PyUnicode_GET_LENGTH(format_spec));
12979 if (ret == -1) {
12980 _PyUnicodeWriter_Dealloc(&writer);
12981 return NULL;
12982 }
12983 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012984}
12985
Eric Smith8c663262007-08-25 02:26:07 +000012986PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012987 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012988\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012989Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012990
12991static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012992unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 Py_ssize_t size;
12995
12996 /* If it's a compact object, account for base structure +
12997 character data. */
12998 if (PyUnicode_IS_COMPACT_ASCII(v))
12999 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13000 else if (PyUnicode_IS_COMPACT(v))
13001 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013002 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 else {
13004 /* If it is a two-block object, account for base object, and
13005 for character block if present. */
13006 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013007 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013009 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010 }
13011 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013012 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013013 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013015 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013016 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017
13018 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013019}
13020
13021PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013022 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013023
13024static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013025unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013026{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013027 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013028 if (!copy)
13029 return NULL;
13030 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013031}
13032
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013034 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013035 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013036 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13037 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013038 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13039 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013040 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013041 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13042 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13043 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13044 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13045 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013047 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13048 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13049 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013050 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013051 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13052 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13053 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013054 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013055 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013056 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013057 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013058 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13059 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13060 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13061 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13062 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13063 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13064 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13065 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13066 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13067 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13068 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13069 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13070 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13071 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013072 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013073 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013074 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013075 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013076 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013077 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013078 {"maketrans", (PyCFunction) unicode_maketrans,
13079 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013080 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013081#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013082 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013083 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084#endif
13085
Benjamin Peterson14339b62009-01-31 16:36:08 +000013086 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087 {NULL, NULL}
13088};
13089
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013090static PyObject *
13091unicode_mod(PyObject *v, PyObject *w)
13092{
Brian Curtindfc80e32011-08-10 20:28:54 -050013093 if (!PyUnicode_Check(v))
13094 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013096}
13097
13098static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013099 0, /*nb_add*/
13100 0, /*nb_subtract*/
13101 0, /*nb_multiply*/
13102 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013103};
13104
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013106 (lenfunc) unicode_length, /* sq_length */
13107 PyUnicode_Concat, /* sq_concat */
13108 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13109 (ssizeargfunc) unicode_getitem, /* sq_item */
13110 0, /* sq_slice */
13111 0, /* sq_ass_item */
13112 0, /* sq_ass_slice */
13113 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114};
13115
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013116static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013117unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 if (PyUnicode_READY(self) == -1)
13120 return NULL;
13121
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013122 if (PyIndex_Check(item)) {
13123 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013124 if (i == -1 && PyErr_Occurred())
13125 return NULL;
13126 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013128 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013129 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013130 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013131 PyObject *result;
13132 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013133 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013134 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013137 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013138 return NULL;
13139 }
13140
13141 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013142 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013144 slicelength == PyUnicode_GET_LENGTH(self)) {
13145 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013146 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013147 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013148 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013149 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013150 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013151 src_kind = PyUnicode_KIND(self);
13152 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013153 if (!PyUnicode_IS_ASCII(self)) {
13154 kind_limit = kind_maxchar_limit(src_kind);
13155 max_char = 0;
13156 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13157 ch = PyUnicode_READ(src_kind, src_data, cur);
13158 if (ch > max_char) {
13159 max_char = ch;
13160 if (max_char >= kind_limit)
13161 break;
13162 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013163 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013164 }
Victor Stinner55c99112011-10-13 01:17:06 +020013165 else
13166 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013167 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013168 if (result == NULL)
13169 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013170 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013171 dest_data = PyUnicode_DATA(result);
13172
13173 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013174 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13175 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013176 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013177 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013178 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013179 } else {
13180 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13181 return NULL;
13182 }
13183}
13184
13185static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013186 (lenfunc)unicode_length, /* mp_length */
13187 (binaryfunc)unicode_subscript, /* mp_subscript */
13188 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013189};
13190
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192/* Helpers for PyUnicode_Format() */
13193
13194static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013195getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013197 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 (*p_argidx)++;
13200 if (arglen < 0)
13201 return args;
13202 else
13203 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204 }
13205 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013206 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207 return NULL;
13208}
13209
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013210/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211
Victor Stinnerd3f08822012-05-29 12:57:52 +020013212static int
13213formatfloat(PyObject *v, int flags, int prec, int type,
13214 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013216 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013218 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013219
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220 x = PyFloat_AsDouble(v);
13221 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013222 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013223
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013225 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013226
Eric Smith0923d1d2009-04-16 20:16:10 +000013227 p = PyOS_double_to_string(x, type, prec,
13228 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013229 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013230 return -1;
13231 len = strlen(p);
13232 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013233 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13234 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013235 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013236 }
Victor Stinner184252a2012-06-16 02:57:41 +020013237 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013238 writer->pos += len;
13239 }
13240 else
13241 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013242 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013243 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013244}
13245
Victor Stinnerd0880d52012-04-27 23:40:13 +020013246/* formatlong() emulates the format codes d, u, o, x and X, and
13247 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13248 * Python's regular ints.
13249 * Return value: a new PyUnicodeObject*, or NULL if error.
13250 * The output string is of the form
13251 * "-"? ("0x" | "0X")? digit+
13252 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13253 * set in flags. The case of hex digits will be correct,
13254 * There will be at least prec digits, zero-filled on the left if
13255 * necessary to get that many.
13256 * val object to be converted
13257 * flags bitmask of format flags; only F_ALT is looked at
13258 * prec minimum number of digits; 0-fill on left if needed
13259 * type a character in [duoxX]; u acts the same as d
13260 *
13261 * CAUTION: o, x and X conversions on regular ints can never
13262 * produce a '-' sign, but can for Python's unbounded ints.
13263 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013264static PyObject*
13265formatlong(PyObject *val, int flags, int prec, int type)
13266{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013267 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013268 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013269 Py_ssize_t i;
13270 int sign; /* 1 if '-', else 0 */
13271 int len; /* number of characters */
13272 Py_ssize_t llen;
13273 int numdigits; /* len == numnondigits + numdigits */
13274 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013275
Victor Stinnerd0880d52012-04-27 23:40:13 +020013276 /* Avoid exceeding SSIZE_T_MAX */
13277 if (prec > INT_MAX-3) {
13278 PyErr_SetString(PyExc_OverflowError,
13279 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013280 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013281 }
13282
13283 assert(PyLong_Check(val));
13284
13285 switch (type) {
13286 case 'd':
13287 case 'u':
13288 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013289 if (PyBool_Check(val))
13290 result = PyNumber_ToBase(val, 10);
13291 else
13292 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013293 break;
13294 case 'o':
13295 numnondigits = 2;
13296 result = PyNumber_ToBase(val, 8);
13297 break;
13298 case 'x':
13299 case 'X':
13300 numnondigits = 2;
13301 result = PyNumber_ToBase(val, 16);
13302 break;
13303 default:
13304 assert(!"'type' not in [duoxX]");
13305 }
13306 if (!result)
13307 return NULL;
13308
13309 assert(unicode_modifiable(result));
13310 assert(PyUnicode_IS_READY(result));
13311 assert(PyUnicode_IS_ASCII(result));
13312
13313 /* To modify the string in-place, there can only be one reference. */
13314 if (Py_REFCNT(result) != 1) {
13315 PyErr_BadInternalCall();
13316 return NULL;
13317 }
13318 buf = PyUnicode_DATA(result);
13319 llen = PyUnicode_GET_LENGTH(result);
13320 if (llen > INT_MAX) {
13321 PyErr_SetString(PyExc_ValueError,
13322 "string too large in _PyBytes_FormatLong");
13323 return NULL;
13324 }
13325 len = (int)llen;
13326 sign = buf[0] == '-';
13327 numnondigits += sign;
13328 numdigits = len - numnondigits;
13329 assert(numdigits > 0);
13330
13331 /* Get rid of base marker unless F_ALT */
13332 if (((flags & F_ALT) == 0 &&
13333 (type == 'o' || type == 'x' || type == 'X'))) {
13334 assert(buf[sign] == '0');
13335 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13336 buf[sign+1] == 'o');
13337 numnondigits -= 2;
13338 buf += 2;
13339 len -= 2;
13340 if (sign)
13341 buf[0] = '-';
13342 assert(len == numnondigits + numdigits);
13343 assert(numdigits > 0);
13344 }
13345
13346 /* Fill with leading zeroes to meet minimum width. */
13347 if (prec > numdigits) {
13348 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13349 numnondigits + prec);
13350 char *b1;
13351 if (!r1) {
13352 Py_DECREF(result);
13353 return NULL;
13354 }
13355 b1 = PyBytes_AS_STRING(r1);
13356 for (i = 0; i < numnondigits; ++i)
13357 *b1++ = *buf++;
13358 for (i = 0; i < prec - numdigits; i++)
13359 *b1++ = '0';
13360 for (i = 0; i < numdigits; i++)
13361 *b1++ = *buf++;
13362 *b1 = '\0';
13363 Py_DECREF(result);
13364 result = r1;
13365 buf = PyBytes_AS_STRING(result);
13366 len = numnondigits + prec;
13367 }
13368
13369 /* Fix up case for hex conversions. */
13370 if (type == 'X') {
13371 /* Need to convert all lower case letters to upper case.
13372 and need to convert 0x to 0X (and -0x to -0X). */
13373 for (i = 0; i < len; i++)
13374 if (buf[i] >= 'a' && buf[i] <= 'x')
13375 buf[i] -= 'a'-'A';
13376 }
13377 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13378 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013379 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013380 Py_DECREF(result);
13381 result = unicode;
13382 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013383 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013384}
13385
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013386static Py_UCS4
13387formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013389 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013390 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013391 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013392 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 goto onError;
13395 }
13396 else {
13397 /* Integer input truncated to a character */
13398 long x;
13399 x = PyLong_AsLong(v);
13400 if (x == -1 && PyErr_Occurred())
13401 goto onError;
13402
Victor Stinner8faf8212011-12-08 22:14:11 +010013403 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 PyErr_SetString(PyExc_OverflowError,
13405 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013406 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 }
13408
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013409 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013410 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013411
Benjamin Peterson29060642009-01-31 22:14:21 +000013412 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013413 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013415 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013416}
13417
Alexander Belopolsky40018472011-02-26 01:02:56 +000013418PyObject *
13419PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013420{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013421 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013423 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013424 PyObject *temp = NULL;
13425 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013426 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013427 void *fmt;
13428 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013429 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013430 Py_ssize_t sublen;
13431 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013432
Guido van Rossumd57fd912000-03-10 22:53:23 +000013433 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013434 PyErr_BadInternalCall();
13435 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013436 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013437 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013438 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013439 return NULL;
Victor Stinner19294072012-10-05 00:09:33 +020013440 if (PyUnicode_READY(uformat) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013441 Py_DECREF(uformat);
Victor Stinner19294072012-10-05 00:09:33 +020013442 return NULL;
13443 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013445 fmt = PyUnicode_DATA(uformat);
13446 fmtkind = PyUnicode_KIND(uformat);
13447 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13448 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013449
Victor Stinnerd3f08822012-05-29 12:57:52 +020013450 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013451
Guido van Rossumd57fd912000-03-10 22:53:23 +000013452 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013453 arglen = PyTuple_Size(args);
13454 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013455 }
13456 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 arglen = -1;
13458 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013459 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013460 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013461 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013462
13463 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013464 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013465 Py_ssize_t nonfmtpos;
13466 nonfmtpos = fmtpos++;
13467 while (fmtcnt >= 0 &&
13468 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13469 fmtpos++;
13470 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013471 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013472 if (fmtcnt < 0)
13473 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013474 sublen = fmtpos - nonfmtpos;
13475 maxchar = _PyUnicode_FindMaxChar(uformat,
13476 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013477 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013478 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013479
Victor Stinnerd3f08822012-05-29 12:57:52 +020013480 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13481 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013482 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013483 }
13484 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 /* Got a format specifier */
13486 int flags = 0;
13487 Py_ssize_t width = -1;
13488 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013489 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013490 Py_UCS4 fill;
13491 int sign;
13492 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013493 int isnumok;
13494 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013495 void *pbuf = NULL;
13496 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013497 Py_UCS4 bufmaxchar;
13498 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013500 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013501 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13502 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013503 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013504 Py_ssize_t keylen;
13505 PyObject *key;
13506 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013507
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 if (dict == NULL) {
13509 PyErr_SetString(PyExc_TypeError,
13510 "format requires a mapping");
13511 goto onError;
13512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013513 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013514 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013515 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 /* Skip over balanced parentheses */
13517 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013518 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13519 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013521 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013525 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 if (fmtcnt < 0 || pcount > 0) {
13527 PyErr_SetString(PyExc_ValueError,
13528 "incomplete format key");
13529 goto onError;
13530 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013531 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013532 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013533 if (key == NULL)
13534 goto onError;
13535 if (args_owned) {
13536 Py_DECREF(args);
13537 args_owned = 0;
13538 }
13539 args = PyObject_GetItem(dict, key);
13540 Py_DECREF(key);
13541 if (args == NULL) {
13542 goto onError;
13543 }
13544 args_owned = 1;
13545 arglen = -1;
13546 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013547 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013549 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13550 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 case '-': flags |= F_LJUST; continue;
13552 case '+': flags |= F_SIGN; continue;
13553 case ' ': flags |= F_BLANK; continue;
13554 case '#': flags |= F_ALT; continue;
13555 case '0': flags |= F_ZERO; continue;
13556 }
13557 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013558 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013559 if (c == '*') {
13560 v = getnextarg(args, arglen, &argidx);
13561 if (v == NULL)
13562 goto onError;
13563 if (!PyLong_Check(v)) {
13564 PyErr_SetString(PyExc_TypeError,
13565 "* wants int");
13566 goto onError;
13567 }
Serhiy Storchaka441d30f2013-01-19 12:26:26 +020013568 width = PyLong_AsSsize_t(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 if (width == -1 && PyErr_Occurred())
13570 goto onError;
13571 if (width < 0) {
13572 flags |= F_LJUST;
13573 width = -width;
13574 }
13575 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013576 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013577 }
13578 else if (c >= '0' && c <= '9') {
13579 width = c - '0';
13580 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013581 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013582 if (c < '0' || c > '9')
13583 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013584 /* Since c is unsigned, the RHS would end up as unsigned,
13585 mixing signed and unsigned comparison. Since c is between
13586 '0' and '9', casting to int is safe. */
13587 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 PyErr_SetString(PyExc_ValueError,
13589 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013590 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 }
13592 width = width*10 + (c - '0');
13593 }
13594 }
13595 if (c == '.') {
13596 prec = 0;
13597 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013598 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013599 if (c == '*') {
13600 v = getnextarg(args, arglen, &argidx);
13601 if (v == NULL)
13602 goto onError;
13603 if (!PyLong_Check(v)) {
13604 PyErr_SetString(PyExc_TypeError,
13605 "* wants int");
13606 goto onError;
13607 }
Serhiy Storchaka441d30f2013-01-19 12:26:26 +020013608 prec = _PyLong_AsInt(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013609 if (prec == -1 && PyErr_Occurred())
13610 goto onError;
13611 if (prec < 0)
13612 prec = 0;
13613 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013614 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 }
13616 else if (c >= '0' && c <= '9') {
13617 prec = c - '0';
13618 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013619 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013620 if (c < '0' || c > '9')
13621 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013622 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013623 PyErr_SetString(PyExc_ValueError,
13624 "prec too big");
13625 goto onError;
13626 }
13627 prec = prec*10 + (c - '0');
13628 }
13629 }
13630 } /* prec */
13631 if (fmtcnt >= 0) {
13632 if (c == 'h' || c == 'l' || c == 'L') {
13633 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013634 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 }
13636 }
13637 if (fmtcnt < 0) {
13638 PyErr_SetString(PyExc_ValueError,
13639 "incomplete format");
13640 goto onError;
13641 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013642 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013643 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013644
13645 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013646 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013647 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013648 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13649 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013650 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013652
Victor Stinneraff3cc62012-04-30 05:19:21 +020013653 v = getnextarg(args, arglen, &argidx);
13654 if (v == NULL)
13655 goto onError;
13656
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013658 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013659 fill = ' ';
13660 switch (c) {
13661
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 case 's':
13663 case 'r':
13664 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013665 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13666 /* Fast path */
13667 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13668 goto onError;
13669 goto nextarg;
13670 }
13671
Victor Stinner808fc0a2010-03-22 12:50:40 +000013672 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013673 temp = v;
13674 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013675 }
13676 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013677 if (c == 's')
13678 temp = PyObject_Str(v);
13679 else if (c == 'r')
13680 temp = PyObject_Repr(v);
13681 else
13682 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 break;
13685
13686 case 'i':
13687 case 'd':
13688 case 'u':
13689 case 'o':
13690 case 'x':
13691 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013692 if (PyLong_CheckExact(v)
13693 && width == -1 && prec == -1
13694 && !(flags & (F_SIGN | F_BLANK)))
13695 {
13696 /* Fast path */
13697 switch(c)
13698 {
13699 case 'd':
13700 case 'i':
13701 case 'u':
13702 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13703 goto onError;
13704 goto nextarg;
13705 case 'x':
13706 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13707 goto onError;
13708 goto nextarg;
13709 case 'o':
13710 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13711 goto onError;
13712 goto nextarg;
13713 default:
13714 break;
13715 }
13716 }
13717
Benjamin Peterson29060642009-01-31 22:14:21 +000013718 isnumok = 0;
13719 if (PyNumber_Check(v)) {
13720 PyObject *iobj=NULL;
13721
13722 if (PyLong_Check(v)) {
13723 iobj = v;
13724 Py_INCREF(iobj);
13725 }
13726 else {
13727 iobj = PyNumber_Long(v);
13728 }
13729 if (iobj!=NULL) {
13730 if (PyLong_Check(iobj)) {
13731 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013732 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013733 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013735 }
13736 else {
13737 Py_DECREF(iobj);
13738 }
13739 }
13740 }
13741 if (!isnumok) {
13742 PyErr_Format(PyExc_TypeError,
13743 "%%%c format: a number is required, "
13744 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13745 goto onError;
13746 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013747 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013748 fill = '0';
13749 break;
13750
13751 case 'e':
13752 case 'E':
13753 case 'f':
13754 case 'F':
13755 case 'g':
13756 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013757 if (width == -1 && prec == -1
13758 && !(flags & (F_SIGN | F_BLANK)))
13759 {
13760 /* Fast path */
13761 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13762 goto onError;
13763 goto nextarg;
13764 }
13765
Benjamin Peterson29060642009-01-31 22:14:21 +000013766 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013767 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013768 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013769 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13770 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013771 break;
13772
13773 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013774 {
13775 Py_UCS4 ch = formatchar(v);
13776 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013777 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013778 if (width == -1 && prec == -1) {
13779 /* Fast path */
13780 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13781 goto onError;
13782 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13783 writer.pos += 1;
13784 goto nextarg;
13785 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013786 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013787 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013788 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013789
13790 default:
13791 PyErr_Format(PyExc_ValueError,
13792 "unsupported format character '%c' (0x%x) "
13793 "at index %zd",
13794 (31<=c && c<=126) ? (char)c : '?',
13795 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013797 goto onError;
13798 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013799 if (temp == NULL)
13800 goto onError;
13801 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013802
13803 if (width == -1 && prec == -1
13804 && !(flags & (F_SIGN | F_BLANK)))
13805 {
13806 /* Fast path */
13807 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13808 goto onError;
13809 goto nextarg;
13810 }
13811
Victor Stinneraff3cc62012-04-30 05:19:21 +020013812 if (PyUnicode_READY(temp) == -1) {
13813 Py_CLEAR(temp);
13814 goto onError;
13815 }
13816 kind = PyUnicode_KIND(temp);
13817 pbuf = PyUnicode_DATA(temp);
13818 len = PyUnicode_GET_LENGTH(temp);
13819
13820 if (c == 's' || c == 'r' || c == 'a') {
13821 if (prec >= 0 && len > prec)
13822 len = prec;
13823 }
13824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013825 /* pbuf is initialized here. */
13826 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013827 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013828 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13829 if (ch == '-' || ch == '+') {
13830 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013831 len--;
13832 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013833 }
13834 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013835 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013837 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013838 else
13839 sign = 0;
13840 }
13841 if (width < len)
13842 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013843
13844 /* Compute the length and maximum character of the
13845 written characters */
13846 bufmaxchar = 127;
13847 if (!(flags & F_LJUST)) {
13848 if (sign) {
13849 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013851 }
13852 else {
13853 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013854 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013855 }
13856 }
13857 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013858 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013859
13860 buflen = width;
13861 if (sign && len == width)
13862 buflen++;
13863
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013864 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013865 goto onError;
13866
13867 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013868 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013869 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013870 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13871 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013872 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013873 if (width > len)
13874 width--;
13875 }
13876 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013877 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013879 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013880 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13881 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13882 writer.pos += 2;
13883 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013884 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013885 width -= 2;
13886 if (width < 0)
13887 width = 0;
13888 len -= 2;
13889 }
13890 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013891 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013892 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13893 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013894 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 }
13896 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013897 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013898 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13899 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013900 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013901 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013902 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13903 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013904 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13905 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13906 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013907 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013908 }
13909 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013910
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013911 if (len) {
13912 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13913 temp, pindex, len);
13914 writer.pos += len;
13915 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013916 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013917 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013918 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13919 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013920 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013921
Victor Stinnerd3f08822012-05-29 12:57:52 +020013922nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013923 if (dict && (argidx < arglen) && c != '%') {
13924 PyErr_SetString(PyExc_TypeError,
13925 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013926 goto onError;
13927 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013928 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013929 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013930 } /* until end */
13931 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013932 PyErr_SetString(PyExc_TypeError,
13933 "not all arguments converted during string formatting");
13934 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013935 }
13936
13937 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013938 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939 }
13940 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013941 Py_XDECREF(temp);
13942 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013943 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013944
Benjamin Peterson29060642009-01-31 22:14:21 +000013945 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013946 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013947 Py_XDECREF(temp);
13948 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013949 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013950 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013951 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013952 }
13953 return NULL;
13954}
13955
Jeremy Hylton938ace62002-07-17 16:30:39 +000013956static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013957unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13958
Tim Peters6d6c1a32001-08-02 04:15:00 +000013959static PyObject *
13960unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13961{
Benjamin Peterson29060642009-01-31 22:14:21 +000013962 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 static char *kwlist[] = {"object", "encoding", "errors", 0};
13964 char *encoding = NULL;
13965 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013966
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 if (type != &PyUnicode_Type)
13968 return unicode_subtype_new(type, args, kwds);
13969 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013970 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013971 return NULL;
13972 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020013973 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000013974 if (encoding == NULL && errors == NULL)
13975 return PyObject_Str(x);
13976 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013977 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013978}
13979
Guido van Rossume023fe02001-08-30 03:12:59 +000013980static PyObject *
13981unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13982{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013983 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013984 Py_ssize_t length, char_size;
13985 int share_wstr, share_utf8;
13986 unsigned int kind;
13987 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013988
Benjamin Peterson14339b62009-01-31 16:36:08 +000013989 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013990
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013991 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013992 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013993 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013994 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013995 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013996 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013997 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013998 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013999
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014000 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014001 if (self == NULL) {
14002 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014003 return NULL;
14004 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014005 kind = PyUnicode_KIND(unicode);
14006 length = PyUnicode_GET_LENGTH(unicode);
14007
14008 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014009#ifdef Py_DEBUG
14010 _PyUnicode_HASH(self) = -1;
14011#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014012 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014013#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014014 _PyUnicode_STATE(self).interned = 0;
14015 _PyUnicode_STATE(self).kind = kind;
14016 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014017 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014018 _PyUnicode_STATE(self).ready = 1;
14019 _PyUnicode_WSTR(self) = NULL;
14020 _PyUnicode_UTF8_LENGTH(self) = 0;
14021 _PyUnicode_UTF8(self) = NULL;
14022 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014023 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014024
14025 share_utf8 = 0;
14026 share_wstr = 0;
14027 if (kind == PyUnicode_1BYTE_KIND) {
14028 char_size = 1;
14029 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14030 share_utf8 = 1;
14031 }
14032 else if (kind == PyUnicode_2BYTE_KIND) {
14033 char_size = 2;
14034 if (sizeof(wchar_t) == 2)
14035 share_wstr = 1;
14036 }
14037 else {
14038 assert(kind == PyUnicode_4BYTE_KIND);
14039 char_size = 4;
14040 if (sizeof(wchar_t) == 4)
14041 share_wstr = 1;
14042 }
14043
14044 /* Ensure we won't overflow the length. */
14045 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14046 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014047 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014049 data = PyObject_MALLOC((length + 1) * char_size);
14050 if (data == NULL) {
14051 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014052 goto onError;
14053 }
14054
Victor Stinnerc3c74152011-10-02 20:39:55 +020014055 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014056 if (share_utf8) {
14057 _PyUnicode_UTF8_LENGTH(self) = length;
14058 _PyUnicode_UTF8(self) = data;
14059 }
14060 if (share_wstr) {
14061 _PyUnicode_WSTR_LENGTH(self) = length;
14062 _PyUnicode_WSTR(self) = (wchar_t *)data;
14063 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014064
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014065 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014066 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014067 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014068#ifdef Py_DEBUG
14069 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14070#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014071 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014072 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014073
14074onError:
14075 Py_DECREF(unicode);
14076 Py_DECREF(self);
14077 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014078}
14079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014080PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014081"str(object='') -> str\n\
14082str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014083\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014084Create a new string object from the given object. If encoding or\n\
14085errors is specified, then the object must expose a data buffer\n\
14086that will be decoded using the given encoding and error handler.\n\
14087Otherwise, returns the result of object.__str__() (if defined)\n\
14088or repr(object).\n\
14089encoding defaults to sys.getdefaultencoding().\n\
14090errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014091
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014092static PyObject *unicode_iter(PyObject *seq);
14093
Guido van Rossumd57fd912000-03-10 22:53:23 +000014094PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014095 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014096 "str", /* tp_name */
14097 sizeof(PyUnicodeObject), /* tp_size */
14098 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014099 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 (destructor)unicode_dealloc, /* tp_dealloc */
14101 0, /* tp_print */
14102 0, /* tp_getattr */
14103 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014104 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014105 unicode_repr, /* tp_repr */
14106 &unicode_as_number, /* tp_as_number */
14107 &unicode_as_sequence, /* tp_as_sequence */
14108 &unicode_as_mapping, /* tp_as_mapping */
14109 (hashfunc) unicode_hash, /* tp_hash*/
14110 0, /* tp_call*/
14111 (reprfunc) unicode_str, /* tp_str */
14112 PyObject_GenericGetAttr, /* tp_getattro */
14113 0, /* tp_setattro */
14114 0, /* tp_as_buffer */
14115 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014116 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014117 unicode_doc, /* tp_doc */
14118 0, /* tp_traverse */
14119 0, /* tp_clear */
14120 PyUnicode_RichCompare, /* tp_richcompare */
14121 0, /* tp_weaklistoffset */
14122 unicode_iter, /* tp_iter */
14123 0, /* tp_iternext */
14124 unicode_methods, /* tp_methods */
14125 0, /* tp_members */
14126 0, /* tp_getset */
14127 &PyBaseObject_Type, /* tp_base */
14128 0, /* tp_dict */
14129 0, /* tp_descr_get */
14130 0, /* tp_descr_set */
14131 0, /* tp_dictoffset */
14132 0, /* tp_init */
14133 0, /* tp_alloc */
14134 unicode_new, /* tp_new */
14135 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014136};
14137
14138/* Initialize the Unicode implementation */
14139
Victor Stinner3a50e702011-10-18 21:21:00 +020014140int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014141{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014142 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014143 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014144 0x000A, /* LINE FEED */
14145 0x000D, /* CARRIAGE RETURN */
14146 0x001C, /* FILE SEPARATOR */
14147 0x001D, /* GROUP SEPARATOR */
14148 0x001E, /* RECORD SEPARATOR */
14149 0x0085, /* NEXT LINE */
14150 0x2028, /* LINE SEPARATOR */
14151 0x2029, /* PARAGRAPH SEPARATOR */
14152 };
14153
Fred Drakee4315f52000-05-09 19:53:39 +000014154 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014155 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014156 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014157 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014158 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014159
Guido van Rossumcacfc072002-05-24 19:01:59 +000014160 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014161 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014162
14163 /* initialize the linebreak bloom filter */
14164 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014165 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014166 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014167
14168 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014169
Benjamin Petersonc4311282012-10-30 23:21:10 -040014170 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14171 Py_FatalError("Can't initialize field name iterator type");
14172
14173 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14174 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014175
Victor Stinner3a50e702011-10-18 21:21:00 +020014176#ifdef HAVE_MBCS
14177 winver.dwOSVersionInfoSize = sizeof(winver);
14178 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14179 PyErr_SetFromWindowsErr(0);
14180 return -1;
14181 }
14182#endif
14183 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014184}
14185
14186/* Finalize the Unicode implementation */
14187
Christian Heimesa156e092008-02-16 07:38:31 +000014188int
14189PyUnicode_ClearFreeList(void)
14190{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014191 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014192}
14193
Guido van Rossumd57fd912000-03-10 22:53:23 +000014194void
Thomas Wouters78890102000-07-22 19:25:51 +000014195_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014196{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014197 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014198
Serhiy Storchaka05997252013-01-26 12:14:02 +020014199 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014200
Serhiy Storchaka05997252013-01-26 12:14:02 +020014201 for (i = 0; i < 256; i++)
14202 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014203 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014204 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014205}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014206
Walter Dörwald16807132007-05-25 13:52:07 +000014207void
14208PyUnicode_InternInPlace(PyObject **p)
14209{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014210 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014211 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014212#ifdef Py_DEBUG
14213 assert(s != NULL);
14214 assert(_PyUnicode_CHECK(s));
14215#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014216 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014217 return;
14218#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014219 /* If it's a subclass, we don't really know what putting
14220 it in the interned dict might do. */
14221 if (!PyUnicode_CheckExact(s))
14222 return;
14223 if (PyUnicode_CHECK_INTERNED(s))
14224 return;
14225 if (interned == NULL) {
14226 interned = PyDict_New();
14227 if (interned == NULL) {
14228 PyErr_Clear(); /* Don't leave an exception */
14229 return;
14230 }
14231 }
14232 /* It might be that the GetItem call fails even
14233 though the key is present in the dictionary,
14234 namely when this happens during a stack overflow. */
14235 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014236 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014237 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014238
Benjamin Peterson29060642009-01-31 22:14:21 +000014239 if (t) {
14240 Py_INCREF(t);
14241 Py_DECREF(*p);
14242 *p = t;
14243 return;
14244 }
Walter Dörwald16807132007-05-25 13:52:07 +000014245
Benjamin Peterson14339b62009-01-31 16:36:08 +000014246 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014247 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014248 PyErr_Clear();
14249 PyThreadState_GET()->recursion_critical = 0;
14250 return;
14251 }
14252 PyThreadState_GET()->recursion_critical = 0;
14253 /* The two references in interned are not counted by refcnt.
14254 The deallocator will take care of this */
14255 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014256 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014257}
14258
14259void
14260PyUnicode_InternImmortal(PyObject **p)
14261{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014262 PyUnicode_InternInPlace(p);
14263 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014264 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 Py_INCREF(*p);
14266 }
Walter Dörwald16807132007-05-25 13:52:07 +000014267}
14268
14269PyObject *
14270PyUnicode_InternFromString(const char *cp)
14271{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014272 PyObject *s = PyUnicode_FromString(cp);
14273 if (s == NULL)
14274 return NULL;
14275 PyUnicode_InternInPlace(&s);
14276 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014277}
14278
Alexander Belopolsky40018472011-02-26 01:02:56 +000014279void
14280_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014281{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014283 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 Py_ssize_t i, n;
14285 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014286
Benjamin Peterson14339b62009-01-31 16:36:08 +000014287 if (interned == NULL || !PyDict_Check(interned))
14288 return;
14289 keys = PyDict_Keys(interned);
14290 if (keys == NULL || !PyList_Check(keys)) {
14291 PyErr_Clear();
14292 return;
14293 }
Walter Dörwald16807132007-05-25 13:52:07 +000014294
Benjamin Peterson14339b62009-01-31 16:36:08 +000014295 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14296 detector, interned unicode strings are not forcibly deallocated;
14297 rather, we give them their stolen references back, and then clear
14298 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014299
Benjamin Peterson14339b62009-01-31 16:36:08 +000014300 n = PyList_GET_SIZE(keys);
14301 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014302 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014303 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014304 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014305 if (PyUnicode_READY(s) == -1) {
14306 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014307 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014309 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014310 case SSTATE_NOT_INTERNED:
14311 /* XXX Shouldn't happen */
14312 break;
14313 case SSTATE_INTERNED_IMMORTAL:
14314 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014315 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014316 break;
14317 case SSTATE_INTERNED_MORTAL:
14318 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014319 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 break;
14321 default:
14322 Py_FatalError("Inconsistent interned string state.");
14323 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014324 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014325 }
14326 fprintf(stderr, "total size of all interned strings: "
14327 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14328 "mortal/immortal\n", mortal_size, immortal_size);
14329 Py_DECREF(keys);
14330 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020014331 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000014332}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014333
14334
14335/********************* Unicode Iterator **************************/
14336
14337typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014338 PyObject_HEAD
14339 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014340 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014341} unicodeiterobject;
14342
14343static void
14344unicodeiter_dealloc(unicodeiterobject *it)
14345{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014346 _PyObject_GC_UNTRACK(it);
14347 Py_XDECREF(it->it_seq);
14348 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014349}
14350
14351static int
14352unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14353{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014354 Py_VISIT(it->it_seq);
14355 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014356}
14357
14358static PyObject *
14359unicodeiter_next(unicodeiterobject *it)
14360{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014361 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014362
Benjamin Peterson14339b62009-01-31 16:36:08 +000014363 assert(it != NULL);
14364 seq = it->it_seq;
14365 if (seq == NULL)
14366 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014367 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014368
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014369 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14370 int kind = PyUnicode_KIND(seq);
14371 void *data = PyUnicode_DATA(seq);
14372 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14373 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014374 if (item != NULL)
14375 ++it->it_index;
14376 return item;
14377 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014378
Benjamin Peterson14339b62009-01-31 16:36:08 +000014379 Py_DECREF(seq);
14380 it->it_seq = NULL;
14381 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014382}
14383
14384static PyObject *
14385unicodeiter_len(unicodeiterobject *it)
14386{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014387 Py_ssize_t len = 0;
14388 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014389 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014391}
14392
14393PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14394
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014395static PyObject *
14396unicodeiter_reduce(unicodeiterobject *it)
14397{
14398 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014399 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014400 it->it_seq, it->it_index);
14401 } else {
14402 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14403 if (u == NULL)
14404 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014405 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014406 }
14407}
14408
14409PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14410
14411static PyObject *
14412unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14413{
14414 Py_ssize_t index = PyLong_AsSsize_t(state);
14415 if (index == -1 && PyErr_Occurred())
14416 return NULL;
14417 if (index < 0)
14418 index = 0;
14419 it->it_index = index;
14420 Py_RETURN_NONE;
14421}
14422
14423PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14424
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014425static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014426 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014427 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014428 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14429 reduce_doc},
14430 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14431 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014432 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014433};
14434
14435PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014436 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14437 "str_iterator", /* tp_name */
14438 sizeof(unicodeiterobject), /* tp_basicsize */
14439 0, /* tp_itemsize */
14440 /* methods */
14441 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14442 0, /* tp_print */
14443 0, /* tp_getattr */
14444 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014445 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014446 0, /* tp_repr */
14447 0, /* tp_as_number */
14448 0, /* tp_as_sequence */
14449 0, /* tp_as_mapping */
14450 0, /* tp_hash */
14451 0, /* tp_call */
14452 0, /* tp_str */
14453 PyObject_GenericGetAttr, /* tp_getattro */
14454 0, /* tp_setattro */
14455 0, /* tp_as_buffer */
14456 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14457 0, /* tp_doc */
14458 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14459 0, /* tp_clear */
14460 0, /* tp_richcompare */
14461 0, /* tp_weaklistoffset */
14462 PyObject_SelfIter, /* tp_iter */
14463 (iternextfunc)unicodeiter_next, /* tp_iternext */
14464 unicodeiter_methods, /* tp_methods */
14465 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014466};
14467
14468static PyObject *
14469unicode_iter(PyObject *seq)
14470{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014471 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014472
Benjamin Peterson14339b62009-01-31 16:36:08 +000014473 if (!PyUnicode_Check(seq)) {
14474 PyErr_BadInternalCall();
14475 return NULL;
14476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014477 if (PyUnicode_READY(seq) == -1)
14478 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014479 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14480 if (it == NULL)
14481 return NULL;
14482 it->it_index = 0;
14483 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014484 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014485 _PyObject_GC_TRACK(it);
14486 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014487}
14488
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014489
14490size_t
14491Py_UNICODE_strlen(const Py_UNICODE *u)
14492{
14493 int res = 0;
14494 while(*u++)
14495 res++;
14496 return res;
14497}
14498
14499Py_UNICODE*
14500Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14501{
14502 Py_UNICODE *u = s1;
14503 while ((*u++ = *s2++));
14504 return s1;
14505}
14506
14507Py_UNICODE*
14508Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14509{
14510 Py_UNICODE *u = s1;
14511 while ((*u++ = *s2++))
14512 if (n-- == 0)
14513 break;
14514 return s1;
14515}
14516
14517Py_UNICODE*
14518Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14519{
14520 Py_UNICODE *u1 = s1;
14521 u1 += Py_UNICODE_strlen(u1);
14522 Py_UNICODE_strcpy(u1, s2);
14523 return s1;
14524}
14525
14526int
14527Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14528{
14529 while (*s1 && *s2 && *s1 == *s2)
14530 s1++, s2++;
14531 if (*s1 && *s2)
14532 return (*s1 < *s2) ? -1 : +1;
14533 if (*s1)
14534 return 1;
14535 if (*s2)
14536 return -1;
14537 return 0;
14538}
14539
14540int
14541Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14542{
14543 register Py_UNICODE u1, u2;
14544 for (; n != 0; n--) {
14545 u1 = *s1;
14546 u2 = *s2;
14547 if (u1 != u2)
14548 return (u1 < u2) ? -1 : +1;
14549 if (u1 == '\0')
14550 return 0;
14551 s1++;
14552 s2++;
14553 }
14554 return 0;
14555}
14556
14557Py_UNICODE*
14558Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14559{
14560 const Py_UNICODE *p;
14561 for (p = s; *p; p++)
14562 if (*p == c)
14563 return (Py_UNICODE*)p;
14564 return NULL;
14565}
14566
14567Py_UNICODE*
14568Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14569{
14570 const Py_UNICODE *p;
14571 p = s + Py_UNICODE_strlen(s);
14572 while (p != s) {
14573 p--;
14574 if (*p == c)
14575 return (Py_UNICODE*)p;
14576 }
14577 return NULL;
14578}
Victor Stinner331ea922010-08-10 16:37:20 +000014579
Victor Stinner71133ff2010-09-01 23:43:53 +000014580Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014581PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014582{
Victor Stinner577db2c2011-10-11 22:12:48 +020014583 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014584 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014586 if (!PyUnicode_Check(unicode)) {
14587 PyErr_BadArgument();
14588 return NULL;
14589 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014590 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014591 if (u == NULL)
14592 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014593 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014594 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014595 PyErr_NoMemory();
14596 return NULL;
14597 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014598 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014599 size *= sizeof(Py_UNICODE);
14600 copy = PyMem_Malloc(size);
14601 if (copy == NULL) {
14602 PyErr_NoMemory();
14603 return NULL;
14604 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014605 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014606 return copy;
14607}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014608
Georg Brandl66c221e2010-10-14 07:04:07 +000014609/* A _string module, to export formatter_parser and formatter_field_name_split
14610 to the string.Formatter class implemented in Python. */
14611
14612static PyMethodDef _string_methods[] = {
14613 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14614 METH_O, PyDoc_STR("split the argument as a field name")},
14615 {"formatter_parser", (PyCFunction) formatter_parser,
14616 METH_O, PyDoc_STR("parse the argument as a format string")},
14617 {NULL, NULL}
14618};
14619
14620static struct PyModuleDef _string_module = {
14621 PyModuleDef_HEAD_INIT,
14622 "_string",
14623 PyDoc_STR("string helper module"),
14624 0,
14625 _string_methods,
14626 NULL,
14627 NULL,
14628 NULL,
14629 NULL
14630};
14631
14632PyMODINIT_FUNC
14633PyInit__string(void)
14634{
14635 return PyModule_Create(&_string_module);
14636}
14637
14638
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014639#ifdef __cplusplus
14640}
14641#endif