blob: e90ee3f1a33f704b251140d8b82e660badd70200 [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
60 The globals are initialized by the _PyUnicode_Init() API and should
61 not be used before calling that API.
62
63*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000064
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065
66#ifdef __cplusplus
67extern "C" {
68#endif
69
Victor Stinner8faf8212011-12-08 22:14:11 +010070/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
71#define MAX_UNICODE 0x10ffff
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinnere6abb482012-05-02 01:15:40 +0200114/* Optimized version of Py_MAX() to compute the maximum character:
115 use it when your are computing the second argument of PyUnicode_New() */
116#define MAX_MAXCHAR(maxchar1, maxchar2) \
117 ((maxchar1) | (maxchar2))
118
Victor Stinner910337b2011-10-03 03:20:16 +0200119#undef PyUnicode_READY
120#define PyUnicode_READY(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200123 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100124 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200162 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
182static PyObject *interned;
183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200185static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000186
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200187/* List of static strings. */
188static _Py_Identifier *static_strings;
189
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190/* Single character Unicode strings in the Latin-1 range are being
191 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200192static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193
Christian Heimes190d79e2008-01-30 11:58:22 +0000194/* Fast detection of the most frequent whitespace characters */
195const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000196 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000197/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000198/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000199/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000200/* case 0x000C: * FORM FEED */
201/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 0, 1, 1, 1, 1, 1, 0, 0,
203 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x001C: * FILE SEPARATOR */
205/* case 0x001D: * GROUP SEPARATOR */
206/* case 0x001E: * RECORD SEPARATOR */
207/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000208 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000209/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 1, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000214
Benjamin Peterson14339b62009-01-31 16:36:08 +0000215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000223};
224
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200225/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200226static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200227static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100228static int unicode_modifiable(PyObject *unicode);
229
Victor Stinnerfe226c02011-10-03 03:52:20 +0200230
Alexander Belopolsky40018472011-02-26 01:02:56 +0000231static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200232_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
233static PyObject *
234_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
235static PyObject *
236_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
237
238static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000240 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100241 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000242 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
243
Alexander Belopolsky40018472011-02-26 01:02:56 +0000244static void
245raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300246 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100247 PyObject *unicode,
248 Py_ssize_t startpos, Py_ssize_t endpos,
249 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000250
Christian Heimes190d79e2008-01-30 11:58:22 +0000251/* Same for linebreaks */
252static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000254/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000255/* 0x000B, * LINE TABULATION */
256/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000257/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000258 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000259 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000260/* 0x001C, * FILE SEPARATOR */
261/* 0x001D, * GROUP SEPARATOR */
262/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 1, 1, 1, 0,
264 0, 0, 0, 0, 0, 0, 0, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000268
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000277};
278
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300279/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
280 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000281Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000282PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000283{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000284#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000286#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 /* This is actually an illegal character, so it should
288 not be passed to unichr. */
289 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000290#endif
291}
292
Victor Stinner910337b2011-10-03 03:20:16 +0200293#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200294int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100295_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200296{
297 PyASCIIObject *ascii;
298 unsigned int kind;
299
300 assert(PyUnicode_Check(op));
301
302 ascii = (PyASCIIObject *)op;
303 kind = ascii->state.kind;
304
Victor Stinnera3b334d2011-10-03 13:53:37 +0200305 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200306 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(ascii->state.ready == 1);
308 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200309 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200310 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200311 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200312
Victor Stinnera41463c2011-10-04 01:05:08 +0200313 if (ascii->state.compact == 1) {
314 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200315 assert(kind == PyUnicode_1BYTE_KIND
316 || kind == PyUnicode_2BYTE_KIND
317 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200318 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200319 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200320 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100321 }
322 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
324
325 data = unicode->data.any;
326 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100327 assert(ascii->length == 0);
328 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 assert(ascii->state.compact == 0);
330 assert(ascii->state.ascii == 0);
331 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100332 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 assert(ascii->wstr != NULL);
334 assert(data == NULL);
335 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 }
337 else {
338 assert(kind == PyUnicode_1BYTE_KIND
339 || kind == PyUnicode_2BYTE_KIND
340 || kind == PyUnicode_4BYTE_KIND);
341 assert(ascii->state.compact == 0);
342 assert(ascii->state.ready == 1);
343 assert(data != NULL);
344 if (ascii->state.ascii) {
345 assert (compact->utf8 == data);
346 assert (compact->utf8_length == ascii->length);
347 }
348 else
349 assert (compact->utf8 != data);
350 }
351 }
352 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200353 if (
354#if SIZEOF_WCHAR_T == 2
355 kind == PyUnicode_2BYTE_KIND
356#else
357 kind == PyUnicode_4BYTE_KIND
358#endif
359 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200360 {
361 assert(ascii->wstr == data);
362 assert(compact->wstr_length == ascii->length);
363 } else
364 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200365 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200366
367 if (compact->utf8 == NULL)
368 assert(compact->utf8_length == 0);
369 if (ascii->wstr == NULL)
370 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200372 /* check that the best kind is used */
373 if (check_content && kind != PyUnicode_WCHAR_KIND)
374 {
375 Py_ssize_t i;
376 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200377 void *data;
378 Py_UCS4 ch;
379
380 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200381 for (i=0; i < ascii->length; i++)
382 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200383 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200384 if (ch > maxchar)
385 maxchar = ch;
386 }
387 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100388 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200389 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100390 assert(maxchar <= 255);
391 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200392 else
393 assert(maxchar < 128);
394 }
Victor Stinner77faf692011-11-20 18:56:05 +0100395 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200396 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100397 assert(maxchar <= 0xFFFF);
398 }
399 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100401 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100402 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200403 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400405 return 1;
406}
Victor Stinner910337b2011-10-03 03:20:16 +0200407#endif
408
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100409static PyObject*
410unicode_result_wchar(PyObject *unicode)
411{
412#ifndef Py_DEBUG
413 Py_ssize_t len;
414
415 assert(Py_REFCNT(unicode) == 1);
416
417 len = _PyUnicode_WSTR_LENGTH(unicode);
418 if (len == 0) {
419 Py_INCREF(unicode_empty);
420 Py_DECREF(unicode);
421 return unicode_empty;
422 }
423
424 if (len == 1) {
425 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
426 if (ch < 256) {
427 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
428 Py_DECREF(unicode);
429 return latin1_char;
430 }
431 }
432
433 if (_PyUnicode_Ready(unicode) < 0) {
434 Py_XDECREF(unicode);
435 return NULL;
436 }
437#else
438 /* don't make the result ready in debug mode to ensure that the caller
439 makes the string ready before using it */
440 assert(_PyUnicode_CheckConsistency(unicode, 1));
441#endif
442 return unicode;
443}
444
445static PyObject*
446unicode_result_ready(PyObject *unicode)
447{
448 Py_ssize_t length;
449
450 length = PyUnicode_GET_LENGTH(unicode);
451 if (length == 0) {
452 if (unicode != unicode_empty) {
453 Py_INCREF(unicode_empty);
454 Py_DECREF(unicode);
455 }
456 return unicode_empty;
457 }
458
459 if (length == 1) {
460 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
461 if (ch < 256) {
462 PyObject *latin1_char = unicode_latin1[ch];
463 if (latin1_char != NULL) {
464 if (unicode != latin1_char) {
465 Py_INCREF(latin1_char);
466 Py_DECREF(unicode);
467 }
468 return latin1_char;
469 }
470 else {
471 assert(_PyUnicode_CheckConsistency(unicode, 1));
472 Py_INCREF(unicode);
473 unicode_latin1[ch] = unicode;
474 return unicode;
475 }
476 }
477 }
478
479 assert(_PyUnicode_CheckConsistency(unicode, 1));
480 return unicode;
481}
482
483static PyObject*
484unicode_result(PyObject *unicode)
485{
486 assert(_PyUnicode_CHECK(unicode));
487 if (PyUnicode_IS_READY(unicode))
488 return unicode_result_ready(unicode);
489 else
490 return unicode_result_wchar(unicode);
491}
492
Victor Stinnerc4b49542011-12-11 22:44:26 +0100493static PyObject*
494unicode_result_unchanged(PyObject *unicode)
495{
496 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500497 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100498 return NULL;
499 Py_INCREF(unicode);
500 return unicode;
501 }
502 else
503 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100504 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100505}
506
Victor Stinner3a50e702011-10-18 21:21:00 +0200507#ifdef HAVE_MBCS
508static OSVERSIONINFOEX winver;
509#endif
510
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511/* --- Bloom Filters ----------------------------------------------------- */
512
513/* stuff to implement simple "bloom filters" for Unicode characters.
514 to keep things simple, we use a single bitmask, using the least 5
515 bits from each unicode characters as the bit index. */
516
517/* the linebreak mask is set up by Unicode_Init below */
518
Antoine Pitrouf068f942010-01-13 14:19:12 +0000519#if LONG_BIT >= 128
520#define BLOOM_WIDTH 128
521#elif LONG_BIT >= 64
522#define BLOOM_WIDTH 64
523#elif LONG_BIT >= 32
524#define BLOOM_WIDTH 32
525#else
526#error "LONG_BIT is smaller than 32"
527#endif
528
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529#define BLOOM_MASK unsigned long
530
531static BLOOM_MASK bloom_linebreak;
532
Antoine Pitrouf068f942010-01-13 14:19:12 +0000533#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
534#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
Benjamin Peterson29060642009-01-31 22:14:21 +0000536#define BLOOM_LINEBREAK(ch) \
537 ((ch) < 128U ? ascii_linebreak[(ch)] : \
538 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539
Alexander Belopolsky40018472011-02-26 01:02:56 +0000540Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200541make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542{
543 /* calculate simple bloom-style bitmask for a given unicode string */
544
Antoine Pitrouf068f942010-01-13 14:19:12 +0000545 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 Py_ssize_t i;
547
548 mask = 0;
549 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552 return mask;
553}
554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555#define BLOOM_MEMBER(mask, chr, str) \
556 (BLOOM(mask, chr) \
557 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200559/* Compilation of templated routines */
560
561#include "stringlib/asciilib.h"
562#include "stringlib/fastsearch.h"
563#include "stringlib/partition.h"
564#include "stringlib/split.h"
565#include "stringlib/count.h"
566#include "stringlib/find.h"
567#include "stringlib/find_max_char.h"
568#include "stringlib/localeutil.h"
569#include "stringlib/undef.h"
570
571#include "stringlib/ucs1lib.h"
572#include "stringlib/fastsearch.h"
573#include "stringlib/partition.h"
574#include "stringlib/split.h"
575#include "stringlib/count.h"
576#include "stringlib/find.h"
577#include "stringlib/find_max_char.h"
578#include "stringlib/localeutil.h"
579#include "stringlib/undef.h"
580
581#include "stringlib/ucs2lib.h"
582#include "stringlib/fastsearch.h"
583#include "stringlib/partition.h"
584#include "stringlib/split.h"
585#include "stringlib/count.h"
586#include "stringlib/find.h"
587#include "stringlib/find_max_char.h"
588#include "stringlib/localeutil.h"
589#include "stringlib/undef.h"
590
591#include "stringlib/ucs4lib.h"
592#include "stringlib/fastsearch.h"
593#include "stringlib/partition.h"
594#include "stringlib/split.h"
595#include "stringlib/count.h"
596#include "stringlib/find.h"
597#include "stringlib/find_max_char.h"
598#include "stringlib/localeutil.h"
599#include "stringlib/undef.h"
600
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200601#include "stringlib/unicodedefs.h"
602#include "stringlib/fastsearch.h"
603#include "stringlib/count.h"
604#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100605#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200606
Guido van Rossumd57fd912000-03-10 22:53:23 +0000607/* --- Unicode Object ----------------------------------------------------- */
608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200610fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200612Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
613 Py_ssize_t size, Py_UCS4 ch,
614 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200615{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200616 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
617
618 switch (kind) {
619 case PyUnicode_1BYTE_KIND:
620 {
621 Py_UCS1 ch1 = (Py_UCS1) ch;
622 if (ch1 == ch)
623 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
624 else
625 return -1;
626 }
627 case PyUnicode_2BYTE_KIND:
628 {
629 Py_UCS2 ch2 = (Py_UCS2) ch;
630 if (ch2 == ch)
631 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
632 else
633 return -1;
634 }
635 case PyUnicode_4BYTE_KIND:
636 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
637 default:
638 assert(0);
639 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641}
642
Victor Stinnerfe226c02011-10-03 03:52:20 +0200643static PyObject*
644resize_compact(PyObject *unicode, Py_ssize_t length)
645{
646 Py_ssize_t char_size;
647 Py_ssize_t struct_size;
648 Py_ssize_t new_size;
649 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100650 PyObject *new_unicode;
Victor Stinner79891572012-05-03 13:43:07 +0200651 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200652 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100653 assert(PyUnicode_IS_COMPACT(unicode));
654
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200655 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100656 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657 struct_size = sizeof(PyASCIIObject);
658 else
659 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200660 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
663 PyErr_NoMemory();
664 return NULL;
665 }
666 new_size = (struct_size + (length + 1) * char_size);
667
Victor Stinner84def372011-12-11 20:04:56 +0100668 _Py_DEC_REFTOTAL;
669 _Py_ForgetReference(unicode);
670
671 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
672 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100673 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 PyErr_NoMemory();
675 return NULL;
676 }
Victor Stinner84def372011-12-11 20:04:56 +0100677 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100679
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200681 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100683 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200684 _PyUnicode_WSTR_LENGTH(unicode) = length;
685 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200686 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
687 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200688 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200689 return unicode;
690}
691
Alexander Belopolsky40018472011-02-26 01:02:56 +0000692static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200693resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694{
Victor Stinner95663112011-10-04 01:03:50 +0200695 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100696 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200697 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000699
Victor Stinnerfe226c02011-10-03 03:52:20 +0200700 if (PyUnicode_IS_READY(unicode)) {
701 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200702 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200703 void *data;
704
705 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200706 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200707 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
708 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200709
710 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
711 PyErr_NoMemory();
712 return -1;
713 }
714 new_size = (length + 1) * char_size;
715
Victor Stinner7a9105a2011-12-12 00:13:42 +0100716 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
717 {
718 PyObject_DEL(_PyUnicode_UTF8(unicode));
719 _PyUnicode_UTF8(unicode) = NULL;
720 _PyUnicode_UTF8_LENGTH(unicode) = 0;
721 }
722
Victor Stinnerfe226c02011-10-03 03:52:20 +0200723 data = (PyObject *)PyObject_REALLOC(data, new_size);
724 if (data == NULL) {
725 PyErr_NoMemory();
726 return -1;
727 }
728 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200729 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200730 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200731 _PyUnicode_WSTR_LENGTH(unicode) = length;
732 }
733 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200734 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200735 _PyUnicode_UTF8_LENGTH(unicode) = length;
736 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _PyUnicode_LENGTH(unicode) = length;
738 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200739 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200740 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200743 }
Victor Stinner95663112011-10-04 01:03:50 +0200744 assert(_PyUnicode_WSTR(unicode) != NULL);
745
746 /* check for integer overflow */
747 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
748 PyErr_NoMemory();
749 return -1;
750 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100751 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200752 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100753 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200754 if (!wstr) {
755 PyErr_NoMemory();
756 return -1;
757 }
758 _PyUnicode_WSTR(unicode) = wstr;
759 _PyUnicode_WSTR(unicode)[length] = 0;
760 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200761 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000762 return 0;
763}
764
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765static PyObject*
766resize_copy(PyObject *unicode, Py_ssize_t length)
767{
768 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100769 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200770 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100771
Benjamin Petersonbac79492012-01-14 13:34:47 -0500772 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100773 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774
775 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
776 if (copy == NULL)
777 return NULL;
778
779 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200780 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200781 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200782 }
783 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200784 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200786 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200787 if (w == NULL)
788 return NULL;
789 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
790 copy_length = Py_MIN(copy_length, length);
791 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
792 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200793 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 }
795}
796
Guido van Rossumd57fd912000-03-10 22:53:23 +0000797/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000798 Ux0000 terminated; some code (e.g. new_identifier)
799 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000800
801 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000802 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000803
804*/
805
Alexander Belopolsky40018472011-02-26 01:02:56 +0000806static PyUnicodeObject *
807_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000808{
809 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200810 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000811
Thomas Wouters477c8d52006-05-27 19:21:47 +0000812 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000813 if (length == 0 && unicode_empty != NULL) {
814 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200815 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000816 }
817
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000818 /* Ensure we won't overflow the size. */
819 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
820 return (PyUnicodeObject *)PyErr_NoMemory();
821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200822 if (length < 0) {
823 PyErr_SetString(PyExc_SystemError,
824 "Negative size passed to _PyUnicode_New");
825 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000826 }
827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
829 if (unicode == NULL)
830 return NULL;
831 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
832 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
833 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100834 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000835 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100836 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838
Jeremy Hyltond8082792003-09-16 19:41:39 +0000839 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000840 * the caller fails before initializing str -- unicode_resize()
841 * reads str[0], and the Keep-Alive optimization can keep memory
842 * allocated for str alive across a call to unicode_dealloc(unicode).
843 * We don't want unicode_resize to read uninitialized memory in
844 * that case.
845 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200846 _PyUnicode_WSTR(unicode)[0] = 0;
847 _PyUnicode_WSTR(unicode)[length] = 0;
848 _PyUnicode_WSTR_LENGTH(unicode) = length;
849 _PyUnicode_HASH(unicode) = -1;
850 _PyUnicode_STATE(unicode).interned = 0;
851 _PyUnicode_STATE(unicode).kind = 0;
852 _PyUnicode_STATE(unicode).compact = 0;
853 _PyUnicode_STATE(unicode).ready = 0;
854 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200855 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200856 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200857 _PyUnicode_UTF8(unicode) = NULL;
858 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100859 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000860 return unicode;
861}
862
Victor Stinnerf42dc442011-10-02 23:33:16 +0200863static const char*
864unicode_kind_name(PyObject *unicode)
865{
Victor Stinner42dfd712011-10-03 14:41:45 +0200866 /* don't check consistency: unicode_kind_name() is called from
867 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200868 if (!PyUnicode_IS_COMPACT(unicode))
869 {
870 if (!PyUnicode_IS_READY(unicode))
871 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600872 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200873 {
874 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200875 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 return "legacy ascii";
877 else
878 return "legacy latin1";
879 case PyUnicode_2BYTE_KIND:
880 return "legacy UCS2";
881 case PyUnicode_4BYTE_KIND:
882 return "legacy UCS4";
883 default:
884 return "<legacy invalid kind>";
885 }
886 }
887 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600888 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200889 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200890 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200891 return "ascii";
892 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200895 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200896 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200897 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200898 default:
899 return "<invalid compact kind>";
900 }
901}
902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200903#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200904/* Functions wrapping macros for use in debugger */
905char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200906 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200907}
908
909void *_PyUnicode_compact_data(void *unicode) {
910 return _PyUnicode_COMPACT_DATA(unicode);
911}
912void *_PyUnicode_data(void *unicode){
913 printf("obj %p\n", unicode);
914 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
915 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
916 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
917 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
918 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
919 return PyUnicode_DATA(unicode);
920}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200921
922void
923_PyUnicode_Dump(PyObject *op)
924{
925 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200926 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
927 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
928 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200929
Victor Stinnera849a4b2011-10-03 12:12:11 +0200930 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200931 {
932 if (ascii->state.ascii)
933 data = (ascii + 1);
934 else
935 data = (compact + 1);
936 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200937 else
938 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200939 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
940
Victor Stinnera849a4b2011-10-03 12:12:11 +0200941 if (ascii->wstr == data)
942 printf("shared ");
943 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200944
Victor Stinnera3b334d2011-10-03 13:53:37 +0200945 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 printf(" (%zu), ", compact->wstr_length);
947 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
948 printf("shared ");
949 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200950 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200952}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953#endif
954
955PyObject *
956PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
957{
958 PyObject *obj;
959 PyCompactUnicodeObject *unicode;
960 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200961 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200962 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200963 Py_ssize_t char_size;
964 Py_ssize_t struct_size;
965
966 /* Optimization for empty strings */
967 if (size == 0 && unicode_empty != NULL) {
968 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200969 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200970 }
971
Victor Stinner9e9d6892011-10-04 01:02:02 +0200972 is_ascii = 0;
973 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 struct_size = sizeof(PyCompactUnicodeObject);
975 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +0200976 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977 char_size = 1;
978 is_ascii = 1;
979 struct_size = sizeof(PyASCIIObject);
980 }
981 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +0200982 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 char_size = 1;
984 }
985 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +0200986 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987 char_size = 2;
988 if (sizeof(wchar_t) == 2)
989 is_sharing = 1;
990 }
991 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +0100992 if (maxchar > MAX_UNICODE) {
993 PyErr_SetString(PyExc_SystemError,
994 "invalid maximum character passed to PyUnicode_New");
995 return NULL;
996 }
Victor Stinner8f825062012-04-27 13:55:39 +0200997 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200998 char_size = 4;
999 if (sizeof(wchar_t) == 4)
1000 is_sharing = 1;
1001 }
1002
1003 /* Ensure we won't overflow the size. */
1004 if (size < 0) {
1005 PyErr_SetString(PyExc_SystemError,
1006 "Negative size passed to PyUnicode_New");
1007 return NULL;
1008 }
1009 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1010 return PyErr_NoMemory();
1011
1012 /* Duplicated allocation code from _PyObject_New() instead of a call to
1013 * PyObject_New() so we are able to allocate space for the object and
1014 * it's data buffer.
1015 */
1016 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1017 if (obj == NULL)
1018 return PyErr_NoMemory();
1019 obj = PyObject_INIT(obj, &PyUnicode_Type);
1020 if (obj == NULL)
1021 return NULL;
1022
1023 unicode = (PyCompactUnicodeObject *)obj;
1024 if (is_ascii)
1025 data = ((PyASCIIObject*)obj) + 1;
1026 else
1027 data = unicode + 1;
1028 _PyUnicode_LENGTH(unicode) = size;
1029 _PyUnicode_HASH(unicode) = -1;
1030 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001031 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001032 _PyUnicode_STATE(unicode).compact = 1;
1033 _PyUnicode_STATE(unicode).ready = 1;
1034 _PyUnicode_STATE(unicode).ascii = is_ascii;
1035 if (is_ascii) {
1036 ((char*)data)[size] = 0;
1037 _PyUnicode_WSTR(unicode) = NULL;
1038 }
Victor Stinner8f825062012-04-27 13:55:39 +02001039 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 ((char*)data)[size] = 0;
1041 _PyUnicode_WSTR(unicode) = NULL;
1042 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001044 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 else {
1047 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001048 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001049 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001051 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 ((Py_UCS4*)data)[size] = 0;
1053 if (is_sharing) {
1054 _PyUnicode_WSTR_LENGTH(unicode) = size;
1055 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1056 }
1057 else {
1058 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1059 _PyUnicode_WSTR(unicode) = NULL;
1060 }
1061 }
Victor Stinner8f825062012-04-27 13:55:39 +02001062#ifdef Py_DEBUG
1063 /* Fill the data with invalid characters to detect bugs earlier.
1064 _PyUnicode_CheckConsistency(str, 1) detects invalid characters,
1065 at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII
1066 and U+FFFFFFFF is an invalid character in Unicode 6.0. */
1067 memset(data, 0xff, size * kind);
1068#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001069 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 return obj;
1071}
1072
1073#if SIZEOF_WCHAR_T == 2
1074/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1075 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001076 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001077
1078 This function assumes that unicode can hold one more code point than wstr
1079 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001080static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001082 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083{
1084 const wchar_t *iter;
1085 Py_UCS4 *ucs4_out;
1086
Victor Stinner910337b2011-10-03 03:20:16 +02001087 assert(unicode != NULL);
1088 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001089 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1090 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1091
1092 for (iter = begin; iter < end; ) {
1093 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1094 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001095 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1096 && (iter+1) < end
1097 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 {
Victor Stinner551ac952011-11-29 22:58:13 +01001099 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 iter += 2;
1101 }
1102 else {
1103 *ucs4_out++ = *iter;
1104 iter++;
1105 }
1106 }
1107 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1108 _PyUnicode_GET_LENGTH(unicode)));
1109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110}
1111#endif
1112
Victor Stinnercd9950f2011-10-02 00:34:53 +02001113static int
Victor Stinner488fa492011-12-12 00:01:39 +01001114unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115{
Victor Stinner488fa492011-12-12 00:01:39 +01001116 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001117 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001118 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001119 return -1;
1120 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001121 return 0;
1122}
1123
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001124static int
1125_copy_characters(PyObject *to, Py_ssize_t to_start,
1126 PyObject *from, Py_ssize_t from_start,
1127 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 unsigned int from_kind, to_kind;
1130 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131
Victor Stinneree4544c2012-05-09 22:24:08 +02001132 assert(0 <= how_many);
1133 assert(0 <= from_start);
1134 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001137 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138
Victor Stinnerd3f08822012-05-29 12:57:52 +02001139 assert(PyUnicode_Check(to));
1140 assert(PyUnicode_IS_READY(to));
1141 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1142
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001143 if (how_many == 0)
1144 return 0;
1145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001149 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
Victor Stinnerf1852262012-06-16 16:38:26 +02001151#ifdef Py_DEBUG
1152 if (!check_maxchar
1153 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1154 {
1155 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1156 Py_UCS4 ch;
1157 Py_ssize_t i;
1158 for (i=0; i < how_many; i++) {
1159 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1160 assert(ch <= to_maxchar);
1161 }
1162 }
1163#endif
1164
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001165 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001166 if (check_maxchar
1167 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1168 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001169 /* Writing Latin-1 characters into an ASCII string requires to
1170 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001171 Py_UCS4 max_char;
1172 max_char = ucs1lib_find_max_char(from_data,
1173 (Py_UCS1*)from_data + how_many);
1174 if (max_char >= 128)
1175 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001176 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001177 Py_MEMCPY((char*)to_data + to_kind * to_start,
1178 (char*)from_data + from_kind * from_start,
1179 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001180 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001181 else if (from_kind == PyUnicode_1BYTE_KIND
1182 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001183 {
1184 _PyUnicode_CONVERT_BYTES(
1185 Py_UCS1, Py_UCS2,
1186 PyUnicode_1BYTE_DATA(from) + from_start,
1187 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1188 PyUnicode_2BYTE_DATA(to) + to_start
1189 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001190 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001191 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001192 && to_kind == PyUnicode_4BYTE_KIND)
1193 {
1194 _PyUnicode_CONVERT_BYTES(
1195 Py_UCS1, Py_UCS4,
1196 PyUnicode_1BYTE_DATA(from) + from_start,
1197 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1198 PyUnicode_4BYTE_DATA(to) + to_start
1199 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001200 }
1201 else if (from_kind == PyUnicode_2BYTE_KIND
1202 && to_kind == PyUnicode_4BYTE_KIND)
1203 {
1204 _PyUnicode_CONVERT_BYTES(
1205 Py_UCS2, Py_UCS4,
1206 PyUnicode_2BYTE_DATA(from) + from_start,
1207 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1208 PyUnicode_4BYTE_DATA(to) + to_start
1209 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001210 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001211 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001212 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1213
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001214 if (!check_maxchar) {
1215 if (from_kind == PyUnicode_2BYTE_KIND
1216 && to_kind == PyUnicode_1BYTE_KIND)
1217 {
1218 _PyUnicode_CONVERT_BYTES(
1219 Py_UCS2, Py_UCS1,
1220 PyUnicode_2BYTE_DATA(from) + from_start,
1221 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1222 PyUnicode_1BYTE_DATA(to) + to_start
1223 );
1224 }
1225 else if (from_kind == PyUnicode_4BYTE_KIND
1226 && to_kind == PyUnicode_1BYTE_KIND)
1227 {
1228 _PyUnicode_CONVERT_BYTES(
1229 Py_UCS4, Py_UCS1,
1230 PyUnicode_4BYTE_DATA(from) + from_start,
1231 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1232 PyUnicode_1BYTE_DATA(to) + to_start
1233 );
1234 }
1235 else if (from_kind == PyUnicode_4BYTE_KIND
1236 && to_kind == PyUnicode_2BYTE_KIND)
1237 {
1238 _PyUnicode_CONVERT_BYTES(
1239 Py_UCS4, Py_UCS2,
1240 PyUnicode_4BYTE_DATA(from) + from_start,
1241 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1242 PyUnicode_2BYTE_DATA(to) + to_start
1243 );
1244 }
1245 else {
1246 assert(0);
1247 return -1;
1248 }
1249 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001250 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001251 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001252 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001253 Py_ssize_t i;
1254
Victor Stinnera0702ab2011-09-29 14:14:38 +02001255 for (i=0; i < how_many; i++) {
1256 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001257 if (ch > to_maxchar)
1258 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001259 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1260 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001261 }
1262 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001263 return 0;
1264}
1265
Victor Stinnerd3f08822012-05-29 12:57:52 +02001266void
1267_PyUnicode_FastCopyCharacters(
1268 PyObject *to, Py_ssize_t to_start,
1269 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001270{
1271 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1272}
1273
1274Py_ssize_t
1275PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1276 PyObject *from, Py_ssize_t from_start,
1277 Py_ssize_t how_many)
1278{
1279 int err;
1280
1281 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1282 PyErr_BadInternalCall();
1283 return -1;
1284 }
1285
Benjamin Petersonbac79492012-01-14 13:34:47 -05001286 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001287 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001288 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001289 return -1;
1290
Victor Stinnerd3f08822012-05-29 12:57:52 +02001291 if (from_start < 0) {
1292 PyErr_SetString(PyExc_IndexError, "string index out of range");
1293 return -1;
1294 }
1295 if (to_start < 0) {
1296 PyErr_SetString(PyExc_IndexError, "string index out of range");
1297 return -1;
1298 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001299 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1300 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1301 PyErr_Format(PyExc_SystemError,
1302 "Cannot write %zi characters at %zi "
1303 "in a string of %zi characters",
1304 how_many, to_start, PyUnicode_GET_LENGTH(to));
1305 return -1;
1306 }
1307
1308 if (how_many == 0)
1309 return 0;
1310
Victor Stinner488fa492011-12-12 00:01:39 +01001311 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001312 return -1;
1313
1314 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1315 if (err) {
1316 PyErr_Format(PyExc_SystemError,
1317 "Cannot copy %s characters "
1318 "into a string of %s characters",
1319 unicode_kind_name(from),
1320 unicode_kind_name(to));
1321 return -1;
1322 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001323 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324}
1325
Victor Stinner17222162011-09-28 22:15:37 +02001326/* Find the maximum code point and count the number of surrogate pairs so a
1327 correct string length can be computed before converting a string to UCS4.
1328 This function counts single surrogates as a character and not as a pair.
1329
1330 Return 0 on success, or -1 on error. */
1331static int
1332find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1333 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334{
1335 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001336 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
Victor Stinnerc53be962011-10-02 21:33:54 +02001338 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 *num_surrogates = 0;
1340 *maxchar = 0;
1341
1342 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001344 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1345 && (iter+1) < end
1346 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001347 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001348 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 iter += 2;
1351 }
1352 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001354 {
1355 ch = *iter;
1356 iter++;
1357 }
1358 if (ch > *maxchar) {
1359 *maxchar = ch;
1360 if (*maxchar > MAX_UNICODE) {
1361 PyErr_Format(PyExc_ValueError,
1362 "character U+%x is not in range [U+0000; U+10ffff]",
1363 ch);
1364 return -1;
1365 }
1366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 }
1368 return 0;
1369}
1370
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001371int
1372_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373{
1374 wchar_t *end;
1375 Py_UCS4 maxchar = 0;
1376 Py_ssize_t num_surrogates;
1377#if SIZEOF_WCHAR_T == 2
1378 Py_ssize_t length_wo_surrogates;
1379#endif
1380
Georg Brandl7597add2011-10-05 16:36:47 +02001381 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001382 strings were created using _PyObject_New() and where no canonical
1383 representation (the str field) has been set yet aka strings
1384 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001385 assert(_PyUnicode_CHECK(unicode));
1386 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001389 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001390 /* Actually, it should neither be interned nor be anything else: */
1391 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001394 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001395 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397
1398 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001399 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1400 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401 PyErr_NoMemory();
1402 return -1;
1403 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001404 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 _PyUnicode_WSTR(unicode), end,
1406 PyUnicode_1BYTE_DATA(unicode));
1407 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1408 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1409 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1410 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001411 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001412 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001413 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 }
1415 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001416 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 _PyUnicode_UTF8(unicode) = NULL;
1418 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 }
1420 PyObject_FREE(_PyUnicode_WSTR(unicode));
1421 _PyUnicode_WSTR(unicode) = NULL;
1422 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1423 }
1424 /* In this case we might have to convert down from 4-byte native
1425 wchar_t to 2-byte unicode. */
1426 else if (maxchar < 65536) {
1427 assert(num_surrogates == 0 &&
1428 "FindMaxCharAndNumSurrogatePairs() messed up");
1429
Victor Stinner506f5922011-09-28 22:34:18 +02001430#if SIZEOF_WCHAR_T == 2
1431 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001432 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001433 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1434 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1435 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001436 _PyUnicode_UTF8(unicode) = NULL;
1437 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001438#else
1439 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001440 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001441 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001442 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001443 PyErr_NoMemory();
1444 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445 }
Victor Stinner506f5922011-09-28 22:34:18 +02001446 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1447 _PyUnicode_WSTR(unicode), end,
1448 PyUnicode_2BYTE_DATA(unicode));
1449 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1450 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1451 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 _PyUnicode_UTF8(unicode) = NULL;
1453 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001454 PyObject_FREE(_PyUnicode_WSTR(unicode));
1455 _PyUnicode_WSTR(unicode) = NULL;
1456 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1457#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 }
1459 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1460 else {
1461#if SIZEOF_WCHAR_T == 2
1462 /* in case the native representation is 2-bytes, we need to allocate a
1463 new normalized 4-byte version. */
1464 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001465 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1466 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 PyErr_NoMemory();
1468 return -1;
1469 }
1470 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1471 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001472 _PyUnicode_UTF8(unicode) = NULL;
1473 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001474 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1475 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001476 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 PyObject_FREE(_PyUnicode_WSTR(unicode));
1478 _PyUnicode_WSTR(unicode) = NULL;
1479 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1480#else
1481 assert(num_surrogates == 0);
1482
Victor Stinnerc3c74152011-10-02 20:39:55 +02001483 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001484 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001485 _PyUnicode_UTF8(unicode) = NULL;
1486 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1488#endif
1489 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1490 }
1491 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001492 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001493 return 0;
1494}
1495
Alexander Belopolsky40018472011-02-26 01:02:56 +00001496static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001497unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001498{
Walter Dörwald16807132007-05-25 13:52:07 +00001499 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001500 case SSTATE_NOT_INTERNED:
1501 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001502
Benjamin Peterson29060642009-01-31 22:14:21 +00001503 case SSTATE_INTERNED_MORTAL:
1504 /* revive dead object temporarily for DelItem */
1505 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001506 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001507 Py_FatalError(
1508 "deletion of interned string failed");
1509 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001510
Benjamin Peterson29060642009-01-31 22:14:21 +00001511 case SSTATE_INTERNED_IMMORTAL:
1512 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001513
Benjamin Peterson29060642009-01-31 22:14:21 +00001514 default:
1515 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001516 }
1517
Victor Stinner03490912011-10-03 23:45:12 +02001518 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001519 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001520 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001521 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001522 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1523 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001524
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001525 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001526}
1527
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001528#ifdef Py_DEBUG
1529static int
1530unicode_is_singleton(PyObject *unicode)
1531{
1532 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1533 if (unicode == unicode_empty)
1534 return 1;
1535 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1536 {
1537 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1538 if (ch < 256 && unicode_latin1[ch] == unicode)
1539 return 1;
1540 }
1541 return 0;
1542}
1543#endif
1544
Alexander Belopolsky40018472011-02-26 01:02:56 +00001545static int
Victor Stinner488fa492011-12-12 00:01:39 +01001546unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001547{
Victor Stinner488fa492011-12-12 00:01:39 +01001548 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001549 if (Py_REFCNT(unicode) != 1)
1550 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001551 if (_PyUnicode_HASH(unicode) != -1)
1552 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001553 if (PyUnicode_CHECK_INTERNED(unicode))
1554 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001555 if (!PyUnicode_CheckExact(unicode))
1556 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001557#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001558 /* singleton refcount is greater than 1 */
1559 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001560#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001561 return 1;
1562}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001563
Victor Stinnerfe226c02011-10-03 03:52:20 +02001564static int
1565unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1566{
1567 PyObject *unicode;
1568 Py_ssize_t old_length;
1569
1570 assert(p_unicode != NULL);
1571 unicode = *p_unicode;
1572
1573 assert(unicode != NULL);
1574 assert(PyUnicode_Check(unicode));
1575 assert(0 <= length);
1576
Victor Stinner910337b2011-10-03 03:20:16 +02001577 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001578 old_length = PyUnicode_WSTR_LENGTH(unicode);
1579 else
1580 old_length = PyUnicode_GET_LENGTH(unicode);
1581 if (old_length == length)
1582 return 0;
1583
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001584 if (length == 0) {
1585 Py_DECREF(*p_unicode);
1586 *p_unicode = unicode_empty;
1587 Py_INCREF(*p_unicode);
1588 return 0;
1589 }
1590
Victor Stinner488fa492011-12-12 00:01:39 +01001591 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592 PyObject *copy = resize_copy(unicode, length);
1593 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001594 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 Py_DECREF(*p_unicode);
1596 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001597 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001598 }
1599
Victor Stinnerfe226c02011-10-03 03:52:20 +02001600 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001601 PyObject *new_unicode = resize_compact(unicode, length);
1602 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001603 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001604 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001605 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001606 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001608}
1609
Alexander Belopolsky40018472011-02-26 01:02:56 +00001610int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001611PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001612{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001613 PyObject *unicode;
1614 if (p_unicode == NULL) {
1615 PyErr_BadInternalCall();
1616 return -1;
1617 }
1618 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001619 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001620 {
1621 PyErr_BadInternalCall();
1622 return -1;
1623 }
1624 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001625}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001626
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001627static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001628unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1629 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001630{
1631 PyObject *result;
1632 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001633 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001634 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1635 return 0;
1636 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1637 maxchar);
1638 if (result == NULL)
1639 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001640 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001641 Py_DECREF(*p_unicode);
1642 *p_unicode = result;
1643 return 0;
1644}
1645
1646static int
1647unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1648 Py_UCS4 ch)
1649{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001650 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001651 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001652 return -1;
1653 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1654 PyUnicode_DATA(*p_unicode),
1655 (*pos)++, ch);
1656 return 0;
1657}
1658
Victor Stinnerc5166102012-02-22 13:55:02 +01001659/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001660
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001661 WARNING: The function doesn't copy the terminating null character and
1662 doesn't check the maximum character (may write a latin1 character in an
1663 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001664static void
1665unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1666 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001667{
1668 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1669 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001670 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001671
1672 switch (kind) {
1673 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001674 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001675 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001676 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001677 }
1678 case PyUnicode_2BYTE_KIND: {
1679 Py_UCS2 *start = (Py_UCS2 *)data + index;
1680 Py_UCS2 *ucs2 = start;
1681 assert(index <= PyUnicode_GET_LENGTH(unicode));
1682
Victor Stinner184252a2012-06-16 02:57:41 +02001683 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001684 *ucs2 = (Py_UCS2)*str;
1685
1686 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001687 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001688 }
1689 default: {
1690 Py_UCS4 *start = (Py_UCS4 *)data + index;
1691 Py_UCS4 *ucs4 = start;
1692 assert(kind == PyUnicode_4BYTE_KIND);
1693 assert(index <= PyUnicode_GET_LENGTH(unicode));
1694
Victor Stinner184252a2012-06-16 02:57:41 +02001695 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001696 *ucs4 = (Py_UCS4)*str;
1697
1698 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001699 }
1700 }
1701}
1702
1703
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704static PyObject*
1705get_latin1_char(unsigned char ch)
1706{
Victor Stinnera464fc12011-10-02 20:39:30 +02001707 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001708 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001709 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 if (!unicode)
1711 return NULL;
1712 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001713 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001714 unicode_latin1[ch] = unicode;
1715 }
1716 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001717 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718}
1719
Alexander Belopolsky40018472011-02-26 01:02:56 +00001720PyObject *
1721PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001722{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001723 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 Py_UCS4 maxchar = 0;
1725 Py_ssize_t num_surrogates;
1726
1727 if (u == NULL)
1728 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001729
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001730 /* If the Unicode data is known at construction time, we can apply
1731 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001733 /* Optimization for empty strings */
1734 if (size == 0 && unicode_empty != NULL) {
1735 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001736 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001737 }
Tim Petersced69f82003-09-16 20:30:58 +00001738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 /* Single character Unicode objects in the Latin-1 range are
1740 shared when using this constructor */
1741 if (size == 1 && *u < 256)
1742 return get_latin1_char((unsigned char)*u);
1743
1744 /* If not empty and not single character, copy the Unicode data
1745 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001746 if (find_maxchar_surrogates(u, u + size,
1747 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 return NULL;
1749
Victor Stinner8faf8212011-12-08 22:14:11 +01001750 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001751 if (!unicode)
1752 return NULL;
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754 switch (PyUnicode_KIND(unicode)) {
1755 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001756 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1758 break;
1759 case PyUnicode_2BYTE_KIND:
1760#if Py_UNICODE_SIZE == 2
1761 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1762#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001763 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1765#endif
1766 break;
1767 case PyUnicode_4BYTE_KIND:
1768#if SIZEOF_WCHAR_T == 2
1769 /* This is the only case which has to process surrogates, thus
1770 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001771 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772#else
1773 assert(num_surrogates == 0);
1774 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1775#endif
1776 break;
1777 default:
1778 assert(0 && "Impossible state");
1779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001780
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001781 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001782}
1783
Alexander Belopolsky40018472011-02-26 01:02:56 +00001784PyObject *
1785PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001786{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001787 if (size < 0) {
1788 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001789 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001790 return NULL;
1791 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001792 if (u != NULL)
1793 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1794 else
1795 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001800{
1801 size_t size = strlen(u);
1802 if (size > PY_SSIZE_T_MAX) {
1803 PyErr_SetString(PyExc_OverflowError, "input too long");
1804 return NULL;
1805 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001806 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001807}
1808
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001809PyObject *
1810_PyUnicode_FromId(_Py_Identifier *id)
1811{
1812 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001813 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1814 strlen(id->string),
1815 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001816 if (!id->object)
1817 return NULL;
1818 PyUnicode_InternInPlace(&id->object);
1819 assert(!id->next);
1820 id->next = static_strings;
1821 static_strings = id;
1822 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001823 return id->object;
1824}
1825
1826void
1827_PyUnicode_ClearStaticStrings()
1828{
1829 _Py_Identifier *i;
1830 for (i = static_strings; i; i = i->next) {
1831 Py_DECREF(i->object);
1832 i->object = NULL;
1833 i->next = NULL;
1834 }
1835}
1836
Benjamin Peterson0df54292012-03-26 14:50:32 -04001837/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001838
Victor Stinnerd3f08822012-05-29 12:57:52 +02001839PyObject*
1840_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001841{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001843 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001844 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001845#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001846 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001847#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001848 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001849 }
Victor Stinner785938e2011-12-11 20:09:03 +01001850 unicode = PyUnicode_New(size, 127);
1851 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001852 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001853 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1854 assert(_PyUnicode_CheckConsistency(unicode, 1));
1855 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001856}
1857
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001858static Py_UCS4
1859kind_maxchar_limit(unsigned int kind)
1860{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001861 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001862 case PyUnicode_1BYTE_KIND:
1863 return 0x80;
1864 case PyUnicode_2BYTE_KIND:
1865 return 0x100;
1866 case PyUnicode_4BYTE_KIND:
1867 return 0x10000;
1868 default:
1869 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001870 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001871 }
1872}
1873
Victor Stinnere6abb482012-05-02 01:15:40 +02001874Py_LOCAL_INLINE(Py_UCS4)
1875align_maxchar(Py_UCS4 maxchar)
1876{
1877 if (maxchar <= 127)
1878 return 127;
1879 else if (maxchar <= 255)
1880 return 255;
1881 else if (maxchar <= 65535)
1882 return 65535;
1883 else
1884 return MAX_UNICODE;
1885}
1886
Victor Stinner702c7342011-10-05 13:50:52 +02001887static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001888_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001890 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001891 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001892
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001893 if (size == 0) {
1894 Py_INCREF(unicode_empty);
1895 return unicode_empty;
1896 }
1897 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001898 if (size == 1)
1899 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001900
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001901 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001902 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 if (!res)
1904 return NULL;
1905 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001906 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001908}
1909
Victor Stinnere57b1c02011-09-28 22:20:48 +02001910static PyObject*
1911_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912{
1913 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001914 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001915
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916 if (size == 0) {
1917 Py_INCREF(unicode_empty);
1918 return unicode_empty;
1919 }
1920 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001921 if (size == 1) {
1922 Py_UCS4 ch = u[0];
1923 if (ch < 256)
1924 return get_latin1_char((unsigned char)ch);
1925
1926 res = PyUnicode_New(1, ch);
1927 if (res == NULL)
1928 return NULL;
1929 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1930 assert(_PyUnicode_CheckConsistency(res, 1));
1931 return res;
1932 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001933
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001934 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001935 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001936 if (!res)
1937 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001938 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001940 else {
1941 _PyUnicode_CONVERT_BYTES(
1942 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1943 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001944 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001945 return res;
1946}
1947
Victor Stinnere57b1c02011-09-28 22:20:48 +02001948static PyObject*
1949_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950{
1951 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001952 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001953
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001954 if (size == 0) {
1955 Py_INCREF(unicode_empty);
1956 return unicode_empty;
1957 }
1958 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001959 if (size == 1) {
1960 Py_UCS4 ch = u[0];
1961 if (ch < 256)
1962 return get_latin1_char((unsigned char)ch);
1963
1964 res = PyUnicode_New(1, ch);
1965 if (res == NULL)
1966 return NULL;
1967 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1968 assert(_PyUnicode_CheckConsistency(res, 1));
1969 return res;
1970 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001971
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001972 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001973 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 if (!res)
1975 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001976 if (max_char < 256)
1977 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1978 PyUnicode_1BYTE_DATA(res));
1979 else if (max_char < 0x10000)
1980 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1981 PyUnicode_2BYTE_DATA(res));
1982 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001984 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 return res;
1986}
1987
1988PyObject*
1989PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1990{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001991 if (size < 0) {
1992 PyErr_SetString(PyExc_ValueError, "size must be positive");
1993 return NULL;
1994 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001995 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001996 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001997 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001999 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002001 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002003 PyErr_SetString(PyExc_SystemError, "invalid kind");
2004 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002006}
2007
Victor Stinnerece58de2012-04-23 23:36:38 +02002008Py_UCS4
2009_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2010{
2011 enum PyUnicode_Kind kind;
2012 void *startptr, *endptr;
2013
2014 assert(PyUnicode_IS_READY(unicode));
2015 assert(0 <= start);
2016 assert(end <= PyUnicode_GET_LENGTH(unicode));
2017 assert(start <= end);
2018
2019 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2020 return PyUnicode_MAX_CHAR_VALUE(unicode);
2021
2022 if (start == end)
2023 return 127;
2024
Victor Stinner94d558b2012-04-27 22:26:58 +02002025 if (PyUnicode_IS_ASCII(unicode))
2026 return 127;
2027
Victor Stinnerece58de2012-04-23 23:36:38 +02002028 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002029 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002030 endptr = (char *)startptr + end * kind;
2031 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002032 switch(kind) {
2033 case PyUnicode_1BYTE_KIND:
2034 return ucs1lib_find_max_char(startptr, endptr);
2035 case PyUnicode_2BYTE_KIND:
2036 return ucs2lib_find_max_char(startptr, endptr);
2037 case PyUnicode_4BYTE_KIND:
2038 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002039 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002040 assert(0);
2041 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002042 }
2043}
2044
Victor Stinner25a4b292011-10-06 12:31:55 +02002045/* Ensure that a string uses the most efficient storage, if it is not the
2046 case: create a new string with of the right kind. Write NULL into *p_unicode
2047 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002048static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002049unicode_adjust_maxchar(PyObject **p_unicode)
2050{
2051 PyObject *unicode, *copy;
2052 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002053 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002054 unsigned int kind;
2055
2056 assert(p_unicode != NULL);
2057 unicode = *p_unicode;
2058 assert(PyUnicode_IS_READY(unicode));
2059 if (PyUnicode_IS_ASCII(unicode))
2060 return;
2061
2062 len = PyUnicode_GET_LENGTH(unicode);
2063 kind = PyUnicode_KIND(unicode);
2064 if (kind == PyUnicode_1BYTE_KIND) {
2065 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002066 max_char = ucs1lib_find_max_char(u, u + len);
2067 if (max_char >= 128)
2068 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002069 }
2070 else if (kind == PyUnicode_2BYTE_KIND) {
2071 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002072 max_char = ucs2lib_find_max_char(u, u + len);
2073 if (max_char >= 256)
2074 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002075 }
2076 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002077 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002078 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002079 max_char = ucs4lib_find_max_char(u, u + len);
2080 if (max_char >= 0x10000)
2081 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002082 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002083 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002084 if (copy != NULL)
2085 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002086 Py_DECREF(unicode);
2087 *p_unicode = copy;
2088}
2089
Victor Stinner034f6cf2011-09-30 02:26:44 +02002090PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002091_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002092{
Victor Stinner87af4f22011-11-21 23:03:47 +01002093 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002094 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002095
Victor Stinner034f6cf2011-09-30 02:26:44 +02002096 if (!PyUnicode_Check(unicode)) {
2097 PyErr_BadInternalCall();
2098 return NULL;
2099 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002100 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002101 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002102
Victor Stinner87af4f22011-11-21 23:03:47 +01002103 length = PyUnicode_GET_LENGTH(unicode);
2104 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002105 if (!copy)
2106 return NULL;
2107 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2108
Victor Stinner87af4f22011-11-21 23:03:47 +01002109 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2110 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002111 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002112 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002113}
2114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002115
Victor Stinnerbc603d12011-10-02 01:00:40 +02002116/* Widen Unicode objects to larger buffers. Don't write terminating null
2117 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002118
2119void*
2120_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2121{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002122 Py_ssize_t len;
2123 void *result;
2124 unsigned int skind;
2125
Benjamin Petersonbac79492012-01-14 13:34:47 -05002126 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002127 return NULL;
2128
2129 len = PyUnicode_GET_LENGTH(s);
2130 skind = PyUnicode_KIND(s);
2131 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002132 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002133 return NULL;
2134 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002135 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002136 case PyUnicode_2BYTE_KIND:
2137 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2138 if (!result)
2139 return PyErr_NoMemory();
2140 assert(skind == PyUnicode_1BYTE_KIND);
2141 _PyUnicode_CONVERT_BYTES(
2142 Py_UCS1, Py_UCS2,
2143 PyUnicode_1BYTE_DATA(s),
2144 PyUnicode_1BYTE_DATA(s) + len,
2145 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002146 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002147 case PyUnicode_4BYTE_KIND:
2148 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2149 if (!result)
2150 return PyErr_NoMemory();
2151 if (skind == PyUnicode_2BYTE_KIND) {
2152 _PyUnicode_CONVERT_BYTES(
2153 Py_UCS2, Py_UCS4,
2154 PyUnicode_2BYTE_DATA(s),
2155 PyUnicode_2BYTE_DATA(s) + len,
2156 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002158 else {
2159 assert(skind == PyUnicode_1BYTE_KIND);
2160 _PyUnicode_CONVERT_BYTES(
2161 Py_UCS1, Py_UCS4,
2162 PyUnicode_1BYTE_DATA(s),
2163 PyUnicode_1BYTE_DATA(s) + len,
2164 result);
2165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002166 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002167 default:
2168 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 }
Victor Stinner01698042011-10-04 00:04:26 +02002170 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 return NULL;
2172}
2173
2174static Py_UCS4*
2175as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2176 int copy_null)
2177{
2178 int kind;
2179 void *data;
2180 Py_ssize_t len, targetlen;
2181 if (PyUnicode_READY(string) == -1)
2182 return NULL;
2183 kind = PyUnicode_KIND(string);
2184 data = PyUnicode_DATA(string);
2185 len = PyUnicode_GET_LENGTH(string);
2186 targetlen = len;
2187 if (copy_null)
2188 targetlen++;
2189 if (!target) {
2190 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2191 PyErr_NoMemory();
2192 return NULL;
2193 }
2194 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2195 if (!target) {
2196 PyErr_NoMemory();
2197 return NULL;
2198 }
2199 }
2200 else {
2201 if (targetsize < targetlen) {
2202 PyErr_Format(PyExc_SystemError,
2203 "string is longer than the buffer");
2204 if (copy_null && 0 < targetsize)
2205 target[0] = 0;
2206 return NULL;
2207 }
2208 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002209 if (kind == PyUnicode_1BYTE_KIND) {
2210 Py_UCS1 *start = (Py_UCS1 *) data;
2211 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002213 else if (kind == PyUnicode_2BYTE_KIND) {
2214 Py_UCS2 *start = (Py_UCS2 *) data;
2215 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2216 }
2217 else {
2218 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002219 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 if (copy_null)
2222 target[len] = 0;
2223 return target;
2224}
2225
2226Py_UCS4*
2227PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002230 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002231 PyErr_BadInternalCall();
2232 return NULL;
2233 }
2234 return as_ucs4(string, target, targetsize, copy_null);
2235}
2236
2237Py_UCS4*
2238PyUnicode_AsUCS4Copy(PyObject *string)
2239{
2240 return as_ucs4(string, NULL, 0, 1);
2241}
2242
2243#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002244
Alexander Belopolsky40018472011-02-26 01:02:56 +00002245PyObject *
2246PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002247{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002248 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002249 if (size == 0) {
2250 Py_INCREF(unicode_empty);
2251 return unicode_empty;
2252 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002253 PyErr_BadInternalCall();
2254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002255 }
2256
Martin v. Löwis790465f2008-04-05 20:41:37 +00002257 if (size == -1) {
2258 size = wcslen(w);
2259 }
2260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002262}
2263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002265
Walter Dörwald346737f2007-05-31 10:44:43 +00002266static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002267makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2268 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002269{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002270 *fmt++ = '%';
2271 if (width) {
2272 if (zeropad)
2273 *fmt++ = '0';
2274 fmt += sprintf(fmt, "%d", width);
2275 }
2276 if (precision)
2277 fmt += sprintf(fmt, ".%d", precision);
2278 if (longflag)
2279 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002280 else if (longlongflag) {
2281 /* longlongflag should only ever be nonzero on machines with
2282 HAVE_LONG_LONG defined */
2283#ifdef HAVE_LONG_LONG
2284 char *f = PY_FORMAT_LONG_LONG;
2285 while (*f)
2286 *fmt++ = *f++;
2287#else
2288 /* we shouldn't ever get here */
2289 assert(0);
2290 *fmt++ = 'l';
2291#endif
2292 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002293 else if (size_tflag) {
2294 char *f = PY_FORMAT_SIZE_T;
2295 while (*f)
2296 *fmt++ = *f++;
2297 }
2298 *fmt++ = c;
2299 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002300}
2301
Victor Stinner96865452011-03-01 23:44:09 +00002302/* helper for PyUnicode_FromFormatV() */
2303
2304static const char*
2305parse_format_flags(const char *f,
2306 int *p_width, int *p_precision,
2307 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2308{
2309 int width, precision, longflag, longlongflag, size_tflag;
2310
2311 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2312 f++;
2313 width = 0;
2314 while (Py_ISDIGIT((unsigned)*f))
2315 width = (width*10) + *f++ - '0';
2316 precision = 0;
2317 if (*f == '.') {
2318 f++;
2319 while (Py_ISDIGIT((unsigned)*f))
2320 precision = (precision*10) + *f++ - '0';
2321 if (*f == '%') {
2322 /* "%.3%s" => f points to "3" */
2323 f--;
2324 }
2325 }
2326 if (*f == '\0') {
2327 /* bogus format "%.1" => go backward, f points to "1" */
2328 f--;
2329 }
2330 if (p_width != NULL)
2331 *p_width = width;
2332 if (p_precision != NULL)
2333 *p_precision = precision;
2334
2335 /* Handle %ld, %lu, %lld and %llu. */
2336 longflag = 0;
2337 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002338 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002339
2340 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002341 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002342 longflag = 1;
2343 ++f;
2344 }
2345#ifdef HAVE_LONG_LONG
2346 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002347 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002348 longlongflag = 1;
2349 f += 2;
2350 }
2351#endif
2352 }
2353 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002354 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002355 size_tflag = 1;
2356 ++f;
2357 }
2358 if (p_longflag != NULL)
2359 *p_longflag = longflag;
2360 if (p_longlongflag != NULL)
2361 *p_longlongflag = longlongflag;
2362 if (p_size_tflag != NULL)
2363 *p_size_tflag = size_tflag;
2364 return f;
2365}
2366
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002367/* maximum number of characters required for output of %ld. 21 characters
2368 allows for 64-bit integers (in decimal) and an optional sign. */
2369#define MAX_LONG_CHARS 21
2370/* maximum number of characters required for output of %lld.
2371 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2372 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2373#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2374
Walter Dörwaldd2034312007-05-18 16:29:38 +00002375PyObject *
2376PyUnicode_FromFormatV(const char *format, va_list vargs)
2377{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002378 va_list count;
2379 Py_ssize_t callcount = 0;
2380 PyObject **callresults = NULL;
2381 PyObject **callresult = NULL;
2382 Py_ssize_t n = 0;
2383 int width = 0;
2384 int precision = 0;
2385 int zeropad;
2386 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002387 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002388 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002389 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002390 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2391 Py_UCS4 argmaxchar;
2392 Py_ssize_t numbersize = 0;
2393 char *numberresults = NULL;
2394 char *numberresult = NULL;
2395 Py_ssize_t i;
2396 int kind;
2397 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002398
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002399 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002400 /* step 1: count the number of %S/%R/%A/%s format specifications
2401 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2402 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002404 * also estimate a upper bound for all the number formats in the string,
2405 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002407 for (f = format; *f; f++) {
2408 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002409 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002410 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2411 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2412 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2413 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002415 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002416#ifdef HAVE_LONG_LONG
2417 if (longlongflag) {
2418 if (width < MAX_LONG_LONG_CHARS)
2419 width = MAX_LONG_LONG_CHARS;
2420 }
2421 else
2422#endif
2423 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2424 including sign. Decimal takes the most space. This
2425 isn't enough for octal. If a width is specified we
2426 need more (which we allocate later). */
2427 if (width < MAX_LONG_CHARS)
2428 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429
2430 /* account for the size + '\0' to separate numbers
2431 inside of the numberresults buffer */
2432 numbersize += (width + 1);
2433 }
2434 }
2435 else if ((unsigned char)*f > 127) {
2436 PyErr_Format(PyExc_ValueError,
2437 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2438 "string, got a non-ASCII byte: 0x%02x",
2439 (unsigned char)*f);
2440 return NULL;
2441 }
2442 }
2443 /* step 2: allocate memory for the results of
2444 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2445 if (callcount) {
2446 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2447 if (!callresults) {
2448 PyErr_NoMemory();
2449 return NULL;
2450 }
2451 callresult = callresults;
2452 }
2453 /* step 2.5: allocate memory for the results of formating numbers */
2454 if (numbersize) {
2455 numberresults = PyObject_Malloc(numbersize);
2456 if (!numberresults) {
2457 PyErr_NoMemory();
2458 goto fail;
2459 }
2460 numberresult = numberresults;
2461 }
2462
2463 /* step 3: format numbers and figure out how large a buffer we need */
2464 for (f = format; *f; f++) {
2465 if (*f == '%') {
2466 const char* p;
2467 int longflag;
2468 int longlongflag;
2469 int size_tflag;
2470 int numprinted;
2471
2472 p = f;
2473 zeropad = (f[1] == '0');
2474 f = parse_format_flags(f, &width, &precision,
2475 &longflag, &longlongflag, &size_tflag);
2476 switch (*f) {
2477 case 'c':
2478 {
2479 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002480 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002481 n++;
2482 break;
2483 }
2484 case '%':
2485 n++;
2486 break;
2487 case 'i':
2488 case 'd':
2489 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2490 width, precision, *f);
2491 if (longflag)
2492 numprinted = sprintf(numberresult, fmt,
2493 va_arg(count, long));
2494#ifdef HAVE_LONG_LONG
2495 else if (longlongflag)
2496 numprinted = sprintf(numberresult, fmt,
2497 va_arg(count, PY_LONG_LONG));
2498#endif
2499 else if (size_tflag)
2500 numprinted = sprintf(numberresult, fmt,
2501 va_arg(count, Py_ssize_t));
2502 else
2503 numprinted = sprintf(numberresult, fmt,
2504 va_arg(count, int));
2505 n += numprinted;
2506 /* advance by +1 to skip over the '\0' */
2507 numberresult += (numprinted + 1);
2508 assert(*(numberresult - 1) == '\0');
2509 assert(*(numberresult - 2) != '\0');
2510 assert(numprinted >= 0);
2511 assert(numberresult <= numberresults + numbersize);
2512 break;
2513 case 'u':
2514 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2515 width, precision, 'u');
2516 if (longflag)
2517 numprinted = sprintf(numberresult, fmt,
2518 va_arg(count, unsigned long));
2519#ifdef HAVE_LONG_LONG
2520 else if (longlongflag)
2521 numprinted = sprintf(numberresult, fmt,
2522 va_arg(count, unsigned PY_LONG_LONG));
2523#endif
2524 else if (size_tflag)
2525 numprinted = sprintf(numberresult, fmt,
2526 va_arg(count, size_t));
2527 else
2528 numprinted = sprintf(numberresult, fmt,
2529 va_arg(count, unsigned int));
2530 n += numprinted;
2531 numberresult += (numprinted + 1);
2532 assert(*(numberresult - 1) == '\0');
2533 assert(*(numberresult - 2) != '\0');
2534 assert(numprinted >= 0);
2535 assert(numberresult <= numberresults + numbersize);
2536 break;
2537 case 'x':
2538 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2539 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2540 n += numprinted;
2541 numberresult += (numprinted + 1);
2542 assert(*(numberresult - 1) == '\0');
2543 assert(*(numberresult - 2) != '\0');
2544 assert(numprinted >= 0);
2545 assert(numberresult <= numberresults + numbersize);
2546 break;
2547 case 'p':
2548 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2549 /* %p is ill-defined: ensure leading 0x. */
2550 if (numberresult[1] == 'X')
2551 numberresult[1] = 'x';
2552 else if (numberresult[1] != 'x') {
2553 memmove(numberresult + 2, numberresult,
2554 strlen(numberresult) + 1);
2555 numberresult[0] = '0';
2556 numberresult[1] = 'x';
2557 numprinted += 2;
2558 }
2559 n += numprinted;
2560 numberresult += (numprinted + 1);
2561 assert(*(numberresult - 1) == '\0');
2562 assert(*(numberresult - 2) != '\0');
2563 assert(numprinted >= 0);
2564 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002565 break;
2566 case 's':
2567 {
2568 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002569 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002570 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002571 if (!str)
2572 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002573 /* since PyUnicode_DecodeUTF8 returns already flexible
2574 unicode objects, there is no need to call ready on them */
2575 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002576 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002578 /* Remember the str and switch to the next slot */
2579 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 break;
2581 }
2582 case 'U':
2583 {
2584 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002585 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002586 if (PyUnicode_READY(obj) == -1)
2587 goto fail;
2588 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002589 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 break;
2592 }
2593 case 'V':
2594 {
2595 PyObject *obj = va_arg(count, PyObject *);
2596 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002597 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002599 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002600 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 if (PyUnicode_READY(obj) == -1)
2602 goto fail;
2603 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002604 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002606 *callresult++ = NULL;
2607 }
2608 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002609 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002610 if (!str_obj)
2611 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002612 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002613 Py_DECREF(str_obj);
2614 goto fail;
2615 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002617 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002619 *callresult++ = str_obj;
2620 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 break;
2622 }
2623 case 'S':
2624 {
2625 PyObject *obj = va_arg(count, PyObject *);
2626 PyObject *str;
2627 assert(obj);
2628 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002629 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002630 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002631 if (PyUnicode_READY(str) == -1) {
2632 Py_DECREF(str);
2633 goto fail;
2634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002635 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002636 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002638 /* Remember the str and switch to the next slot */
2639 *callresult++ = str;
2640 break;
2641 }
2642 case 'R':
2643 {
2644 PyObject *obj = va_arg(count, PyObject *);
2645 PyObject *repr;
2646 assert(obj);
2647 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002648 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002649 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002650 if (PyUnicode_READY(repr) == -1) {
2651 Py_DECREF(repr);
2652 goto fail;
2653 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002654 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002655 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002656 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002657 /* Remember the repr and switch to the next slot */
2658 *callresult++ = repr;
2659 break;
2660 }
2661 case 'A':
2662 {
2663 PyObject *obj = va_arg(count, PyObject *);
2664 PyObject *ascii;
2665 assert(obj);
2666 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002667 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002668 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002669 if (PyUnicode_READY(ascii) == -1) {
2670 Py_DECREF(ascii);
2671 goto fail;
2672 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002674 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002675 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002676 /* Remember the repr and switch to the next slot */
2677 *callresult++ = ascii;
2678 break;
2679 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002680 default:
2681 /* if we stumble upon an unknown
2682 formatting code, copy the rest of
2683 the format string to the output
2684 string. (we cannot just skip the
2685 code, since there's no way to know
2686 what's in the argument list) */
2687 n += strlen(p);
2688 goto expand;
2689 }
2690 } else
2691 n++;
2692 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002693 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002695 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002696 we don't have to resize the string.
2697 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002698 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 if (!string)
2700 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 kind = PyUnicode_KIND(string);
2702 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002703 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002708 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002709
2710 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002711 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2712 /* checking for == because the last argument could be a empty
2713 string, which causes i to point to end, the assert at the end of
2714 the loop */
2715 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002716
Benjamin Peterson14339b62009-01-31 16:36:08 +00002717 switch (*f) {
2718 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002719 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720 const int ordinal = va_arg(vargs, int);
2721 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002722 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002723 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002724 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002725 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002726 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002727 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002728 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002729 {
Victor Stinner184252a2012-06-16 02:57:41 +02002730 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 /* unused, since we already have the result */
2732 if (*f == 'p')
2733 (void) va_arg(vargs, void *);
2734 else
2735 (void) va_arg(vargs, int);
2736 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002737 len = strlen(numberresult);
2738 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002739 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002740 i += len;
2741 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 assert(*numberresult == '\0');
2743 numberresult++;
2744 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002746 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002747 case 's':
2748 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002749 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002750 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002751 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752 size = PyUnicode_GET_LENGTH(*callresult);
2753 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002754 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002755 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002756 /* We're done with the unicode()/repr() => forget it */
2757 Py_DECREF(*callresult);
2758 /* switch to next unicode()/repr() result */
2759 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002760 break;
2761 }
2762 case 'U':
2763 {
2764 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002765 Py_ssize_t size;
2766 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2767 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002768 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002769 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002770 break;
2771 }
2772 case 'V':
2773 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002775 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002776 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002777 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002778 size = PyUnicode_GET_LENGTH(obj);
2779 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002780 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002782 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 size = PyUnicode_GET_LENGTH(*callresult);
2784 assert(PyUnicode_KIND(*callresult) <=
2785 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002786 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002788 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002789 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002790 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002791 break;
2792 }
2793 case 'S':
2794 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002795 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002796 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002797 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002798 /* unused, since we already have the result */
2799 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002800 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002801 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002802 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002803 /* We're done with the unicode()/repr() => forget it */
2804 Py_DECREF(*callresult);
2805 /* switch to next unicode()/repr() result */
2806 ++callresult;
2807 break;
2808 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002809 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002811 break;
2812 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002813 {
2814 Py_ssize_t len = strlen(p);
2815 unicode_write_cstr(string, i, p, len);
2816 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002817 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002818 goto end;
2819 }
Victor Stinner184252a2012-06-16 02:57:41 +02002820 }
Victor Stinner1205f272010-09-11 00:54:47 +00002821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002822 else {
2823 assert(i < PyUnicode_GET_LENGTH(string));
2824 PyUnicode_WRITE(kind, data, i++, *f);
2825 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002826 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002827 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002828
Benjamin Peterson29060642009-01-31 22:14:21 +00002829 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002830 if (callresults)
2831 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002832 if (numberresults)
2833 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002834 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002835 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002836 if (callresults) {
2837 PyObject **callresult2 = callresults;
2838 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002839 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002840 ++callresult2;
2841 }
2842 PyObject_Free(callresults);
2843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002844 if (numberresults)
2845 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002846 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002847}
2848
Walter Dörwaldd2034312007-05-18 16:29:38 +00002849PyObject *
2850PyUnicode_FromFormat(const char *format, ...)
2851{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002852 PyObject* ret;
2853 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002854
2855#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002856 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002857#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002858 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002859#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002860 ret = PyUnicode_FromFormatV(format, vargs);
2861 va_end(vargs);
2862 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863}
2864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865#ifdef HAVE_WCHAR_H
2866
Victor Stinner5593d8a2010-10-02 11:11:27 +00002867/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2868 convert a Unicode object to a wide character string.
2869
Victor Stinnerd88d9832011-09-06 02:00:05 +02002870 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002871 character) required to convert the unicode object. Ignore size argument.
2872
Victor Stinnerd88d9832011-09-06 02:00:05 +02002873 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002874 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002875 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002876static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002877unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002878 wchar_t *w,
2879 Py_ssize_t size)
2880{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002881 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002882 const wchar_t *wstr;
2883
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002884 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 if (wstr == NULL)
2886 return -1;
2887
Victor Stinner5593d8a2010-10-02 11:11:27 +00002888 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002889 if (size > res)
2890 size = res + 1;
2891 else
2892 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002893 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002894 return res;
2895 }
2896 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002897 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002898}
2899
2900Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002901PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002902 wchar_t *w,
2903 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002904{
2905 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 PyErr_BadInternalCall();
2907 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002908 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002909 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002910}
2911
Victor Stinner137c34c2010-09-29 10:25:54 +00002912wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002913PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002914 Py_ssize_t *size)
2915{
2916 wchar_t* buffer;
2917 Py_ssize_t buflen;
2918
2919 if (unicode == NULL) {
2920 PyErr_BadInternalCall();
2921 return NULL;
2922 }
2923
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002924 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002925 if (buflen == -1)
2926 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002927 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002928 PyErr_NoMemory();
2929 return NULL;
2930 }
2931
Victor Stinner137c34c2010-09-29 10:25:54 +00002932 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2933 if (buffer == NULL) {
2934 PyErr_NoMemory();
2935 return NULL;
2936 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002937 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002938 if (buflen == -1) {
2939 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002940 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002941 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002942 if (size != NULL)
2943 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002944 return buffer;
2945}
2946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002947#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002948
Alexander Belopolsky40018472011-02-26 01:02:56 +00002949PyObject *
2950PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002953 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002954 PyErr_SetString(PyExc_ValueError,
2955 "chr() arg not in range(0x110000)");
2956 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002957 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (ordinal < 256)
2960 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002962 v = PyUnicode_New(1, ordinal);
2963 if (v == NULL)
2964 return NULL;
2965 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002966 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002967 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002968}
2969
Alexander Belopolsky40018472011-02-26 01:02:56 +00002970PyObject *
2971PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002972{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002973 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002974 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002975 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002976 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002977 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 Py_INCREF(obj);
2979 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002980 }
2981 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002982 /* For a Unicode subtype that's not a Unicode object,
2983 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002984 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002985 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002986 PyErr_Format(PyExc_TypeError,
2987 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002988 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002989 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002990}
2991
Alexander Belopolsky40018472011-02-26 01:02:56 +00002992PyObject *
2993PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002994 const char *encoding,
2995 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002996{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002997 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002998 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002999
Guido van Rossumd57fd912000-03-10 22:53:23 +00003000 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003001 PyErr_BadInternalCall();
3002 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003003 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003004
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003005 /* Decoding bytes objects is the most common case and should be fast */
3006 if (PyBytes_Check(obj)) {
3007 if (PyBytes_GET_SIZE(obj) == 0) {
3008 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003009 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003010 }
3011 else {
3012 v = PyUnicode_Decode(
3013 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3014 encoding, errors);
3015 }
3016 return v;
3017 }
3018
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003019 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 PyErr_SetString(PyExc_TypeError,
3021 "decoding str is not supported");
3022 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003023 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003024
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003025 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3026 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3027 PyErr_Format(PyExc_TypeError,
3028 "coercing to str: need bytes, bytearray "
3029 "or buffer-like object, %.80s found",
3030 Py_TYPE(obj)->tp_name);
3031 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003032 }
Tim Petersced69f82003-09-16 20:30:58 +00003033
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003034 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003035 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003036 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037 }
Tim Petersced69f82003-09-16 20:30:58 +00003038 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003039 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003040
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003041 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043}
3044
Victor Stinner600d3be2010-06-10 12:00:55 +00003045/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003046 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3047 1 on success. */
3048static int
3049normalize_encoding(const char *encoding,
3050 char *lower,
3051 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003053 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003054 char *l;
3055 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003056
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003057 if (encoding == NULL) {
3058 strcpy(lower, "utf-8");
3059 return 1;
3060 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003061 e = encoding;
3062 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003063 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003064 while (*e) {
3065 if (l == l_end)
3066 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003067 if (Py_ISUPPER(*e)) {
3068 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003069 }
3070 else if (*e == '_') {
3071 *l++ = '-';
3072 e++;
3073 }
3074 else {
3075 *l++ = *e++;
3076 }
3077 }
3078 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003079 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003080}
3081
Alexander Belopolsky40018472011-02-26 01:02:56 +00003082PyObject *
3083PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003084 Py_ssize_t size,
3085 const char *encoding,
3086 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003087{
3088 PyObject *buffer = NULL, *unicode;
3089 Py_buffer info;
3090 char lower[11]; /* Enough for any encoding shortcut */
3091
Fred Drakee4315f52000-05-09 19:53:39 +00003092 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003093 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003094 if ((strcmp(lower, "utf-8") == 0) ||
3095 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003096 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003097 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003098 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003099 (strcmp(lower, "iso-8859-1") == 0))
3100 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003101#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003102 else if (strcmp(lower, "mbcs") == 0)
3103 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003104#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003105 else if (strcmp(lower, "ascii") == 0)
3106 return PyUnicode_DecodeASCII(s, size, errors);
3107 else if (strcmp(lower, "utf-16") == 0)
3108 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3109 else if (strcmp(lower, "utf-32") == 0)
3110 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3111 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003112
3113 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003114 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003115 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003116 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003117 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118 if (buffer == NULL)
3119 goto onError;
3120 unicode = PyCodec_Decode(buffer, encoding, errors);
3121 if (unicode == NULL)
3122 goto onError;
3123 if (!PyUnicode_Check(unicode)) {
3124 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003125 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003126 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 Py_DECREF(unicode);
3128 goto onError;
3129 }
3130 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003131 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003132
Benjamin Peterson29060642009-01-31 22:14:21 +00003133 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003134 Py_XDECREF(buffer);
3135 return NULL;
3136}
3137
Alexander Belopolsky40018472011-02-26 01:02:56 +00003138PyObject *
3139PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003140 const char *encoding,
3141 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003142{
3143 PyObject *v;
3144
3145 if (!PyUnicode_Check(unicode)) {
3146 PyErr_BadArgument();
3147 goto onError;
3148 }
3149
3150 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003151 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003152
3153 /* Decode via the codec registry */
3154 v = PyCodec_Decode(unicode, encoding, errors);
3155 if (v == NULL)
3156 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003157 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003158
Benjamin Peterson29060642009-01-31 22:14:21 +00003159 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003160 return NULL;
3161}
3162
Alexander Belopolsky40018472011-02-26 01:02:56 +00003163PyObject *
3164PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003165 const char *encoding,
3166 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003167{
3168 PyObject *v;
3169
3170 if (!PyUnicode_Check(unicode)) {
3171 PyErr_BadArgument();
3172 goto onError;
3173 }
3174
3175 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003176 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003177
3178 /* Decode via the codec registry */
3179 v = PyCodec_Decode(unicode, encoding, errors);
3180 if (v == NULL)
3181 goto onError;
3182 if (!PyUnicode_Check(v)) {
3183 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003184 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003185 Py_TYPE(v)->tp_name);
3186 Py_DECREF(v);
3187 goto onError;
3188 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003189 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003190
Benjamin Peterson29060642009-01-31 22:14:21 +00003191 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003192 return NULL;
3193}
3194
Alexander Belopolsky40018472011-02-26 01:02:56 +00003195PyObject *
3196PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003197 Py_ssize_t size,
3198 const char *encoding,
3199 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200{
3201 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003202
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 unicode = PyUnicode_FromUnicode(s, size);
3204 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003205 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3207 Py_DECREF(unicode);
3208 return v;
3209}
3210
Alexander Belopolsky40018472011-02-26 01:02:56 +00003211PyObject *
3212PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003213 const char *encoding,
3214 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003215{
3216 PyObject *v;
3217
3218 if (!PyUnicode_Check(unicode)) {
3219 PyErr_BadArgument();
3220 goto onError;
3221 }
3222
3223 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003224 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003225
3226 /* Encode via the codec registry */
3227 v = PyCodec_Encode(unicode, encoding, errors);
3228 if (v == NULL)
3229 goto onError;
3230 return v;
3231
Benjamin Peterson29060642009-01-31 22:14:21 +00003232 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003233 return NULL;
3234}
3235
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236static size_t
3237wcstombs_errorpos(const wchar_t *wstr)
3238{
3239 size_t len;
3240#if SIZEOF_WCHAR_T == 2
3241 wchar_t buf[3];
3242#else
3243 wchar_t buf[2];
3244#endif
3245 char outbuf[MB_LEN_MAX];
3246 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003247
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003248#if SIZEOF_WCHAR_T == 2
3249 buf[2] = 0;
3250#else
3251 buf[1] = 0;
3252#endif
3253 start = wstr;
3254 while (*wstr != L'\0')
3255 {
3256 previous = wstr;
3257#if SIZEOF_WCHAR_T == 2
3258 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3259 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3260 {
3261 buf[0] = wstr[0];
3262 buf[1] = wstr[1];
3263 wstr += 2;
3264 }
3265 else {
3266 buf[0] = *wstr;
3267 buf[1] = 0;
3268 wstr++;
3269 }
3270#else
3271 buf[0] = *wstr;
3272 wstr++;
3273#endif
3274 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003275 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 }
3278
3279 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 return 0;
3281}
3282
Victor Stinner1b579672011-12-17 05:47:23 +01003283static int
3284locale_error_handler(const char *errors, int *surrogateescape)
3285{
3286 if (errors == NULL) {
3287 *surrogateescape = 0;
3288 return 0;
3289 }
3290
3291 if (strcmp(errors, "strict") == 0) {
3292 *surrogateescape = 0;
3293 return 0;
3294 }
3295 if (strcmp(errors, "surrogateescape") == 0) {
3296 *surrogateescape = 1;
3297 return 0;
3298 }
3299 PyErr_Format(PyExc_ValueError,
3300 "only 'strict' and 'surrogateescape' error handlers "
3301 "are supported, not '%s'",
3302 errors);
3303 return -1;
3304}
3305
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003307PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003308{
3309 Py_ssize_t wlen, wlen2;
3310 wchar_t *wstr;
3311 PyObject *bytes = NULL;
3312 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003313 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003314 PyObject *exc;
3315 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003316 int surrogateescape;
3317
3318 if (locale_error_handler(errors, &surrogateescape) < 0)
3319 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003320
3321 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3322 if (wstr == NULL)
3323 return NULL;
3324
3325 wlen2 = wcslen(wstr);
3326 if (wlen2 != wlen) {
3327 PyMem_Free(wstr);
3328 PyErr_SetString(PyExc_TypeError, "embedded null character");
3329 return NULL;
3330 }
3331
3332 if (surrogateescape) {
3333 /* locale encoding with surrogateescape */
3334 char *str;
3335
3336 str = _Py_wchar2char(wstr, &error_pos);
3337 if (str == NULL) {
3338 if (error_pos == (size_t)-1) {
3339 PyErr_NoMemory();
3340 PyMem_Free(wstr);
3341 return NULL;
3342 }
3343 else {
3344 goto encode_error;
3345 }
3346 }
3347 PyMem_Free(wstr);
3348
3349 bytes = PyBytes_FromString(str);
3350 PyMem_Free(str);
3351 }
3352 else {
3353 size_t len, len2;
3354
3355 len = wcstombs(NULL, wstr, 0);
3356 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003357 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003358 goto encode_error;
3359 }
3360
3361 bytes = PyBytes_FromStringAndSize(NULL, len);
3362 if (bytes == NULL) {
3363 PyMem_Free(wstr);
3364 return NULL;
3365 }
3366
3367 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3368 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003369 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 goto encode_error;
3371 }
3372 PyMem_Free(wstr);
3373 }
3374 return bytes;
3375
3376encode_error:
3377 errmsg = strerror(errno);
3378 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003379
3380 if (error_pos == (size_t)-1)
3381 error_pos = wcstombs_errorpos(wstr);
3382
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003383 PyMem_Free(wstr);
3384 Py_XDECREF(bytes);
3385
Victor Stinner2f197072011-12-17 07:08:30 +01003386 if (errmsg != NULL) {
3387 size_t errlen;
3388 wstr = _Py_char2wchar(errmsg, &errlen);
3389 if (wstr != NULL) {
3390 reason = PyUnicode_FromWideChar(wstr, errlen);
3391 PyMem_Free(wstr);
3392 } else
3393 errmsg = NULL;
3394 }
3395 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003396 reason = PyUnicode_FromString(
3397 "wcstombs() encountered an unencodable "
3398 "wide character");
3399 if (reason == NULL)
3400 return NULL;
3401
3402 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3403 "locale", unicode,
3404 (Py_ssize_t)error_pos,
3405 (Py_ssize_t)(error_pos+1),
3406 reason);
3407 Py_DECREF(reason);
3408 if (exc != NULL) {
3409 PyCodec_StrictErrors(exc);
3410 Py_XDECREF(exc);
3411 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003412 return NULL;
3413}
3414
Victor Stinnerad158722010-10-27 00:25:46 +00003415PyObject *
3416PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003417{
Victor Stinner99b95382011-07-04 14:23:54 +02003418#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003419 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003420#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003421 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003422#else
Victor Stinner793b5312011-04-27 00:24:21 +02003423 PyInterpreterState *interp = PyThreadState_GET()->interp;
3424 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3425 cannot use it to encode and decode filenames before it is loaded. Load
3426 the Python codec requires to encode at least its own filename. Use the C
3427 version of the locale codec until the codec registry is initialized and
3428 the Python codec is loaded.
3429
3430 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3431 cannot only rely on it: check also interp->fscodec_initialized for
3432 subinterpreters. */
3433 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003434 return PyUnicode_AsEncodedString(unicode,
3435 Py_FileSystemDefaultEncoding,
3436 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003437 }
3438 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003439 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003440 }
Victor Stinnerad158722010-10-27 00:25:46 +00003441#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003442}
3443
Alexander Belopolsky40018472011-02-26 01:02:56 +00003444PyObject *
3445PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003446 const char *encoding,
3447 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003448{
3449 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003450 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003451
Guido van Rossumd57fd912000-03-10 22:53:23 +00003452 if (!PyUnicode_Check(unicode)) {
3453 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003454 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003455 }
Fred Drakee4315f52000-05-09 19:53:39 +00003456
Fred Drakee4315f52000-05-09 19:53:39 +00003457 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003458 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003459 if ((strcmp(lower, "utf-8") == 0) ||
3460 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003461 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003462 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003463 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003464 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003466 }
Victor Stinner37296e82010-06-10 13:36:23 +00003467 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003468 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003469 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003470 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003471#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003472 else if (strcmp(lower, "mbcs") == 0)
3473 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003474#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003475 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003476 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003478
3479 /* Encode via the codec registry */
3480 v = PyCodec_Encode(unicode, encoding, errors);
3481 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003482 return NULL;
3483
3484 /* The normal path */
3485 if (PyBytes_Check(v))
3486 return v;
3487
3488 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003489 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003490 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003491 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003492
3493 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3494 "encoder %s returned bytearray instead of bytes",
3495 encoding);
3496 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003497 Py_DECREF(v);
3498 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003499 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003500
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003501 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3502 Py_DECREF(v);
3503 return b;
3504 }
3505
3506 PyErr_Format(PyExc_TypeError,
3507 "encoder did not return a bytes object (type=%.400s)",
3508 Py_TYPE(v)->tp_name);
3509 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003510 return NULL;
3511}
3512
Alexander Belopolsky40018472011-02-26 01:02:56 +00003513PyObject *
3514PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003515 const char *encoding,
3516 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003517{
3518 PyObject *v;
3519
3520 if (!PyUnicode_Check(unicode)) {
3521 PyErr_BadArgument();
3522 goto onError;
3523 }
3524
3525 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003526 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003527
3528 /* Encode via the codec registry */
3529 v = PyCodec_Encode(unicode, encoding, errors);
3530 if (v == NULL)
3531 goto onError;
3532 if (!PyUnicode_Check(v)) {
3533 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003534 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003535 Py_TYPE(v)->tp_name);
3536 Py_DECREF(v);
3537 goto onError;
3538 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003539 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003540
Benjamin Peterson29060642009-01-31 22:14:21 +00003541 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003542 return NULL;
3543}
3544
Victor Stinner2f197072011-12-17 07:08:30 +01003545static size_t
3546mbstowcs_errorpos(const char *str, size_t len)
3547{
3548#ifdef HAVE_MBRTOWC
3549 const char *start = str;
3550 mbstate_t mbs;
3551 size_t converted;
3552 wchar_t ch;
3553
3554 memset(&mbs, 0, sizeof mbs);
3555 while (len)
3556 {
3557 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3558 if (converted == 0)
3559 /* Reached end of string */
3560 break;
3561 if (converted == (size_t)-1 || converted == (size_t)-2) {
3562 /* Conversion error or incomplete character */
3563 return str - start;
3564 }
3565 else {
3566 str += converted;
3567 len -= converted;
3568 }
3569 }
3570 /* failed to find the undecodable byte sequence */
3571 return 0;
3572#endif
3573 return 0;
3574}
3575
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003576PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003577PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003578 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003579{
3580 wchar_t smallbuf[256];
3581 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3582 wchar_t *wstr;
3583 size_t wlen, wlen2;
3584 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003585 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003586 size_t error_pos;
3587 char *errmsg;
3588 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003589
3590 if (locale_error_handler(errors, &surrogateescape) < 0)
3591 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003592
3593 if (str[len] != '\0' || len != strlen(str)) {
3594 PyErr_SetString(PyExc_TypeError, "embedded null character");
3595 return NULL;
3596 }
3597
3598 if (surrogateescape)
3599 {
3600 wstr = _Py_char2wchar(str, &wlen);
3601 if (wstr == NULL) {
3602 if (wlen == (size_t)-1)
3603 PyErr_NoMemory();
3604 else
3605 PyErr_SetFromErrno(PyExc_OSError);
3606 return NULL;
3607 }
3608
3609 unicode = PyUnicode_FromWideChar(wstr, wlen);
3610 PyMem_Free(wstr);
3611 }
3612 else {
3613#ifndef HAVE_BROKEN_MBSTOWCS
3614 wlen = mbstowcs(NULL, str, 0);
3615#else
3616 wlen = len;
3617#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003618 if (wlen == (size_t)-1)
3619 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003620 if (wlen+1 <= smallbuf_len) {
3621 wstr = smallbuf;
3622 }
3623 else {
3624 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3625 return PyErr_NoMemory();
3626
3627 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3628 if (!wstr)
3629 return PyErr_NoMemory();
3630 }
3631
3632 /* This shouldn't fail now */
3633 wlen2 = mbstowcs(wstr, str, wlen+1);
3634 if (wlen2 == (size_t)-1) {
3635 if (wstr != smallbuf)
3636 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003637 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003638 }
3639#ifdef HAVE_BROKEN_MBSTOWCS
3640 assert(wlen2 == wlen);
3641#endif
3642 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3643 if (wstr != smallbuf)
3644 PyMem_Free(wstr);
3645 }
3646 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003647
3648decode_error:
3649 errmsg = strerror(errno);
3650 assert(errmsg != NULL);
3651
3652 error_pos = mbstowcs_errorpos(str, len);
3653 if (errmsg != NULL) {
3654 size_t errlen;
3655 wstr = _Py_char2wchar(errmsg, &errlen);
3656 if (wstr != NULL) {
3657 reason = PyUnicode_FromWideChar(wstr, errlen);
3658 PyMem_Free(wstr);
3659 } else
3660 errmsg = NULL;
3661 }
3662 if (errmsg == NULL)
3663 reason = PyUnicode_FromString(
3664 "mbstowcs() encountered an invalid multibyte sequence");
3665 if (reason == NULL)
3666 return NULL;
3667
3668 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3669 "locale", str, len,
3670 (Py_ssize_t)error_pos,
3671 (Py_ssize_t)(error_pos+1),
3672 reason);
3673 Py_DECREF(reason);
3674 if (exc != NULL) {
3675 PyCodec_StrictErrors(exc);
3676 Py_XDECREF(exc);
3677 }
3678 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003679}
3680
3681PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003682PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003683{
3684 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003685 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003686}
3687
3688
3689PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003690PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003691 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003692 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3693}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003694
Christian Heimes5894ba72007-11-04 11:43:14 +00003695PyObject*
3696PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3697{
Victor Stinner99b95382011-07-04 14:23:54 +02003698#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003699 return PyUnicode_DecodeMBCS(s, size, NULL);
3700#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003701 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003702#else
Victor Stinner793b5312011-04-27 00:24:21 +02003703 PyInterpreterState *interp = PyThreadState_GET()->interp;
3704 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3705 cannot use it to encode and decode filenames before it is loaded. Load
3706 the Python codec requires to encode at least its own filename. Use the C
3707 version of the locale codec until the codec registry is initialized and
3708 the Python codec is loaded.
3709
3710 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3711 cannot only rely on it: check also interp->fscodec_initialized for
3712 subinterpreters. */
3713 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003714 return PyUnicode_Decode(s, size,
3715 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003716 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003717 }
3718 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003719 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003720 }
Victor Stinnerad158722010-10-27 00:25:46 +00003721#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003722}
3723
Martin v. Löwis011e8422009-05-05 04:43:17 +00003724
3725int
Antoine Pitrou13348842012-01-29 18:36:34 +01003726_PyUnicode_HasNULChars(PyObject* s)
3727{
3728 static PyObject *nul = NULL;
3729
3730 if (nul == NULL)
3731 nul = PyUnicode_FromStringAndSize("\0", 1);
3732 if (nul == NULL)
3733 return -1;
3734 return PyUnicode_Contains(s, nul);
3735}
3736
3737
3738int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003739PyUnicode_FSConverter(PyObject* arg, void* addr)
3740{
3741 PyObject *output = NULL;
3742 Py_ssize_t size;
3743 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003744 if (arg == NULL) {
3745 Py_DECREF(*(PyObject**)addr);
3746 return 1;
3747 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003748 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003749 output = arg;
3750 Py_INCREF(output);
3751 }
3752 else {
3753 arg = PyUnicode_FromObject(arg);
3754 if (!arg)
3755 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003756 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003757 Py_DECREF(arg);
3758 if (!output)
3759 return 0;
3760 if (!PyBytes_Check(output)) {
3761 Py_DECREF(output);
3762 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3763 return 0;
3764 }
3765 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003766 size = PyBytes_GET_SIZE(output);
3767 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003768 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003769 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003770 Py_DECREF(output);
3771 return 0;
3772 }
3773 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003774 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003775}
3776
3777
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003778int
3779PyUnicode_FSDecoder(PyObject* arg, void* addr)
3780{
3781 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003782 if (arg == NULL) {
3783 Py_DECREF(*(PyObject**)addr);
3784 return 1;
3785 }
3786 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003787 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003789 output = arg;
3790 Py_INCREF(output);
3791 }
3792 else {
3793 arg = PyBytes_FromObject(arg);
3794 if (!arg)
3795 return 0;
3796 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3797 PyBytes_GET_SIZE(arg));
3798 Py_DECREF(arg);
3799 if (!output)
3800 return 0;
3801 if (!PyUnicode_Check(output)) {
3802 Py_DECREF(output);
3803 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3804 return 0;
3805 }
3806 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003807 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003808 Py_DECREF(output);
3809 return 0;
3810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003812 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003813 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3814 Py_DECREF(output);
3815 return 0;
3816 }
3817 *(PyObject**)addr = output;
3818 return Py_CLEANUP_SUPPORTED;
3819}
3820
3821
Martin v. Löwis5b222132007-06-10 09:51:05 +00003822char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003824{
Christian Heimesf3863112007-11-22 07:46:41 +00003825 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003827 if (!PyUnicode_Check(unicode)) {
3828 PyErr_BadArgument();
3829 return NULL;
3830 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003831 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003832 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003834 if (PyUnicode_UTF8(unicode) == NULL) {
3835 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3837 if (bytes == NULL)
3838 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003839 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3840 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 Py_DECREF(bytes);
3842 return NULL;
3843 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003844 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3845 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3846 PyBytes_AS_STRING(bytes),
3847 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003848 Py_DECREF(bytes);
3849 }
3850
3851 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003852 *psize = PyUnicode_UTF8_LENGTH(unicode);
3853 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003854}
3855
3856char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003857PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3860}
3861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862Py_UNICODE *
3863PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3864{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 const unsigned char *one_byte;
3866#if SIZEOF_WCHAR_T == 4
3867 const Py_UCS2 *two_bytes;
3868#else
3869 const Py_UCS4 *four_bytes;
3870 const Py_UCS4 *ucs4_end;
3871 Py_ssize_t num_surrogates;
3872#endif
3873 wchar_t *w;
3874 wchar_t *wchar_end;
3875
3876 if (!PyUnicode_Check(unicode)) {
3877 PyErr_BadArgument();
3878 return NULL;
3879 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003880 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 assert(_PyUnicode_KIND(unicode) != 0);
3883 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003885 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003886#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003887 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3888 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 num_surrogates = 0;
3890
3891 for (; four_bytes < ucs4_end; ++four_bytes) {
3892 if (*four_bytes > 0xFFFF)
3893 ++num_surrogates;
3894 }
3895
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003896 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3897 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3898 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899 PyErr_NoMemory();
3900 return NULL;
3901 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003902 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003903
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003904 w = _PyUnicode_WSTR(unicode);
3905 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3906 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003907 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3908 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003909 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003911 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3912 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913 }
3914 else
3915 *w = *four_bytes;
3916
3917 if (w > wchar_end) {
3918 assert(0 && "Miscalculated string end");
3919 }
3920 }
3921 *w = 0;
3922#else
3923 /* sizeof(wchar_t) == 4 */
3924 Py_FatalError("Impossible unicode object state, wstr and str "
3925 "should share memory already.");
3926 return NULL;
3927#endif
3928 }
3929 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003930 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3931 (_PyUnicode_LENGTH(unicode) + 1));
3932 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003933 PyErr_NoMemory();
3934 return NULL;
3935 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003936 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3937 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3938 w = _PyUnicode_WSTR(unicode);
3939 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3942 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 for (; w < wchar_end; ++one_byte, ++w)
3944 *w = *one_byte;
3945 /* null-terminate the wstr */
3946 *w = 0;
3947 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003948 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003950 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003951 for (; w < wchar_end; ++two_bytes, ++w)
3952 *w = *two_bytes;
3953 /* null-terminate the wstr */
3954 *w = 0;
3955#else
3956 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003957 PyObject_FREE(_PyUnicode_WSTR(unicode));
3958 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959 Py_FatalError("Impossible unicode object state, wstr "
3960 "and str should share memory already.");
3961 return NULL;
3962#endif
3963 }
3964 else {
3965 assert(0 && "This should never happen.");
3966 }
3967 }
3968 }
3969 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003970 *size = PyUnicode_WSTR_LENGTH(unicode);
3971 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003972}
3973
Alexander Belopolsky40018472011-02-26 01:02:56 +00003974Py_UNICODE *
3975PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003978}
3979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980
Alexander Belopolsky40018472011-02-26 01:02:56 +00003981Py_ssize_t
3982PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003983{
3984 if (!PyUnicode_Check(unicode)) {
3985 PyErr_BadArgument();
3986 goto onError;
3987 }
3988 return PyUnicode_GET_SIZE(unicode);
3989
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003991 return -1;
3992}
3993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003994Py_ssize_t
3995PyUnicode_GetLength(PyObject *unicode)
3996{
Victor Stinner07621332012-06-16 04:53:46 +02003997 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 PyErr_BadArgument();
3999 return -1;
4000 }
Victor Stinner07621332012-06-16 04:53:46 +02004001 if (PyUnicode_READY(unicode) == -1)
4002 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 return PyUnicode_GET_LENGTH(unicode);
4004}
4005
4006Py_UCS4
4007PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4008{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004009 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4010 PyErr_BadArgument();
4011 return (Py_UCS4)-1;
4012 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004013 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004014 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 return (Py_UCS4)-1;
4016 }
4017 return PyUnicode_READ_CHAR(unicode, index);
4018}
4019
4020int
4021PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4022{
4023 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004024 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025 return -1;
4026 }
Victor Stinner488fa492011-12-12 00:01:39 +01004027 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004028 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004029 PyErr_SetString(PyExc_IndexError, "string index out of range");
4030 return -1;
4031 }
Victor Stinner488fa492011-12-12 00:01:39 +01004032 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004033 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004034 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4035 PyErr_SetString(PyExc_ValueError, "character out of range");
4036 return -1;
4037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4039 index, ch);
4040 return 0;
4041}
4042
Alexander Belopolsky40018472011-02-26 01:02:56 +00004043const char *
4044PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004045{
Victor Stinner42cb4622010-09-01 19:39:01 +00004046 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004047}
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049/* create or adjust a UnicodeDecodeError */
4050static void
4051make_decode_exception(PyObject **exceptionObject,
4052 const char *encoding,
4053 const char *input, Py_ssize_t length,
4054 Py_ssize_t startpos, Py_ssize_t endpos,
4055 const char *reason)
4056{
4057 if (*exceptionObject == NULL) {
4058 *exceptionObject = PyUnicodeDecodeError_Create(
4059 encoding, input, length, startpos, endpos, reason);
4060 }
4061 else {
4062 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4063 goto onError;
4064 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4065 goto onError;
4066 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4067 goto onError;
4068 }
4069 return;
4070
4071onError:
4072 Py_DECREF(*exceptionObject);
4073 *exceptionObject = NULL;
4074}
4075
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076/* error handling callback helper:
4077 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004078 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004079 and adjust various state variables.
4080 return 0 on success, -1 on error
4081*/
4082
Alexander Belopolsky40018472011-02-26 01:02:56 +00004083static int
4084unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004085 const char *encoding, const char *reason,
4086 const char **input, const char **inend, Py_ssize_t *startinpos,
4087 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004088 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004089{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004090 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004091
4092 PyObject *restuple = NULL;
4093 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004094 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004095 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004096 Py_ssize_t requiredsize;
4097 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004098 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099 int res = -1;
4100
Victor Stinner596a6c42011-11-09 00:02:18 +01004101 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4102 outsize = PyUnicode_GET_LENGTH(*output);
4103 else
4104 outsize = _PyUnicode_WSTR_LENGTH(*output);
4105
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004107 *errorHandler = PyCodec_LookupError(errors);
4108 if (*errorHandler == NULL)
4109 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 }
4111
Victor Stinner554f3f02010-06-16 23:33:54 +00004112 make_decode_exception(exceptionObject,
4113 encoding,
4114 *input, *inend - *input,
4115 *startinpos, *endinpos,
4116 reason);
4117 if (*exceptionObject == NULL)
4118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119
4120 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4121 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004122 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004123 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004124 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004125 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004126 }
4127 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004129 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004130 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004131
4132 /* Copy back the bytes variables, which might have been modified by the
4133 callback */
4134 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4135 if (!inputobj)
4136 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004137 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004138 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004139 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004140 *input = PyBytes_AS_STRING(inputobj);
4141 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004142 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004143 /* we can DECREF safely, as the exception has another reference,
4144 so the object won't go away. */
4145 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004146
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004147 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004148 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004149 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4151 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004152 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004153
Victor Stinner596a6c42011-11-09 00:02:18 +01004154 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4155 /* need more space? (at least enough for what we
4156 have+the replacement+the rest of the string (starting
4157 at the new input position), so we won't have to check space
4158 when there are no errors in the rest of the string) */
4159 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4160 requiredsize = *outpos + replen + insize-newpos;
4161 if (requiredsize > outsize) {
4162 if (requiredsize<2*outsize)
4163 requiredsize = 2*outsize;
4164 if (unicode_resize(output, requiredsize) < 0)
4165 goto onError;
4166 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004167 if (unicode_widen(output, *outpos,
4168 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004169 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004170 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004171 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004173 else {
4174 wchar_t *repwstr;
4175 Py_ssize_t repwlen;
4176 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4177 if (repwstr == NULL)
4178 goto onError;
4179 /* need more space? (at least enough for what we
4180 have+the replacement+the rest of the string (starting
4181 at the new input position), so we won't have to check space
4182 when there are no errors in the rest of the string) */
4183 requiredsize = *outpos + repwlen + insize-newpos;
4184 if (requiredsize > outsize) {
4185 if (requiredsize < 2*outsize)
4186 requiredsize = 2*outsize;
4187 if (unicode_resize(output, requiredsize) < 0)
4188 goto onError;
4189 }
4190 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4191 *outpos += repwlen;
4192 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004193 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004194 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004196 /* we made it! */
4197 res = 0;
4198
Benjamin Peterson29060642009-01-31 22:14:21 +00004199 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 Py_XDECREF(restuple);
4201 return res;
4202}
4203
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004204/* --- UTF-7 Codec -------------------------------------------------------- */
4205
Antoine Pitrou244651a2009-05-04 18:56:13 +00004206/* See RFC2152 for details. We encode conservatively and decode liberally. */
4207
4208/* Three simple macros defining base-64. */
4209
4210/* Is c a base-64 character? */
4211
4212#define IS_BASE64(c) \
4213 (((c) >= 'A' && (c) <= 'Z') || \
4214 ((c) >= 'a' && (c) <= 'z') || \
4215 ((c) >= '0' && (c) <= '9') || \
4216 (c) == '+' || (c) == '/')
4217
4218/* given that c is a base-64 character, what is its base-64 value? */
4219
4220#define FROM_BASE64(c) \
4221 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4222 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4223 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4224 (c) == '+' ? 62 : 63)
4225
4226/* What is the base-64 character of the bottom 6 bits of n? */
4227
4228#define TO_BASE64(n) \
4229 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4230
4231/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4232 * decoded as itself. We are permissive on decoding; the only ASCII
4233 * byte not decoding to itself is the + which begins a base64
4234 * string. */
4235
4236#define DECODE_DIRECT(c) \
4237 ((c) <= 127 && (c) != '+')
4238
4239/* The UTF-7 encoder treats ASCII characters differently according to
4240 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4241 * the above). See RFC2152. This array identifies these different
4242 * sets:
4243 * 0 : "Set D"
4244 * alphanumeric and '(),-./:?
4245 * 1 : "Set O"
4246 * !"#$%&*;<=>@[]^_`{|}
4247 * 2 : "whitespace"
4248 * ht nl cr sp
4249 * 3 : special (must be base64 encoded)
4250 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4251 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004252
Tim Petersced69f82003-09-16 20:30:58 +00004253static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004254char utf7_category[128] = {
4255/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4256 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4257/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4258 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4259/* sp ! " # $ % & ' ( ) * + , - . / */
4260 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4261/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4262 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4263/* @ A B C D E F G H I J K L M N O */
4264 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4265/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4266 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4267/* ` a b c d e f g h i j k l m n o */
4268 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4269/* p q r s t u v w x y z { | } ~ del */
4270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004271};
4272
Antoine Pitrou244651a2009-05-04 18:56:13 +00004273/* ENCODE_DIRECT: this character should be encoded as itself. The
4274 * answer depends on whether we are encoding set O as itself, and also
4275 * on whether we are encoding whitespace as itself. RFC2152 makes it
4276 * clear that the answers to these questions vary between
4277 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004278
Antoine Pitrou244651a2009-05-04 18:56:13 +00004279#define ENCODE_DIRECT(c, directO, directWS) \
4280 ((c) < 128 && (c) > 0 && \
4281 ((utf7_category[(c)] == 0) || \
4282 (directWS && (utf7_category[(c)] == 2)) || \
4283 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004284
Alexander Belopolsky40018472011-02-26 01:02:56 +00004285PyObject *
4286PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004287 Py_ssize_t size,
4288 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4291}
4292
Antoine Pitrou244651a2009-05-04 18:56:13 +00004293/* The decoder. The only state we preserve is our read position,
4294 * i.e. how many characters we have consumed. So if we end in the
4295 * middle of a shift sequence we have to back off the read position
4296 * and the output to the beginning of the sequence, otherwise we lose
4297 * all the shift state (seen bits, number of bits seen, high
4298 * surrogate). */
4299
Alexander Belopolsky40018472011-02-26 01:02:56 +00004300PyObject *
4301PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004302 Py_ssize_t size,
4303 const char *errors,
4304 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004305{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004306 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004307 Py_ssize_t startinpos;
4308 Py_ssize_t endinpos;
4309 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004311 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004312 const char *errmsg = "";
4313 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004315 unsigned int base64bits = 0;
4316 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004317 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004318 PyObject *errorHandler = NULL;
4319 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 /* Start off assuming it's all ASCII. Widen later as necessary. */
4322 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004323 if (!unicode)
4324 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004325 if (size == 0) {
4326 if (consumed)
4327 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004328 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004329 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004331 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332 e = s + size;
4333
4334 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004335 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004336 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004337 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004338
Antoine Pitrou244651a2009-05-04 18:56:13 +00004339 if (inShift) { /* in a base-64 section */
4340 if (IS_BASE64(ch)) { /* consume a base-64 character */
4341 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4342 base64bits += 6;
4343 s++;
4344 if (base64bits >= 16) {
4345 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004346 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 base64bits -= 16;
4348 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4349 if (surrogate) {
4350 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004351 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4352 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4354 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004356 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004357 }
4358 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4360 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 }
4363 }
Victor Stinner551ac952011-11-29 22:58:13 +01004364 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 /* first surrogate */
4366 surrogate = outCh;
4367 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4370 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 }
4373 }
4374 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375 inShift = 0;
4376 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4379 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004380 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 if (base64bits > 0) { /* left-over bits */
4383 if (base64bits >= 6) {
4384 /* We've seen at least one base-64 character */
4385 errmsg = "partial character in shift sequence";
4386 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 else {
4389 /* Some bits remain; they should be zero */
4390 if (base64buffer != 0) {
4391 errmsg = "non-zero padding bits in shift sequence";
4392 goto utf7Error;
4393 }
4394 }
4395 }
4396 if (ch != '-') {
4397 /* '-' is absorbed; other terminating
4398 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4400 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 }
4403 }
4404 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 s++; /* consume '+' */
4407 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4410 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 }
4412 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004414 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004419 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4420 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 s++;
4422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
4432 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004436 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
4448 if (unicode_decode_call_errorhandler(
4449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004452 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004462 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004463 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 }
4465 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004468 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004469
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004470 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 goto onError;
4472
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 Py_XDECREF(errorHandler);
4474 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004475 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004476
Benjamin Peterson29060642009-01-31 22:14:21 +00004477 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004478 Py_XDECREF(errorHandler);
4479 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480 Py_DECREF(unicode);
4481 return NULL;
4482}
4483
4484
Alexander Belopolsky40018472011-02-26 01:02:56 +00004485PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004486_PyUnicode_EncodeUTF7(PyObject *str,
4487 int base64SetO,
4488 int base64WhiteSpace,
4489 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491 int kind;
4492 void *data;
4493 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004494 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004497 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 unsigned int base64bits = 0;
4499 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 char * out;
4501 char * start;
4502
Benjamin Petersonbac79492012-01-14 13:34:47 -05004503 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004504 return NULL;
4505 kind = PyUnicode_KIND(str);
4506 data = PyUnicode_DATA(str);
4507 len = PyUnicode_GET_LENGTH(str);
4508
4509 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004512 /* It might be possible to tighten this worst case */
4513 allocated = 8 * len;
4514 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004515 return PyErr_NoMemory();
4516
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518 if (v == NULL)
4519 return NULL;
4520
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004521 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004522 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004523 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 if (inShift) {
4526 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4527 /* shifting out */
4528 if (base64bits) { /* output remaining bits */
4529 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4530 base64buffer = 0;
4531 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 }
4533 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 /* Characters not in the BASE64 set implicitly unshift the sequence
4535 so no '-' is required, except if the character is itself a '-' */
4536 if (IS_BASE64(ch) || ch == '-') {
4537 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 *out++ = (char) ch;
4540 }
4541 else {
4542 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004543 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 else { /* not in a shift sequence */
4546 if (ch == '+') {
4547 *out++ = '+';
4548 *out++ = '-';
4549 }
4550 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4551 *out++ = (char) ch;
4552 }
4553 else {
4554 *out++ = '+';
4555 inShift = 1;
4556 goto encode_char;
4557 }
4558 }
4559 continue;
4560encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004562 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004563
Antoine Pitrou244651a2009-05-04 18:56:13 +00004564 /* code first surrogate */
4565 base64bits += 16;
4566 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4567 while (base64bits >= 6) {
4568 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4569 base64bits -= 6;
4570 }
4571 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004572 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 base64bits += 16;
4575 base64buffer = (base64buffer << 16) | ch;
4576 while (base64bits >= 6) {
4577 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4578 base64bits -= 6;
4579 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004580 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 if (base64bits)
4582 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4583 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004585 if (_PyBytes_Resize(&v, out - start) < 0)
4586 return NULL;
4587 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004589PyObject *
4590PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4591 Py_ssize_t size,
4592 int base64SetO,
4593 int base64WhiteSpace,
4594 const char *errors)
4595{
4596 PyObject *result;
4597 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4598 if (tmp == NULL)
4599 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004600 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601 base64WhiteSpace, errors);
4602 Py_DECREF(tmp);
4603 return result;
4604}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606#undef IS_BASE64
4607#undef FROM_BASE64
4608#undef TO_BASE64
4609#undef DECODE_DIRECT
4610#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612/* --- UTF-8 Codec -------------------------------------------------------- */
4613
Alexander Belopolsky40018472011-02-26 01:02:56 +00004614PyObject *
4615PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004616 Py_ssize_t size,
4617 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004618{
Walter Dörwald69652032004-09-07 20:24:22 +00004619 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4620}
4621
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004622#include "stringlib/asciilib.h"
4623#include "stringlib/codecs.h"
4624#include "stringlib/undef.h"
4625
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004626#include "stringlib/ucs1lib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
4630#include "stringlib/ucs2lib.h"
4631#include "stringlib/codecs.h"
4632#include "stringlib/undef.h"
4633
4634#include "stringlib/ucs4lib.h"
4635#include "stringlib/codecs.h"
4636#include "stringlib/undef.h"
4637
Antoine Pitrouab868312009-01-10 15:40:25 +00004638/* Mask to quickly check whether a C 'long' contains a
4639 non-ASCII, UTF8-encoded char. */
4640#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004641# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004642#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004643# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004644#else
4645# error C 'long' size should be either 4 or 8!
4646#endif
4647
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004648static Py_ssize_t
4649ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004650{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004652 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004653
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004655 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4656 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 /* Fast path, see in STRINGLIB(utf8_decode) for
4658 an explanation. */
4659 /* Help register allocation */
4660 register const char *_p = p;
4661 register Py_UCS1 * q = dest;
4662 while (_p < aligned_end) {
4663 unsigned long value = *(const unsigned long *) _p;
4664 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004665 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004666 *((unsigned long *)q) = value;
4667 _p += SIZEOF_LONG;
4668 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004669 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004670 p = _p;
4671 while (p < end) {
4672 if ((unsigned char)*p & 0x80)
4673 break;
4674 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004675 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004677 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678#endif
4679 while (p < end) {
4680 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4681 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004682 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004683 /* Help register allocation */
4684 register const char *_p = p;
4685 while (_p < aligned_end) {
4686 unsigned long value = *(unsigned long *) _p;
4687 if (value & ASCII_CHAR_MASK)
4688 break;
4689 _p += SIZEOF_LONG;
4690 }
4691 p = _p;
4692 if (_p == end)
4693 break;
4694 }
4695 if ((unsigned char)*p & 0x80)
4696 break;
4697 ++p;
4698 }
4699 memcpy(dest, start, p - start);
4700 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004701}
Antoine Pitrouab868312009-01-10 15:40:25 +00004702
Victor Stinner785938e2011-12-11 20:09:03 +01004703PyObject *
4704PyUnicode_DecodeUTF8Stateful(const char *s,
4705 Py_ssize_t size,
4706 const char *errors,
4707 Py_ssize_t *consumed)
4708{
Victor Stinner785938e2011-12-11 20:09:03 +01004709 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004710 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004711 const char *end = s + size;
4712 Py_ssize_t outpos;
4713
4714 Py_ssize_t startinpos;
4715 Py_ssize_t endinpos;
4716 const char *errmsg = "";
4717 PyObject *errorHandler = NULL;
4718 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004719
4720 if (size == 0) {
4721 if (consumed)
4722 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004723 Py_INCREF(unicode_empty);
4724 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004725 }
4726
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4728 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004729 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 *consumed = 1;
4731 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004732 }
4733
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004735 if (!unicode)
4736 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004737
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4739 s += outpos;
4740 while (s < end) {
4741 Py_UCS4 ch;
4742 int kind = PyUnicode_KIND(unicode);
4743 if (kind == PyUnicode_1BYTE_KIND) {
4744 if (PyUnicode_IS_ASCII(unicode))
4745 ch = asciilib_utf8_decode(&s, end,
4746 PyUnicode_1BYTE_DATA(unicode), &outpos);
4747 else
4748 ch = ucs1lib_utf8_decode(&s, end,
4749 PyUnicode_1BYTE_DATA(unicode), &outpos);
4750 } else if (kind == PyUnicode_2BYTE_KIND) {
4751 ch = ucs2lib_utf8_decode(&s, end,
4752 PyUnicode_2BYTE_DATA(unicode), &outpos);
4753 } else {
4754 assert(kind == PyUnicode_4BYTE_KIND);
4755 ch = ucs4lib_utf8_decode(&s, end,
4756 PyUnicode_4BYTE_DATA(unicode), &outpos);
4757 }
4758
4759 switch (ch) {
4760 case 0:
4761 if (s == end || consumed)
4762 goto End;
4763 errmsg = "unexpected end of data";
4764 startinpos = s - starts;
4765 endinpos = startinpos + 1;
4766 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4767 endinpos++;
4768 break;
4769 case 1:
4770 errmsg = "invalid start byte";
4771 startinpos = s - starts;
4772 endinpos = startinpos + 1;
4773 break;
4774 case 2:
4775 errmsg = "invalid continuation byte";
4776 startinpos = s - starts;
4777 endinpos = startinpos + 1;
4778 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4779 endinpos++;
4780 break;
4781 default:
4782 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4783 goto onError;
4784 continue;
4785 }
4786
4787 if (unicode_decode_call_errorhandler(
4788 errors, &errorHandler,
4789 "utf-8", errmsg,
4790 &starts, &end, &startinpos, &endinpos, &exc, &s,
4791 &unicode, &outpos))
4792 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004793 }
4794
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795End:
4796 if (unicode_resize(&unicode, outpos) < 0)
4797 goto onError;
4798
4799 if (consumed)
4800 *consumed = s - starts;
4801
4802 Py_XDECREF(errorHandler);
4803 Py_XDECREF(exc);
4804 assert(_PyUnicode_CheckConsistency(unicode, 1));
4805 return unicode;
4806
4807onError:
4808 Py_XDECREF(errorHandler);
4809 Py_XDECREF(exc);
4810 Py_XDECREF(unicode);
4811 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004812}
4813
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004814#ifdef __APPLE__
4815
4816/* Simplified UTF-8 decoder using surrogateescape error handler,
4817 used to decode the command line arguments on Mac OS X. */
4818
4819wchar_t*
4820_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4821{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823 wchar_t *unicode;
4824 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825
4826 /* Note: size will always be longer than the resulting Unicode
4827 character count */
4828 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4829 PyErr_NoMemory();
4830 return NULL;
4831 }
4832 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4833 if (!unicode)
4834 return NULL;
4835
4836 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004837 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004838 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004839 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004840 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004841#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004842 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004843#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004844 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004845#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004846 if (ch > 0xFF) {
4847#if SIZEOF_WCHAR_T == 4
4848 assert(0);
4849#else
4850 assert(Py_UNICODE_IS_SURROGATE(ch));
4851 /* compute and append the two surrogates: */
4852 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4853 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4854#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004855 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856 else {
4857 if (!ch && s == e)
4858 break;
4859 /* surrogateescape */
4860 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4861 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004862 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864 return unicode;
4865}
4866
4867#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004869/* Primary internal function which creates utf8 encoded bytes objects.
4870
4871 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004872 and allocate exactly as much space needed at the end. Else allocate the
4873 maximum possible needed (4 result bytes per Unicode character), and return
4874 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004875*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004876PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004877_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004878{
Victor Stinner6099a032011-12-18 14:22:26 +01004879 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880 void *data;
4881 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883 if (!PyUnicode_Check(unicode)) {
4884 PyErr_BadArgument();
4885 return NULL;
4886 }
4887
4888 if (PyUnicode_READY(unicode) == -1)
4889 return NULL;
4890
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004891 if (PyUnicode_UTF8(unicode))
4892 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4893 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004894
4895 kind = PyUnicode_KIND(unicode);
4896 data = PyUnicode_DATA(unicode);
4897 size = PyUnicode_GET_LENGTH(unicode);
4898
Benjamin Petersonead6b532011-12-20 17:23:42 -06004899 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004900 default:
4901 assert(0);
4902 case PyUnicode_1BYTE_KIND:
4903 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4904 assert(!PyUnicode_IS_ASCII(unicode));
4905 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4906 case PyUnicode_2BYTE_KIND:
4907 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4908 case PyUnicode_4BYTE_KIND:
4909 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004910 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004911}
4912
Alexander Belopolsky40018472011-02-26 01:02:56 +00004913PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004914PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4915 Py_ssize_t size,
4916 const char *errors)
4917{
4918 PyObject *v, *unicode;
4919
4920 unicode = PyUnicode_FromUnicode(s, size);
4921 if (unicode == NULL)
4922 return NULL;
4923 v = _PyUnicode_AsUTF8String(unicode, errors);
4924 Py_DECREF(unicode);
4925 return v;
4926}
4927
4928PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004929PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004931 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004932}
4933
Walter Dörwald41980ca2007-08-16 21:55:45 +00004934/* --- UTF-32 Codec ------------------------------------------------------- */
4935
4936PyObject *
4937PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004938 Py_ssize_t size,
4939 const char *errors,
4940 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004941{
4942 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4943}
4944
4945PyObject *
4946PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004947 Py_ssize_t size,
4948 const char *errors,
4949 int *byteorder,
4950 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004951{
4952 const char *starts = s;
4953 Py_ssize_t startinpos;
4954 Py_ssize_t endinpos;
4955 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004956 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004957 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004958 int bo = 0; /* assume native ordering by default */
4959 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960 /* Offsets from q for retrieving bytes in the right order. */
4961#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4962 int iorder[] = {0, 1, 2, 3};
4963#else
4964 int iorder[] = {3, 2, 1, 0};
4965#endif
4966 PyObject *errorHandler = NULL;
4967 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004968
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969 q = (unsigned char *)s;
4970 e = q + size;
4971
4972 if (byteorder)
4973 bo = *byteorder;
4974
4975 /* Check for BOM marks (U+FEFF) in the input and adjust current
4976 byte order setting accordingly. In native mode, the leading BOM
4977 mark is skipped, in all other modes, it is copied to the output
4978 stream as-is (giving a ZWNBSP character). */
4979 if (bo == 0) {
4980 if (size >= 4) {
4981 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004982 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004983#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004984 if (bom == 0x0000FEFF) {
4985 q += 4;
4986 bo = -1;
4987 }
4988 else if (bom == 0xFFFE0000) {
4989 q += 4;
4990 bo = 1;
4991 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004993 if (bom == 0x0000FEFF) {
4994 q += 4;
4995 bo = 1;
4996 }
4997 else if (bom == 0xFFFE0000) {
4998 q += 4;
4999 bo = -1;
5000 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005001#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005002 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005003 }
5004
5005 if (bo == -1) {
5006 /* force LE */
5007 iorder[0] = 0;
5008 iorder[1] = 1;
5009 iorder[2] = 2;
5010 iorder[3] = 3;
5011 }
5012 else if (bo == 1) {
5013 /* force BE */
5014 iorder[0] = 3;
5015 iorder[1] = 2;
5016 iorder[2] = 1;
5017 iorder[3] = 0;
5018 }
5019
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005020 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005021 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005022 if (!unicode)
5023 return NULL;
5024 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005025 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005026 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005027
Walter Dörwald41980ca2007-08-16 21:55:45 +00005028 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 Py_UCS4 ch;
5030 /* remaining bytes at the end? (size should be divisible by 4) */
5031 if (e-q<4) {
5032 if (consumed)
5033 break;
5034 errmsg = "truncated data";
5035 startinpos = ((const char *)q)-starts;
5036 endinpos = ((const char *)e)-starts;
5037 goto utf32Error;
5038 /* The remaining input chars are ignored if the callback
5039 chooses to skip the input */
5040 }
5041 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5042 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043
Benjamin Peterson29060642009-01-31 22:14:21 +00005044 if (ch >= 0x110000)
5045 {
5046 errmsg = "codepoint not in range(0x110000)";
5047 startinpos = ((const char *)q)-starts;
5048 endinpos = startinpos+4;
5049 goto utf32Error;
5050 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005051 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5052 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005053 q += 4;
5054 continue;
5055 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 if (unicode_decode_call_errorhandler(
5057 errors, &errorHandler,
5058 "utf32", errmsg,
5059 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005060 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005061 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062 }
5063
5064 if (byteorder)
5065 *byteorder = bo;
5066
5067 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005068 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005069
5070 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005071 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072 goto onError;
5073
5074 Py_XDECREF(errorHandler);
5075 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005076 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 Py_DECREF(unicode);
5080 Py_XDECREF(errorHandler);
5081 Py_XDECREF(exc);
5082 return NULL;
5083}
5084
5085PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005086_PyUnicode_EncodeUTF32(PyObject *str,
5087 const char *errors,
5088 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005090 int kind;
5091 void *data;
5092 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005093 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005095 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096 /* Offsets from p for storing byte pairs in the right order. */
5097#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5098 int iorder[] = {0, 1, 2, 3};
5099#else
5100 int iorder[] = {3, 2, 1, 0};
5101#endif
5102
Benjamin Peterson29060642009-01-31 22:14:21 +00005103#define STORECHAR(CH) \
5104 do { \
5105 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5106 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5107 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5108 p[iorder[0]] = (CH) & 0xff; \
5109 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005110 } while(0)
5111
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005112 if (!PyUnicode_Check(str)) {
5113 PyErr_BadArgument();
5114 return NULL;
5115 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005116 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005117 return NULL;
5118 kind = PyUnicode_KIND(str);
5119 data = PyUnicode_DATA(str);
5120 len = PyUnicode_GET_LENGTH(str);
5121
5122 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005123 bytesize = nsize * 4;
5124 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005125 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005126 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005127 if (v == NULL)
5128 return NULL;
5129
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005130 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005131 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005132 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005133 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005134 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005135
5136 if (byteorder == -1) {
5137 /* force LE */
5138 iorder[0] = 0;
5139 iorder[1] = 1;
5140 iorder[2] = 2;
5141 iorder[3] = 3;
5142 }
5143 else if (byteorder == 1) {
5144 /* force BE */
5145 iorder[0] = 3;
5146 iorder[1] = 2;
5147 iorder[2] = 1;
5148 iorder[3] = 0;
5149 }
5150
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005151 for (i = 0; i < len; i++)
5152 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005153
5154 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005155 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005156#undef STORECHAR
5157}
5158
Alexander Belopolsky40018472011-02-26 01:02:56 +00005159PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005160PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5161 Py_ssize_t size,
5162 const char *errors,
5163 int byteorder)
5164{
5165 PyObject *result;
5166 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5167 if (tmp == NULL)
5168 return NULL;
5169 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5170 Py_DECREF(tmp);
5171 return result;
5172}
5173
5174PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005175PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005176{
Victor Stinnerb960b342011-11-20 19:12:52 +01005177 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005178}
5179
Guido van Rossumd57fd912000-03-10 22:53:23 +00005180/* --- UTF-16 Codec ------------------------------------------------------- */
5181
Tim Peters772747b2001-08-09 22:21:55 +00005182PyObject *
5183PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005184 Py_ssize_t size,
5185 const char *errors,
5186 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005187{
Walter Dörwald69652032004-09-07 20:24:22 +00005188 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5189}
5190
5191PyObject *
5192PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005193 Py_ssize_t size,
5194 const char *errors,
5195 int *byteorder,
5196 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005197{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005198 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005199 Py_ssize_t startinpos;
5200 Py_ssize_t endinpos;
5201 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005202 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005203 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005204 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005205 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005206 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005207 PyObject *errorHandler = NULL;
5208 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209
Tim Peters772747b2001-08-09 22:21:55 +00005210 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005211 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
5213 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005214 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005216 /* Check for BOM marks (U+FEFF) in the input and adjust current
5217 byte order setting accordingly. In native mode, the leading BOM
5218 mark is skipped, in all other modes, it is copied to the output
5219 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005220 if (bo == 0 && size >= 2) {
5221 const Py_UCS4 bom = (q[1] << 8) | q[0];
5222 if (bom == 0xFEFF) {
5223 q += 2;
5224 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005225 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005226 else if (bom == 0xFFFE) {
5227 q += 2;
5228 bo = 1;
5229 }
5230 if (byteorder)
5231 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005232 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005233
Antoine Pitrou63065d72012-05-15 23:48:04 +02005234 if (q == e) {
5235 if (consumed)
5236 *consumed = size;
5237 Py_INCREF(unicode_empty);
5238 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005239 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005240
Antoine Pitrouab868312009-01-10 15:40:25 +00005241#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005242 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005243#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005244 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005245#endif
Tim Peters772747b2001-08-09 22:21:55 +00005246
Antoine Pitrou63065d72012-05-15 23:48:04 +02005247 /* Note: size will always be longer than the resulting Unicode
5248 character count */
5249 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5250 if (!unicode)
5251 return NULL;
5252
5253 outpos = 0;
5254 while (1) {
5255 Py_UCS4 ch = 0;
5256 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005257 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005258 if (kind == PyUnicode_1BYTE_KIND) {
5259 if (PyUnicode_IS_ASCII(unicode))
5260 ch = asciilib_utf16_decode(&q, e,
5261 PyUnicode_1BYTE_DATA(unicode), &outpos,
5262 native_ordering);
5263 else
5264 ch = ucs1lib_utf16_decode(&q, e,
5265 PyUnicode_1BYTE_DATA(unicode), &outpos,
5266 native_ordering);
5267 } else if (kind == PyUnicode_2BYTE_KIND) {
5268 ch = ucs2lib_utf16_decode(&q, e,
5269 PyUnicode_2BYTE_DATA(unicode), &outpos,
5270 native_ordering);
5271 } else {
5272 assert(kind == PyUnicode_4BYTE_KIND);
5273 ch = ucs4lib_utf16_decode(&q, e,
5274 PyUnicode_4BYTE_DATA(unicode), &outpos,
5275 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005276 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005277 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005278
Antoine Pitrou63065d72012-05-15 23:48:04 +02005279 switch (ch)
5280 {
5281 case 0:
5282 /* remaining byte at the end? (size should be even) */
5283 if (q == e || consumed)
5284 goto End;
5285 errmsg = "truncated data";
5286 startinpos = ((const char *)q) - starts;
5287 endinpos = ((const char *)e) - starts;
5288 break;
5289 /* The remaining input chars are ignored if the callback
5290 chooses to skip the input */
5291 case 1:
5292 errmsg = "unexpected end of data";
5293 startinpos = ((const char *)q) - 2 - starts;
5294 endinpos = ((const char *)e) - starts;
5295 break;
5296 case 2:
5297 errmsg = "illegal encoding";
5298 startinpos = ((const char *)q) - 2 - starts;
5299 endinpos = startinpos + 2;
5300 break;
5301 case 3:
5302 errmsg = "illegal UTF-16 surrogate";
5303 startinpos = ((const char *)q) - 4 - starts;
5304 endinpos = startinpos + 2;
5305 break;
5306 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005307 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5308 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 continue;
5310 }
5311
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005313 errors,
5314 &errorHandler,
5315 "utf16", errmsg,
5316 &starts,
5317 (const char **)&e,
5318 &startinpos,
5319 &endinpos,
5320 &exc,
5321 (const char **)&q,
5322 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005323 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005324 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005325 }
5326
Antoine Pitrou63065d72012-05-15 23:48:04 +02005327End:
Walter Dörwald69652032004-09-07 20:24:22 +00005328 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005330
Guido van Rossumd57fd912000-03-10 22:53:23 +00005331 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005332 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005333 goto onError;
5334
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005335 Py_XDECREF(errorHandler);
5336 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005337 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005338
Benjamin Peterson29060642009-01-31 22:14:21 +00005339 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005340 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005341 Py_XDECREF(errorHandler);
5342 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343 return NULL;
5344}
5345
Tim Peters772747b2001-08-09 22:21:55 +00005346PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347_PyUnicode_EncodeUTF16(PyObject *str,
5348 const char *errors,
5349 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005350{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005351 enum PyUnicode_Kind kind;
5352 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005353 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005354 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005355 unsigned short *out;
5356 Py_ssize_t bytesize;
5357 Py_ssize_t pairs;
5358#ifdef WORDS_BIGENDIAN
5359 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005360#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005361 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005362#endif
5363
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005364 if (!PyUnicode_Check(str)) {
5365 PyErr_BadArgument();
5366 return NULL;
5367 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005368 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005369 return NULL;
5370 kind = PyUnicode_KIND(str);
5371 data = PyUnicode_DATA(str);
5372 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005373
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005374 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005375 if (kind == PyUnicode_4BYTE_KIND) {
5376 const Py_UCS4 *in = (const Py_UCS4 *)data;
5377 const Py_UCS4 *end = in + len;
5378 while (in < end)
5379 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005380 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005381 }
5382 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005383 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005384 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005385 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005386 if (v == NULL)
5387 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005388
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005389 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005390 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005391 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005392 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005393 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005394 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005395 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005396
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005397 switch (kind) {
5398 case PyUnicode_1BYTE_KIND: {
5399 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5400 break;
Tim Peters772747b2001-08-09 22:21:55 +00005401 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005402 case PyUnicode_2BYTE_KIND: {
5403 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5404 break;
Tim Peters772747b2001-08-09 22:21:55 +00005405 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005406 case PyUnicode_4BYTE_KIND: {
5407 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5408 break;
5409 }
5410 default:
5411 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005412 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005413
5414 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005415 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416}
5417
Alexander Belopolsky40018472011-02-26 01:02:56 +00005418PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005419PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5420 Py_ssize_t size,
5421 const char *errors,
5422 int byteorder)
5423{
5424 PyObject *result;
5425 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5426 if (tmp == NULL)
5427 return NULL;
5428 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5429 Py_DECREF(tmp);
5430 return result;
5431}
5432
5433PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005434PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005435{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005436 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437}
5438
5439/* --- Unicode Escape Codec ----------------------------------------------- */
5440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005441/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5442 if all the escapes in the string make it still a valid ASCII string.
5443 Returns -1 if any escapes were found which cause the string to
5444 pop out of ASCII range. Otherwise returns the length of the
5445 required buffer to hold the string.
5446 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005447static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005448length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5449{
5450 const unsigned char *p = (const unsigned char *)s;
5451 const unsigned char *end = p + size;
5452 Py_ssize_t length = 0;
5453
5454 if (size < 0)
5455 return -1;
5456
5457 for (; p < end; ++p) {
5458 if (*p > 127) {
5459 /* Non-ASCII */
5460 return -1;
5461 }
5462 else if (*p != '\\') {
5463 /* Normal character */
5464 ++length;
5465 }
5466 else {
5467 /* Backslash-escape, check next char */
5468 ++p;
5469 /* Escape sequence reaches till end of string or
5470 non-ASCII follow-up. */
5471 if (p >= end || *p > 127)
5472 return -1;
5473 switch (*p) {
5474 case '\n':
5475 /* backslash + \n result in zero characters */
5476 break;
5477 case '\\': case '\'': case '\"':
5478 case 'b': case 'f': case 't':
5479 case 'n': case 'r': case 'v': case 'a':
5480 ++length;
5481 break;
5482 case '0': case '1': case '2': case '3':
5483 case '4': case '5': case '6': case '7':
5484 case 'x': case 'u': case 'U': case 'N':
5485 /* these do not guarantee ASCII characters */
5486 return -1;
5487 default:
5488 /* count the backslash + the other character */
5489 length += 2;
5490 }
5491 }
5492 }
5493 return length;
5494}
5495
Fredrik Lundh06d12682001-01-24 07:59:11 +00005496static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005497
Alexander Belopolsky40018472011-02-26 01:02:56 +00005498PyObject *
5499PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005500 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005501 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005502{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005503 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005504 Py_ssize_t startinpos;
5505 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005506 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005507 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005508 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005509 char* message;
5510 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005511 PyObject *errorHandler = NULL;
5512 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005513 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005514 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005515
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005516 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005517
5518 /* After length_of_escaped_ascii_string() there are two alternatives,
5519 either the string is pure ASCII with named escapes like \n, etc.
5520 and we determined it's exact size (common case)
5521 or it contains \x, \u, ... escape sequences. then we create a
5522 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005523 if (len >= 0) {
5524 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005525 if (!v)
5526 goto onError;
5527 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005528 }
5529 else {
5530 /* Escaped strings will always be longer than the resulting
5531 Unicode string, so we start with size here and then reduce the
5532 length after conversion to the true value.
5533 (but if the error callback returns a long replacement string
5534 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005535 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005536 if (!v)
5537 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005538 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005539 }
5540
Guido van Rossumd57fd912000-03-10 22:53:23 +00005541 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005542 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005543 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005544 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005545
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546 while (s < end) {
5547 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005548 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005549 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005550
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005551 /* The only case in which i == ascii_length is a backslash
5552 followed by a newline. */
5553 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005554
Guido van Rossumd57fd912000-03-10 22:53:23 +00005555 /* Non-escape characters are interpreted as Unicode ordinals */
5556 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005557 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5558 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559 continue;
5560 }
5561
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005562 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005563 /* \ - Escapes */
5564 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005565 c = *s++;
5566 if (s > end)
5567 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005568
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005569 /* The only case in which i == ascii_length is a backslash
5570 followed by a newline. */
5571 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005572
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005573 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574
Benjamin Peterson29060642009-01-31 22:14:21 +00005575 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005576#define WRITECHAR(ch) \
5577 do { \
5578 if (unicode_putchar(&v, &i, ch) < 0) \
5579 goto onError; \
5580 }while(0)
5581
Guido van Rossumd57fd912000-03-10 22:53:23 +00005582 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005583 case '\\': WRITECHAR('\\'); break;
5584 case '\'': WRITECHAR('\''); break;
5585 case '\"': WRITECHAR('\"'); break;
5586 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005587 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588 case 'f': WRITECHAR('\014'); break;
5589 case 't': WRITECHAR('\t'); break;
5590 case 'n': WRITECHAR('\n'); break;
5591 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005592 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005593 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005594 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005595 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005596
Benjamin Peterson29060642009-01-31 22:14:21 +00005597 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005598 case '0': case '1': case '2': case '3':
5599 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005600 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005601 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005602 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005603 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005604 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005605 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005606 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005607 break;
5608
Benjamin Peterson29060642009-01-31 22:14:21 +00005609 /* hex escapes */
5610 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005612 digits = 2;
5613 message = "truncated \\xXX escape";
5614 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005617 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005618 digits = 4;
5619 message = "truncated \\uXXXX escape";
5620 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621
Benjamin Peterson29060642009-01-31 22:14:21 +00005622 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005623 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005624 digits = 8;
5625 message = "truncated \\UXXXXXXXX escape";
5626 hexescape:
5627 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005628 if (s+digits>end) {
5629 endinpos = size;
5630 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005631 errors, &errorHandler,
5632 "unicodeescape", "end of string in escape sequence",
5633 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005634 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 goto onError;
5636 goto nextByte;
5637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005638 for (j = 0; j < digits; ++j) {
5639 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005640 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005641 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005642 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 errors, &errorHandler,
5644 "unicodeescape", message,
5645 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005646 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005647 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005648 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005649 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005650 }
5651 chr = (chr<<4) & ~0xF;
5652 if (c >= '0' && c <= '9')
5653 chr += c - '0';
5654 else if (c >= 'a' && c <= 'f')
5655 chr += 10 + c - 'a';
5656 else
5657 chr += 10 + c - 'A';
5658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005659 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005660 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005661 /* _decoding_error will have already written into the
5662 target buffer. */
5663 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005664 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005665 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005666 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005667 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005668 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005669 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005670 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 errors, &errorHandler,
5672 "unicodeescape", "illegal Unicode character",
5673 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005674 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005675 goto onError;
5676 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005677 break;
5678
Benjamin Peterson29060642009-01-31 22:14:21 +00005679 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005680 case 'N':
5681 message = "malformed \\N character escape";
5682 if (ucnhash_CAPI == NULL) {
5683 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005684 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5685 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005686 if (ucnhash_CAPI == NULL)
5687 goto ucnhashError;
5688 }
5689 if (*s == '{') {
5690 const char *start = s+1;
5691 /* look for the closing brace */
5692 while (*s != '}' && s < end)
5693 s++;
5694 if (s > start && s < end && *s == '}') {
5695 /* found a name. look it up in the unicode database */
5696 message = "unknown Unicode character name";
5697 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005698 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005699 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005700 goto store;
5701 }
5702 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005703 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005704 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005705 errors, &errorHandler,
5706 "unicodeescape", message,
5707 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005708 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005709 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005710 break;
5711
5712 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005713 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005714 message = "\\ at end of string";
5715 s--;
5716 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005717 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 errors, &errorHandler,
5719 "unicodeescape", message,
5720 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005721 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005722 goto onError;
5723 }
5724 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005725 WRITECHAR('\\');
5726 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005727 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005728 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005731 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005733#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005734
Victor Stinner16e6a802011-12-12 13:24:15 +01005735 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005736 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005737 Py_XDECREF(errorHandler);
5738 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005739 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005742 PyErr_SetString(
5743 PyExc_UnicodeError,
5744 "\\N escapes not supported (can't load unicodedata module)"
5745 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005746 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 Py_XDECREF(errorHandler);
5748 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005749 return NULL;
5750
Benjamin Peterson29060642009-01-31 22:14:21 +00005751 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005753 Py_XDECREF(errorHandler);
5754 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 return NULL;
5756}
5757
5758/* Return a Unicode-Escape string version of the Unicode object.
5759
5760 If quotes is true, the string is enclosed in u"" or u'' quotes as
5761 appropriate.
5762
5763*/
5764
Alexander Belopolsky40018472011-02-26 01:02:56 +00005765PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005766PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005768 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005769 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005770 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005771 int kind;
5772 void *data;
5773 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005774
Ezio Melottie7f90372012-10-05 03:33:31 +03005775 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005776 escape.
5777
Ezio Melottie7f90372012-10-05 03:33:31 +03005778 For UCS1 strings it's '\xxx', 4 bytes per source character.
5779 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5780 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005781 */
5782
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005783 if (!PyUnicode_Check(unicode)) {
5784 PyErr_BadArgument();
5785 return NULL;
5786 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005787 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005788 return NULL;
5789 len = PyUnicode_GET_LENGTH(unicode);
5790 kind = PyUnicode_KIND(unicode);
5791 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005792 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005793 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5794 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5795 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5796 }
5797
5798 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005799 return PyBytes_FromStringAndSize(NULL, 0);
5800
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005801 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005802 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005803
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005804 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005806 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005807 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005808 if (repr == NULL)
5809 return NULL;
5810
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005811 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005812
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005813 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005814 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005815
Walter Dörwald79e913e2007-05-12 11:08:06 +00005816 /* Escape backslashes */
5817 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818 *p++ = '\\';
5819 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005820 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005821 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005822
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005823 /* Map 21-bit characters to '\U00xxxxxx' */
5824 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005825 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005826 *p++ = '\\';
5827 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005828 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5829 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5830 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5831 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5832 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5833 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5834 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5835 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005837 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005838
Guido van Rossumd57fd912000-03-10 22:53:23 +00005839 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005840 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005841 *p++ = '\\';
5842 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005843 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5844 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5845 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5846 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005847 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005848
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005849 /* Map special whitespace to '\t', \n', '\r' */
5850 else if (ch == '\t') {
5851 *p++ = '\\';
5852 *p++ = 't';
5853 }
5854 else if (ch == '\n') {
5855 *p++ = '\\';
5856 *p++ = 'n';
5857 }
5858 else if (ch == '\r') {
5859 *p++ = '\\';
5860 *p++ = 'r';
5861 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005862
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005863 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005864 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005866 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005867 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5868 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005869 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005870
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871 /* Copy everything else as-is */
5872 else
5873 *p++ = (char) ch;
5874 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005876 assert(p - PyBytes_AS_STRING(repr) > 0);
5877 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5878 return NULL;
5879 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880}
5881
Alexander Belopolsky40018472011-02-26 01:02:56 +00005882PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005883PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5884 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886 PyObject *result;
5887 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5888 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005890 result = PyUnicode_AsUnicodeEscapeString(tmp);
5891 Py_DECREF(tmp);
5892 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893}
5894
5895/* --- Raw Unicode Escape Codec ------------------------------------------- */
5896
Alexander Belopolsky40018472011-02-26 01:02:56 +00005897PyObject *
5898PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005899 Py_ssize_t size,
5900 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005902 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005903 Py_ssize_t startinpos;
5904 Py_ssize_t endinpos;
5905 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005906 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907 const char *end;
5908 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005909 PyObject *errorHandler = NULL;
5910 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005911
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 /* Escaped strings will always be longer than the resulting
5913 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005914 length after conversion to the true value. (But decoding error
5915 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005916 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005918 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005920 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005921 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 end = s + size;
5923 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005924 unsigned char c;
5925 Py_UCS4 x;
5926 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005927 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 /* Non-escape characters are interpreted as Unicode ordinals */
5930 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005931 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5932 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005933 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005934 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 startinpos = s-starts;
5936
5937 /* \u-escapes are only interpreted iff the number of leading
5938 backslashes if odd */
5939 bs = s;
5940 for (;s < end;) {
5941 if (*s != '\\')
5942 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005943 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5944 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005945 }
5946 if (((s - bs) & 1) == 0 ||
5947 s >= end ||
5948 (*s != 'u' && *s != 'U')) {
5949 continue;
5950 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005951 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 count = *s=='u' ? 4 : 8;
5953 s++;
5954
5955 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 for (x = 0, i = 0; i < count; ++i, ++s) {
5957 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005958 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 endinpos = s-starts;
5960 if (unicode_decode_call_errorhandler(
5961 errors, &errorHandler,
5962 "rawunicodeescape", "truncated \\uXXXX",
5963 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005964 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 goto onError;
5966 goto nextByte;
5967 }
5968 x = (x<<4) & ~0xF;
5969 if (c >= '0' && c <= '9')
5970 x += c - '0';
5971 else if (c >= 'a' && c <= 'f')
5972 x += 10 + c - 'a';
5973 else
5974 x += 10 + c - 'A';
5975 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005976 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005977 if (unicode_putchar(&v, &outpos, x) < 0)
5978 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005979 } else {
5980 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005981 if (unicode_decode_call_errorhandler(
5982 errors, &errorHandler,
5983 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005984 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005985 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005987 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 nextByte:
5989 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005991 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005992 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005993 Py_XDECREF(errorHandler);
5994 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005995 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00005996
Benjamin Peterson29060642009-01-31 22:14:21 +00005997 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005999 Py_XDECREF(errorHandler);
6000 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001 return NULL;
6002}
6003
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006004
Alexander Belopolsky40018472011-02-26 01:02:56 +00006005PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006006PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006008 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009 char *p;
6010 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006011 Py_ssize_t expandsize, pos;
6012 int kind;
6013 void *data;
6014 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006016 if (!PyUnicode_Check(unicode)) {
6017 PyErr_BadArgument();
6018 return NULL;
6019 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006020 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006021 return NULL;
6022 kind = PyUnicode_KIND(unicode);
6023 data = PyUnicode_DATA(unicode);
6024 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006025 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6026 bytes, and 1 byte characters 4. */
6027 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006028
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006029 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006030 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006031
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006032 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 if (repr == NULL)
6034 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006035 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006036 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006038 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006039 for (pos = 0; pos < len; pos++) {
6040 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006041 /* Map 32-bit characters to '\Uxxxxxxxx' */
6042 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006043 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006044 *p++ = '\\';
6045 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006046 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6047 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6048 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6049 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6050 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6051 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6052 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6053 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006054 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006056 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 *p++ = '\\';
6058 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006059 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6060 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6061 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6062 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 /* Copy everything else as-is */
6065 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066 *p++ = (char) ch;
6067 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006068
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006069 assert(p > q);
6070 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006071 return NULL;
6072 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073}
6074
Alexander Belopolsky40018472011-02-26 01:02:56 +00006075PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006076PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6077 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006079 PyObject *result;
6080 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6081 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006082 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006083 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6084 Py_DECREF(tmp);
6085 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086}
6087
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006088/* --- Unicode Internal Codec ------------------------------------------- */
6089
Alexander Belopolsky40018472011-02-26 01:02:56 +00006090PyObject *
6091_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006092 Py_ssize_t size,
6093 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006094{
6095 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006096 Py_ssize_t startinpos;
6097 Py_ssize_t endinpos;
6098 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006099 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006100 const char *end;
6101 const char *reason;
6102 PyObject *errorHandler = NULL;
6103 PyObject *exc = NULL;
6104
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006105 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006106 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006107 1))
6108 return NULL;
6109
Thomas Wouters89f507f2006-12-13 04:49:30 +00006110 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006111 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006112 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006113 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006114 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006115 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006116 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006117 end = s + size;
6118
6119 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006120 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006121 Py_UCS4 ch;
6122 /* We copy the raw representation one byte at a time because the
6123 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006124 ((char *) &uch)[0] = s[0];
6125 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006126#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006127 ((char *) &uch)[2] = s[2];
6128 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006129#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006130 ch = uch;
6131
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006132 /* We have to sanity check the raw data, otherwise doom looms for
6133 some malformed UCS-4 data. */
6134 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006135#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006136 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006137#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006138 end-s < Py_UNICODE_SIZE
6139 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006141 startinpos = s - starts;
6142 if (end-s < Py_UNICODE_SIZE) {
6143 endinpos = end-starts;
6144 reason = "truncated input";
6145 }
6146 else {
6147 endinpos = s - starts + Py_UNICODE_SIZE;
6148 reason = "illegal code point (> 0x10FFFF)";
6149 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006150 if (unicode_decode_call_errorhandler(
6151 errors, &errorHandler,
6152 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006153 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006154 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006155 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006156 continue;
6157 }
6158
6159 s += Py_UNICODE_SIZE;
6160#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006161 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006162 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006163 Py_UNICODE uch2;
6164 ((char *) &uch2)[0] = s[0];
6165 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006166 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006167 {
Victor Stinner551ac952011-11-29 22:58:13 +01006168 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006169 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006170 }
6171 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006172#endif
6173
6174 if (unicode_putchar(&v, &outpos, ch) < 0)
6175 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006176 }
6177
Victor Stinner16e6a802011-12-12 13:24:15 +01006178 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006179 goto onError;
6180 Py_XDECREF(errorHandler);
6181 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006182 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006183
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006185 Py_XDECREF(v);
6186 Py_XDECREF(errorHandler);
6187 Py_XDECREF(exc);
6188 return NULL;
6189}
6190
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191/* --- Latin-1 Codec ------------------------------------------------------ */
6192
Alexander Belopolsky40018472011-02-26 01:02:56 +00006193PyObject *
6194PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006195 Py_ssize_t size,
6196 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006199 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200}
6201
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006202/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006203static void
6204make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006205 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006206 PyObject *unicode,
6207 Py_ssize_t startpos, Py_ssize_t endpos,
6208 const char *reason)
6209{
6210 if (*exceptionObject == NULL) {
6211 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006212 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006213 encoding, unicode, startpos, endpos, reason);
6214 }
6215 else {
6216 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6217 goto onError;
6218 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6219 goto onError;
6220 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6221 goto onError;
6222 return;
6223 onError:
6224 Py_DECREF(*exceptionObject);
6225 *exceptionObject = NULL;
6226 }
6227}
6228
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006229/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006230static void
6231raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006232 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006233 PyObject *unicode,
6234 Py_ssize_t startpos, Py_ssize_t endpos,
6235 const char *reason)
6236{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006237 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006238 encoding, unicode, startpos, endpos, reason);
6239 if (*exceptionObject != NULL)
6240 PyCodec_StrictErrors(*exceptionObject);
6241}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006242
6243/* error handling callback helper:
6244 build arguments, call the callback and check the arguments,
6245 put the result into newpos and return the replacement string, which
6246 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006247static PyObject *
6248unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006249 PyObject **errorHandler,
6250 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006251 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006252 Py_ssize_t startpos, Py_ssize_t endpos,
6253 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006254{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006255 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006256 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006257 PyObject *restuple;
6258 PyObject *resunicode;
6259
6260 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006261 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006262 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006264 }
6265
Benjamin Petersonbac79492012-01-14 13:34:47 -05006266 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006267 return NULL;
6268 len = PyUnicode_GET_LENGTH(unicode);
6269
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006270 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006271 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006272 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006274
6275 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006277 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006279 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006280 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 Py_DECREF(restuple);
6282 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006283 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006284 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 &resunicode, newpos)) {
6286 Py_DECREF(restuple);
6287 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006289 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6290 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6291 Py_DECREF(restuple);
6292 return NULL;
6293 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006294 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006295 *newpos = len + *newpos;
6296 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6298 Py_DECREF(restuple);
6299 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006300 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006301 Py_INCREF(resunicode);
6302 Py_DECREF(restuple);
6303 return resunicode;
6304}
6305
Alexander Belopolsky40018472011-02-26 01:02:56 +00006306static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006307unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006308 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006309 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006310{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006311 /* input state */
6312 Py_ssize_t pos=0, size;
6313 int kind;
6314 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006315 /* output object */
6316 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006317 /* pointer into the output */
6318 char *str;
6319 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006320 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006321 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6322 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006323 PyObject *errorHandler = NULL;
6324 PyObject *exc = NULL;
6325 /* the following variable is used for caching string comparisons
6326 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6327 int known_errorHandler = -1;
6328
Benjamin Petersonbac79492012-01-14 13:34:47 -05006329 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006330 return NULL;
6331 size = PyUnicode_GET_LENGTH(unicode);
6332 kind = PyUnicode_KIND(unicode);
6333 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006334 /* allocate enough for a simple encoding without
6335 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006336 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006337 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006338 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006339 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006340 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006341 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006342 ressize = size;
6343
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006344 while (pos < size) {
6345 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006346
Benjamin Peterson29060642009-01-31 22:14:21 +00006347 /* can we encode this? */
6348 if (c<limit) {
6349 /* no overflow check, because we know that the space is enough */
6350 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006351 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006352 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006353 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 Py_ssize_t requiredsize;
6355 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006356 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006358 Py_ssize_t collstart = pos;
6359 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 ++collend;
6363 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6364 if (known_errorHandler==-1) {
6365 if ((errors==NULL) || (!strcmp(errors, "strict")))
6366 known_errorHandler = 1;
6367 else if (!strcmp(errors, "replace"))
6368 known_errorHandler = 2;
6369 else if (!strcmp(errors, "ignore"))
6370 known_errorHandler = 3;
6371 else if (!strcmp(errors, "xmlcharrefreplace"))
6372 known_errorHandler = 4;
6373 else
6374 known_errorHandler = 0;
6375 }
6376 switch (known_errorHandler) {
6377 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006378 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 goto onError;
6380 case 2: /* replace */
6381 while (collstart++<collend)
6382 *str++ = '?'; /* fall through */
6383 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006384 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006385 break;
6386 case 4: /* xmlcharrefreplace */
6387 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006388 /* determine replacement size */
6389 for (i = collstart, repsize = 0; i < collend; ++i) {
6390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6391 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006393 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006394 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006397 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006398 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006399 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006401 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006403 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006404 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006406 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006408 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 if (requiredsize > ressize) {
6410 if (requiredsize<2*ressize)
6411 requiredsize = 2*ressize;
6412 if (_PyBytes_Resize(&res, requiredsize))
6413 goto onError;
6414 str = PyBytes_AS_STRING(res) + respos;
6415 ressize = requiredsize;
6416 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006417 /* generate replacement */
6418 for (i = collstart; i < collend; ++i) {
6419 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006421 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 break;
6423 default:
6424 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006425 encoding, reason, unicode, &exc,
6426 collstart, collend, &newpos);
6427 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006428 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006430 if (PyBytes_Check(repunicode)) {
6431 /* Directly copy bytes result to output. */
6432 repsize = PyBytes_Size(repunicode);
6433 if (repsize > 1) {
6434 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006435 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006436 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6437 Py_DECREF(repunicode);
6438 goto onError;
6439 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006440 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006441 ressize += repsize-1;
6442 }
6443 memcpy(str, PyBytes_AsString(repunicode), repsize);
6444 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006445 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006446 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006447 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006448 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006449 /* need more space? (at least enough for what we
6450 have+the replacement+the rest of the string, so
6451 we won't have to check space for encodable characters) */
6452 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006453 repsize = PyUnicode_GET_LENGTH(repunicode);
6454 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 if (requiredsize > ressize) {
6456 if (requiredsize<2*ressize)
6457 requiredsize = 2*ressize;
6458 if (_PyBytes_Resize(&res, requiredsize)) {
6459 Py_DECREF(repunicode);
6460 goto onError;
6461 }
6462 str = PyBytes_AS_STRING(res) + respos;
6463 ressize = requiredsize;
6464 }
6465 /* check if there is anything unencodable in the replacement
6466 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006467 for (i = 0; repsize-->0; ++i, ++str) {
6468 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006470 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006471 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 Py_DECREF(repunicode);
6473 goto onError;
6474 }
6475 *str = (char)c;
6476 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006477 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006478 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006479 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006480 }
6481 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006482 /* Resize if we allocated to much */
6483 size = str - PyBytes_AS_STRING(res);
6484 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006485 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006486 if (_PyBytes_Resize(&res, size) < 0)
6487 goto onError;
6488 }
6489
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490 Py_XDECREF(errorHandler);
6491 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006492 return res;
6493
6494 onError:
6495 Py_XDECREF(res);
6496 Py_XDECREF(errorHandler);
6497 Py_XDECREF(exc);
6498 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006499}
6500
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006502PyObject *
6503PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006504 Py_ssize_t size,
6505 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006506{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507 PyObject *result;
6508 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6509 if (unicode == NULL)
6510 return NULL;
6511 result = unicode_encode_ucs1(unicode, errors, 256);
6512 Py_DECREF(unicode);
6513 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006514}
6515
Alexander Belopolsky40018472011-02-26 01:02:56 +00006516PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006517_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518{
6519 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 PyErr_BadArgument();
6521 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006523 if (PyUnicode_READY(unicode) == -1)
6524 return NULL;
6525 /* Fast path: if it is a one-byte string, construct
6526 bytes object directly. */
6527 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6528 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6529 PyUnicode_GET_LENGTH(unicode));
6530 /* Non-Latin-1 characters present. Defer to above function to
6531 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006532 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006533}
6534
6535PyObject*
6536PyUnicode_AsLatin1String(PyObject *unicode)
6537{
6538 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006539}
6540
6541/* --- 7-bit ASCII Codec -------------------------------------------------- */
6542
Alexander Belopolsky40018472011-02-26 01:02:56 +00006543PyObject *
6544PyUnicode_DecodeASCII(const char *s,
6545 Py_ssize_t size,
6546 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006547{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006548 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006549 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006550 int kind;
6551 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006552 Py_ssize_t startinpos;
6553 Py_ssize_t endinpos;
6554 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006555 const char *e;
6556 PyObject *errorHandler = NULL;
6557 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006558
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006559 if (size == 0) {
6560 Py_INCREF(unicode_empty);
6561 return unicode_empty;
6562 }
6563
Guido van Rossumd57fd912000-03-10 22:53:23 +00006564 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006565 if (size == 1 && (unsigned char)s[0] < 128)
6566 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006567
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006568 unicode = PyUnicode_New(size, 127);
6569 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006571
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006572 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006573 data = PyUnicode_1BYTE_DATA(unicode);
6574 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6575 if (outpos == size)
6576 return unicode;
6577
6578 s += outpos;
6579 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006580 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 register unsigned char c = (unsigned char)*s;
6582 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006583 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 ++s;
6585 }
6586 else {
6587 startinpos = s-starts;
6588 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 if (unicode_decode_call_errorhandler(
6590 errors, &errorHandler,
6591 "ascii", "ordinal not in range(128)",
6592 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006593 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006595 kind = PyUnicode_KIND(unicode);
6596 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006598 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006599 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006600 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 Py_XDECREF(errorHandler);
6602 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006603 assert(_PyUnicode_CheckConsistency(unicode, 1));
6604 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006605
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006607 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006608 Py_XDECREF(errorHandler);
6609 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006610 return NULL;
6611}
6612
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006614PyObject *
6615PyUnicode_EncodeASCII(const Py_UNICODE *p,
6616 Py_ssize_t size,
6617 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006618{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006619 PyObject *result;
6620 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6621 if (unicode == NULL)
6622 return NULL;
6623 result = unicode_encode_ucs1(unicode, errors, 128);
6624 Py_DECREF(unicode);
6625 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006626}
6627
Alexander Belopolsky40018472011-02-26 01:02:56 +00006628PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006629_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006630{
6631 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006632 PyErr_BadArgument();
6633 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006635 if (PyUnicode_READY(unicode) == -1)
6636 return NULL;
6637 /* Fast path: if it is an ASCII-only string, construct bytes object
6638 directly. Else defer to above function to raise the exception. */
6639 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6640 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6641 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006642 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006643}
6644
6645PyObject *
6646PyUnicode_AsASCIIString(PyObject *unicode)
6647{
6648 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006649}
6650
Victor Stinner99b95382011-07-04 14:23:54 +02006651#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006652
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006653/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006654
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006655#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006656#define NEED_RETRY
6657#endif
6658
Victor Stinner3a50e702011-10-18 21:21:00 +02006659#ifndef WC_ERR_INVALID_CHARS
6660# define WC_ERR_INVALID_CHARS 0x0080
6661#endif
6662
6663static char*
6664code_page_name(UINT code_page, PyObject **obj)
6665{
6666 *obj = NULL;
6667 if (code_page == CP_ACP)
6668 return "mbcs";
6669 if (code_page == CP_UTF7)
6670 return "CP_UTF7";
6671 if (code_page == CP_UTF8)
6672 return "CP_UTF8";
6673
6674 *obj = PyBytes_FromFormat("cp%u", code_page);
6675 if (*obj == NULL)
6676 return NULL;
6677 return PyBytes_AS_STRING(*obj);
6678}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006679
Alexander Belopolsky40018472011-02-26 01:02:56 +00006680static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006681is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006682{
6683 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006684 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006685
Victor Stinner3a50e702011-10-18 21:21:00 +02006686 if (!IsDBCSLeadByteEx(code_page, *curr))
6687 return 0;
6688
6689 prev = CharPrevExA(code_page, s, curr, 0);
6690 if (prev == curr)
6691 return 1;
6692 /* FIXME: This code is limited to "true" double-byte encodings,
6693 as it assumes an incomplete character consists of a single
6694 byte. */
6695 if (curr - prev == 2)
6696 return 1;
6697 if (!IsDBCSLeadByteEx(code_page, *prev))
6698 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006699 return 0;
6700}
6701
Victor Stinner3a50e702011-10-18 21:21:00 +02006702static DWORD
6703decode_code_page_flags(UINT code_page)
6704{
6705 if (code_page == CP_UTF7) {
6706 /* The CP_UTF7 decoder only supports flags=0 */
6707 return 0;
6708 }
6709 else
6710 return MB_ERR_INVALID_CHARS;
6711}
6712
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006713/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006714 * Decode a byte string from a Windows code page into unicode object in strict
6715 * mode.
6716 *
6717 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6718 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006719 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006720static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006721decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006722 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006723 const char *in,
6724 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006725{
Victor Stinner3a50e702011-10-18 21:21:00 +02006726 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006727 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006728 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006729
6730 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006731 assert(insize > 0);
6732 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6733 if (outsize <= 0)
6734 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006735
6736 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006738 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006739 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 if (*v == NULL)
6741 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006742 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006743 }
6744 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006746 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006747 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006749 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006750 }
6751
6752 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006753 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6754 if (outsize <= 0)
6755 goto error;
6756 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006757
Victor Stinner3a50e702011-10-18 21:21:00 +02006758error:
6759 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6760 return -2;
6761 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006762 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006763}
6764
Victor Stinner3a50e702011-10-18 21:21:00 +02006765/*
6766 * Decode a byte string from a code page into unicode object with an error
6767 * handler.
6768 *
6769 * Returns consumed size if succeed, or raise a WindowsError or
6770 * UnicodeDecodeError exception and returns -1 on error.
6771 */
6772static int
6773decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006774 PyObject **v,
6775 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006776 const char *errors)
6777{
6778 const char *startin = in;
6779 const char *endin = in + size;
6780 const DWORD flags = decode_code_page_flags(code_page);
6781 /* Ideally, we should get reason from FormatMessage. This is the Windows
6782 2000 English version of the message. */
6783 const char *reason = "No mapping for the Unicode character exists "
6784 "in the target code page.";
6785 /* each step cannot decode more than 1 character, but a character can be
6786 represented as a surrogate pair */
6787 wchar_t buffer[2], *startout, *out;
6788 int insize, outsize;
6789 PyObject *errorHandler = NULL;
6790 PyObject *exc = NULL;
6791 PyObject *encoding_obj = NULL;
6792 char *encoding;
6793 DWORD err;
6794 int ret = -1;
6795
6796 assert(size > 0);
6797
6798 encoding = code_page_name(code_page, &encoding_obj);
6799 if (encoding == NULL)
6800 return -1;
6801
6802 if (errors == NULL || strcmp(errors, "strict") == 0) {
6803 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6804 UnicodeDecodeError. */
6805 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6806 if (exc != NULL) {
6807 PyCodec_StrictErrors(exc);
6808 Py_CLEAR(exc);
6809 }
6810 goto error;
6811 }
6812
6813 if (*v == NULL) {
6814 /* Create unicode object */
6815 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6816 PyErr_NoMemory();
6817 goto error;
6818 }
Victor Stinnerab595942011-12-17 04:59:06 +01006819 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006820 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006821 if (*v == NULL)
6822 goto error;
6823 startout = PyUnicode_AS_UNICODE(*v);
6824 }
6825 else {
6826 /* Extend unicode object */
6827 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6828 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6829 PyErr_NoMemory();
6830 goto error;
6831 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006832 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006833 goto error;
6834 startout = PyUnicode_AS_UNICODE(*v) + n;
6835 }
6836
6837 /* Decode the byte string character per character */
6838 out = startout;
6839 while (in < endin)
6840 {
6841 /* Decode a character */
6842 insize = 1;
6843 do
6844 {
6845 outsize = MultiByteToWideChar(code_page, flags,
6846 in, insize,
6847 buffer, Py_ARRAY_LENGTH(buffer));
6848 if (outsize > 0)
6849 break;
6850 err = GetLastError();
6851 if (err != ERROR_NO_UNICODE_TRANSLATION
6852 && err != ERROR_INSUFFICIENT_BUFFER)
6853 {
6854 PyErr_SetFromWindowsErr(0);
6855 goto error;
6856 }
6857 insize++;
6858 }
6859 /* 4=maximum length of a UTF-8 sequence */
6860 while (insize <= 4 && (in + insize) <= endin);
6861
6862 if (outsize <= 0) {
6863 Py_ssize_t startinpos, endinpos, outpos;
6864
6865 startinpos = in - startin;
6866 endinpos = startinpos + 1;
6867 outpos = out - PyUnicode_AS_UNICODE(*v);
6868 if (unicode_decode_call_errorhandler(
6869 errors, &errorHandler,
6870 encoding, reason,
6871 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006872 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006873 {
6874 goto error;
6875 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006876 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006877 }
6878 else {
6879 in += insize;
6880 memcpy(out, buffer, outsize * sizeof(wchar_t));
6881 out += outsize;
6882 }
6883 }
6884
6885 /* write a NUL character at the end */
6886 *out = 0;
6887
6888 /* Extend unicode object */
6889 outsize = out - startout;
6890 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006891 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006892 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006893 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006894
6895error:
6896 Py_XDECREF(encoding_obj);
6897 Py_XDECREF(errorHandler);
6898 Py_XDECREF(exc);
6899 return ret;
6900}
6901
Victor Stinner3a50e702011-10-18 21:21:00 +02006902static PyObject *
6903decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006904 const char *s, Py_ssize_t size,
6905 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006906{
Victor Stinner76a31a62011-11-04 00:05:13 +01006907 PyObject *v = NULL;
6908 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909
Victor Stinner3a50e702011-10-18 21:21:00 +02006910 if (code_page < 0) {
6911 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6912 return NULL;
6913 }
6914
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006915 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006917
Victor Stinner76a31a62011-11-04 00:05:13 +01006918 do
6919 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006920#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006921 if (size > INT_MAX) {
6922 chunk_size = INT_MAX;
6923 final = 0;
6924 done = 0;
6925 }
6926 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006927#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006928 {
6929 chunk_size = (int)size;
6930 final = (consumed == NULL);
6931 done = 1;
6932 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006933
Victor Stinner76a31a62011-11-04 00:05:13 +01006934 /* Skip trailing lead-byte unless 'final' is set */
6935 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6936 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937
Victor Stinner76a31a62011-11-04 00:05:13 +01006938 if (chunk_size == 0 && done) {
6939 if (v != NULL)
6940 break;
6941 Py_INCREF(unicode_empty);
6942 return unicode_empty;
6943 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006944
Victor Stinner76a31a62011-11-04 00:05:13 +01006945
6946 converted = decode_code_page_strict(code_page, &v,
6947 s, chunk_size);
6948 if (converted == -2)
6949 converted = decode_code_page_errors(code_page, &v,
6950 s, chunk_size,
6951 errors);
6952 assert(converted != 0);
6953
6954 if (converted < 0) {
6955 Py_XDECREF(v);
6956 return NULL;
6957 }
6958
6959 if (consumed)
6960 *consumed += converted;
6961
6962 s += converted;
6963 size -= converted;
6964 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006965
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006966 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006967}
6968
Alexander Belopolsky40018472011-02-26 01:02:56 +00006969PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006970PyUnicode_DecodeCodePageStateful(int code_page,
6971 const char *s,
6972 Py_ssize_t size,
6973 const char *errors,
6974 Py_ssize_t *consumed)
6975{
6976 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6977}
6978
6979PyObject *
6980PyUnicode_DecodeMBCSStateful(const char *s,
6981 Py_ssize_t size,
6982 const char *errors,
6983 Py_ssize_t *consumed)
6984{
6985 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6986}
6987
6988PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006989PyUnicode_DecodeMBCS(const char *s,
6990 Py_ssize_t size,
6991 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006992{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006993 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6994}
6995
Victor Stinner3a50e702011-10-18 21:21:00 +02006996static DWORD
6997encode_code_page_flags(UINT code_page, const char *errors)
6998{
6999 if (code_page == CP_UTF8) {
7000 if (winver.dwMajorVersion >= 6)
7001 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7002 and later */
7003 return WC_ERR_INVALID_CHARS;
7004 else
7005 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7006 return 0;
7007 }
7008 else if (code_page == CP_UTF7) {
7009 /* CP_UTF7 only supports flags=0 */
7010 return 0;
7011 }
7012 else {
7013 if (errors != NULL && strcmp(errors, "replace") == 0)
7014 return 0;
7015 else
7016 return WC_NO_BEST_FIT_CHARS;
7017 }
7018}
7019
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007021 * Encode a Unicode string to a Windows code page into a byte string in strict
7022 * mode.
7023 *
7024 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7025 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007026 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007027static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007028encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007029 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031{
Victor Stinner554f3f02010-06-16 23:33:54 +00007032 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 BOOL *pusedDefaultChar = &usedDefaultChar;
7034 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007035 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007036 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007037 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 const DWORD flags = encode_code_page_flags(code_page, NULL);
7039 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007040 /* Create a substring so that we can get the UTF-16 representation
7041 of just the slice under consideration. */
7042 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007043
Martin v. Löwis3d325192011-11-04 18:23:06 +01007044 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007045
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007047 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007049 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007050
Victor Stinner2fc507f2011-11-04 20:06:39 +01007051 substring = PyUnicode_Substring(unicode, offset, offset+len);
7052 if (substring == NULL)
7053 return -1;
7054 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7055 if (p == NULL) {
7056 Py_DECREF(substring);
7057 return -1;
7058 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007059
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007060 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007061 outsize = WideCharToMultiByte(code_page, flags,
7062 p, size,
7063 NULL, 0,
7064 NULL, pusedDefaultChar);
7065 if (outsize <= 0)
7066 goto error;
7067 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007068 if (pusedDefaultChar && *pusedDefaultChar) {
7069 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007070 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007071 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007072
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007074 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007075 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007076 if (*outbytes == NULL) {
7077 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007078 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007079 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081 }
7082 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 const Py_ssize_t n = PyBytes_Size(*outbytes);
7085 if (outsize > PY_SSIZE_T_MAX - n) {
7086 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007087 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007089 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007090 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7091 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007093 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095 }
7096
7097 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 outsize = WideCharToMultiByte(code_page, flags,
7099 p, size,
7100 out, outsize,
7101 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007102 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 if (outsize <= 0)
7104 goto error;
7105 if (pusedDefaultChar && *pusedDefaultChar)
7106 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007107 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007110 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7112 return -2;
7113 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007114 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007115}
7116
Victor Stinner3a50e702011-10-18 21:21:00 +02007117/*
7118 * Encode a Unicode string to a Windows code page into a byte string using a
7119 * error handler.
7120 *
7121 * Returns consumed characters if succeed, or raise a WindowsError and returns
7122 * -1 on other error.
7123 */
7124static int
7125encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007126 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007127 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007128{
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007130 Py_ssize_t pos = unicode_offset;
7131 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 /* Ideally, we should get reason from FormatMessage. This is the Windows
7133 2000 English version of the message. */
7134 const char *reason = "invalid character";
7135 /* 4=maximum length of a UTF-8 sequence */
7136 char buffer[4];
7137 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7138 Py_ssize_t outsize;
7139 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 PyObject *errorHandler = NULL;
7141 PyObject *exc = NULL;
7142 PyObject *encoding_obj = NULL;
7143 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007144 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 PyObject *rep;
7146 int ret = -1;
7147
7148 assert(insize > 0);
7149
7150 encoding = code_page_name(code_page, &encoding_obj);
7151 if (encoding == NULL)
7152 return -1;
7153
7154 if (errors == NULL || strcmp(errors, "strict") == 0) {
7155 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7156 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007157 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 if (exc != NULL) {
7159 PyCodec_StrictErrors(exc);
7160 Py_DECREF(exc);
7161 }
7162 Py_XDECREF(encoding_obj);
7163 return -1;
7164 }
7165
7166 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7167 pusedDefaultChar = &usedDefaultChar;
7168 else
7169 pusedDefaultChar = NULL;
7170
7171 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7172 PyErr_NoMemory();
7173 goto error;
7174 }
7175 outsize = insize * Py_ARRAY_LENGTH(buffer);
7176
7177 if (*outbytes == NULL) {
7178 /* Create string object */
7179 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7180 if (*outbytes == NULL)
7181 goto error;
7182 out = PyBytes_AS_STRING(*outbytes);
7183 }
7184 else {
7185 /* Extend string object */
7186 Py_ssize_t n = PyBytes_Size(*outbytes);
7187 if (n > PY_SSIZE_T_MAX - outsize) {
7188 PyErr_NoMemory();
7189 goto error;
7190 }
7191 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7192 goto error;
7193 out = PyBytes_AS_STRING(*outbytes) + n;
7194 }
7195
7196 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007197 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007199 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7200 wchar_t chars[2];
7201 int charsize;
7202 if (ch < 0x10000) {
7203 chars[0] = (wchar_t)ch;
7204 charsize = 1;
7205 }
7206 else {
7207 ch -= 0x10000;
7208 chars[0] = 0xd800 + (ch >> 10);
7209 chars[1] = 0xdc00 + (ch & 0x3ff);
7210 charsize = 2;
7211 }
7212
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007214 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 buffer, Py_ARRAY_LENGTH(buffer),
7216 NULL, pusedDefaultChar);
7217 if (outsize > 0) {
7218 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7219 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007220 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 memcpy(out, buffer, outsize);
7222 out += outsize;
7223 continue;
7224 }
7225 }
7226 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7227 PyErr_SetFromWindowsErr(0);
7228 goto error;
7229 }
7230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 rep = unicode_encode_call_errorhandler(
7232 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007233 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007234 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 if (rep == NULL)
7236 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007237 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007238
7239 if (PyBytes_Check(rep)) {
7240 outsize = PyBytes_GET_SIZE(rep);
7241 if (outsize != 1) {
7242 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7243 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7244 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7245 Py_DECREF(rep);
7246 goto error;
7247 }
7248 out = PyBytes_AS_STRING(*outbytes) + offset;
7249 }
7250 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7251 out += outsize;
7252 }
7253 else {
7254 Py_ssize_t i;
7255 enum PyUnicode_Kind kind;
7256 void *data;
7257
Benjamin Petersonbac79492012-01-14 13:34:47 -05007258 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 Py_DECREF(rep);
7260 goto error;
7261 }
7262
7263 outsize = PyUnicode_GET_LENGTH(rep);
7264 if (outsize != 1) {
7265 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7266 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7267 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7268 Py_DECREF(rep);
7269 goto error;
7270 }
7271 out = PyBytes_AS_STRING(*outbytes) + offset;
7272 }
7273 kind = PyUnicode_KIND(rep);
7274 data = PyUnicode_DATA(rep);
7275 for (i=0; i < outsize; i++) {
7276 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7277 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007278 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007279 encoding, unicode,
7280 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007281 "unable to encode error handler result to ASCII");
7282 Py_DECREF(rep);
7283 goto error;
7284 }
7285 *out = (unsigned char)ch;
7286 out++;
7287 }
7288 }
7289 Py_DECREF(rep);
7290 }
7291 /* write a NUL byte */
7292 *out = 0;
7293 outsize = out - PyBytes_AS_STRING(*outbytes);
7294 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7295 if (_PyBytes_Resize(outbytes, outsize) < 0)
7296 goto error;
7297 ret = 0;
7298
7299error:
7300 Py_XDECREF(encoding_obj);
7301 Py_XDECREF(errorHandler);
7302 Py_XDECREF(exc);
7303 return ret;
7304}
7305
Victor Stinner3a50e702011-10-18 21:21:00 +02007306static PyObject *
7307encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007308 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 const char *errors)
7310{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007311 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007313 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007314 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007315
Benjamin Petersonbac79492012-01-14 13:34:47 -05007316 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007317 return NULL;
7318 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007319
Victor Stinner3a50e702011-10-18 21:21:00 +02007320 if (code_page < 0) {
7321 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7322 return NULL;
7323 }
7324
Martin v. Löwis3d325192011-11-04 18:23:06 +01007325 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007326 return PyBytes_FromStringAndSize(NULL, 0);
7327
Victor Stinner7581cef2011-11-03 22:32:33 +01007328 offset = 0;
7329 do
7330 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007332 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007333 chunks. */
7334 if (len > INT_MAX/2) {
7335 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007336 done = 0;
7337 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007338 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007340 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007341 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007342 done = 1;
7343 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007344
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007346 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007347 errors);
7348 if (ret == -2)
7349 ret = encode_code_page_errors(code_page, &outbytes,
7350 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007352 if (ret < 0) {
7353 Py_XDECREF(outbytes);
7354 return NULL;
7355 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356
Victor Stinner7581cef2011-11-03 22:32:33 +01007357 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007358 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007359 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007360
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 return outbytes;
7362}
7363
7364PyObject *
7365PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7366 Py_ssize_t size,
7367 const char *errors)
7368{
Victor Stinner7581cef2011-11-03 22:32:33 +01007369 PyObject *unicode, *res;
7370 unicode = PyUnicode_FromUnicode(p, size);
7371 if (unicode == NULL)
7372 return NULL;
7373 res = encode_code_page(CP_ACP, unicode, errors);
7374 Py_DECREF(unicode);
7375 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007376}
7377
7378PyObject *
7379PyUnicode_EncodeCodePage(int code_page,
7380 PyObject *unicode,
7381 const char *errors)
7382{
Victor Stinner7581cef2011-11-03 22:32:33 +01007383 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007384}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007385
Alexander Belopolsky40018472011-02-26 01:02:56 +00007386PyObject *
7387PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007388{
7389 if (!PyUnicode_Check(unicode)) {
7390 PyErr_BadArgument();
7391 return NULL;
7392 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007393 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007394}
7395
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007396#undef NEED_RETRY
7397
Victor Stinner99b95382011-07-04 14:23:54 +02007398#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007399
Guido van Rossumd57fd912000-03-10 22:53:23 +00007400/* --- Character Mapping Codec -------------------------------------------- */
7401
Alexander Belopolsky40018472011-02-26 01:02:56 +00007402PyObject *
7403PyUnicode_DecodeCharmap(const char *s,
7404 Py_ssize_t size,
7405 PyObject *mapping,
7406 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007407{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007408 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007409 Py_ssize_t startinpos;
7410 Py_ssize_t endinpos;
7411 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007412 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007413 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007414 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007415 PyObject *errorHandler = NULL;
7416 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007417
Guido van Rossumd57fd912000-03-10 22:53:23 +00007418 /* Default to Latin-1 */
7419 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007421
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007422 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007423 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007425 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007426 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007427 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007428 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007429 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007430 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007431 enum PyUnicode_Kind mapkind;
7432 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007433 Py_UCS4 x;
7434
Benjamin Petersonbac79492012-01-14 13:34:47 -05007435 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007436 return NULL;
7437
7438 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007439 mapdata = PyUnicode_DATA(mapping);
7440 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007441 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007442 unsigned char ch;
7443 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7444 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7445 if (outkind == PyUnicode_1BYTE_KIND) {
7446 void *outdata = PyUnicode_DATA(v);
7447 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7448 while (s < e) {
7449 unsigned char ch = *s;
7450 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7451 if (x > maxchar)
7452 goto Error;
7453 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7454 ++s;
7455 }
7456 break;
7457 }
7458 else if (outkind == PyUnicode_2BYTE_KIND) {
7459 void *outdata = PyUnicode_DATA(v);
7460 while (s < e) {
7461 unsigned char ch = *s;
7462 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7463 if (x == 0xFFFE)
7464 goto Error;
7465 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7466 ++s;
7467 }
7468 break;
7469 }
7470 }
7471 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007472
Benjamin Peterson29060642009-01-31 22:14:21 +00007473 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007474 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007475 else
7476 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007477Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007478 if (x == 0xfffe)
7479 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007480 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 startinpos = s-starts;
7482 endinpos = startinpos+1;
7483 if (unicode_decode_call_errorhandler(
7484 errors, &errorHandler,
7485 "charmap", "character maps to <undefined>",
7486 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007487 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007488 goto onError;
7489 }
7490 continue;
7491 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007492
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007493 if (unicode_putchar(&v, &outpos, x) < 0)
7494 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007495 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007496 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007497 }
7498 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 while (s < e) {
7500 unsigned char ch = *s;
7501 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007502
Benjamin Peterson29060642009-01-31 22:14:21 +00007503 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7504 w = PyLong_FromLong((long)ch);
7505 if (w == NULL)
7506 goto onError;
7507 x = PyObject_GetItem(mapping, w);
7508 Py_DECREF(w);
7509 if (x == NULL) {
7510 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7511 /* No mapping found means: mapping is undefined. */
7512 PyErr_Clear();
7513 x = Py_None;
7514 Py_INCREF(x);
7515 } else
7516 goto onError;
7517 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007518
Benjamin Peterson29060642009-01-31 22:14:21 +00007519 /* Apply mapping */
7520 if (PyLong_Check(x)) {
7521 long value = PyLong_AS_LONG(x);
Antoine Pitroua1f76552012-09-23 20:00:04 +02007522 if (value < 0 || value > MAX_UNICODE) {
7523 PyErr_Format(PyExc_TypeError,
7524 "character mapping must be in range(0x%lx)",
7525 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007526 Py_DECREF(x);
7527 goto onError;
7528 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007529 if (unicode_putchar(&v, &outpos, value) < 0)
7530 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007531 }
7532 else if (x == Py_None) {
7533 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007534 startinpos = s-starts;
7535 endinpos = startinpos+1;
7536 if (unicode_decode_call_errorhandler(
7537 errors, &errorHandler,
7538 "charmap", "character maps to <undefined>",
7539 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007540 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007541 Py_DECREF(x);
7542 goto onError;
7543 }
7544 Py_DECREF(x);
7545 continue;
7546 }
7547 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007548 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007549
Benjamin Petersonbac79492012-01-14 13:34:47 -05007550 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007551 goto onError;
7552 targetsize = PyUnicode_GET_LENGTH(x);
7553
7554 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007555 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007556 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007557 PyUnicode_READ_CHAR(x, 0)) < 0)
7558 goto onError;
7559 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007560 else if (targetsize > 1) {
7561 /* 1-n mapping */
7562 if (targetsize > extrachars) {
7563 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007564 Py_ssize_t needed = (targetsize - extrachars) + \
7565 (targetsize << 2);
7566 extrachars += needed;
7567 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007568 if (unicode_resize(&v,
7569 PyUnicode_GET_LENGTH(v) + needed) < 0)
7570 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007571 Py_DECREF(x);
7572 goto onError;
7573 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007574 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007575 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007576 goto onError;
7577 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7578 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007579 extrachars -= targetsize;
7580 }
7581 /* 1-0 mapping: skip the character */
7582 }
7583 else {
7584 /* wrong return value */
7585 PyErr_SetString(PyExc_TypeError,
7586 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007587 Py_DECREF(x);
7588 goto onError;
7589 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 Py_DECREF(x);
7591 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007592 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007593 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007594 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007595 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007596 Py_XDECREF(errorHandler);
7597 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007598 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007599
Benjamin Peterson29060642009-01-31 22:14:21 +00007600 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007601 Py_XDECREF(errorHandler);
7602 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007603 Py_XDECREF(v);
7604 return NULL;
7605}
7606
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007607/* Charmap encoding: the lookup table */
7608
Alexander Belopolsky40018472011-02-26 01:02:56 +00007609struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007610 PyObject_HEAD
7611 unsigned char level1[32];
7612 int count2, count3;
7613 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007614};
7615
7616static PyObject*
7617encoding_map_size(PyObject *obj, PyObject* args)
7618{
7619 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007620 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007622}
7623
7624static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007625 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 PyDoc_STR("Return the size (in bytes) of this object") },
7627 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007628};
7629
7630static void
7631encoding_map_dealloc(PyObject* o)
7632{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007633 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007634}
7635
7636static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007637 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007638 "EncodingMap", /*tp_name*/
7639 sizeof(struct encoding_map), /*tp_basicsize*/
7640 0, /*tp_itemsize*/
7641 /* methods */
7642 encoding_map_dealloc, /*tp_dealloc*/
7643 0, /*tp_print*/
7644 0, /*tp_getattr*/
7645 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007646 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 0, /*tp_repr*/
7648 0, /*tp_as_number*/
7649 0, /*tp_as_sequence*/
7650 0, /*tp_as_mapping*/
7651 0, /*tp_hash*/
7652 0, /*tp_call*/
7653 0, /*tp_str*/
7654 0, /*tp_getattro*/
7655 0, /*tp_setattro*/
7656 0, /*tp_as_buffer*/
7657 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7658 0, /*tp_doc*/
7659 0, /*tp_traverse*/
7660 0, /*tp_clear*/
7661 0, /*tp_richcompare*/
7662 0, /*tp_weaklistoffset*/
7663 0, /*tp_iter*/
7664 0, /*tp_iternext*/
7665 encoding_map_methods, /*tp_methods*/
7666 0, /*tp_members*/
7667 0, /*tp_getset*/
7668 0, /*tp_base*/
7669 0, /*tp_dict*/
7670 0, /*tp_descr_get*/
7671 0, /*tp_descr_set*/
7672 0, /*tp_dictoffset*/
7673 0, /*tp_init*/
7674 0, /*tp_alloc*/
7675 0, /*tp_new*/
7676 0, /*tp_free*/
7677 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007678};
7679
7680PyObject*
7681PyUnicode_BuildEncodingMap(PyObject* string)
7682{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007683 PyObject *result;
7684 struct encoding_map *mresult;
7685 int i;
7686 int need_dict = 0;
7687 unsigned char level1[32];
7688 unsigned char level2[512];
7689 unsigned char *mlevel1, *mlevel2, *mlevel3;
7690 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007691 int kind;
7692 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007693 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007694 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007695
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007696 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007697 PyErr_BadArgument();
7698 return NULL;
7699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007700 kind = PyUnicode_KIND(string);
7701 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007702 length = PyUnicode_GET_LENGTH(string);
7703 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007704 memset(level1, 0xFF, sizeof level1);
7705 memset(level2, 0xFF, sizeof level2);
7706
7707 /* If there isn't a one-to-one mapping of NULL to \0,
7708 or if there are non-BMP characters, we need to use
7709 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007710 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007711 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007712 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007713 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007714 ch = PyUnicode_READ(kind, data, i);
7715 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007716 need_dict = 1;
7717 break;
7718 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007719 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007720 /* unmapped character */
7721 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007722 l1 = ch >> 11;
7723 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007724 if (level1[l1] == 0xFF)
7725 level1[l1] = count2++;
7726 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007727 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007728 }
7729
7730 if (count2 >= 0xFF || count3 >= 0xFF)
7731 need_dict = 1;
7732
7733 if (need_dict) {
7734 PyObject *result = PyDict_New();
7735 PyObject *key, *value;
7736 if (!result)
7737 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007738 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007739 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007740 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007741 if (!key || !value)
7742 goto failed1;
7743 if (PyDict_SetItem(result, key, value) == -1)
7744 goto failed1;
7745 Py_DECREF(key);
7746 Py_DECREF(value);
7747 }
7748 return result;
7749 failed1:
7750 Py_XDECREF(key);
7751 Py_XDECREF(value);
7752 Py_DECREF(result);
7753 return NULL;
7754 }
7755
7756 /* Create a three-level trie */
7757 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7758 16*count2 + 128*count3 - 1);
7759 if (!result)
7760 return PyErr_NoMemory();
7761 PyObject_Init(result, &EncodingMapType);
7762 mresult = (struct encoding_map*)result;
7763 mresult->count2 = count2;
7764 mresult->count3 = count3;
7765 mlevel1 = mresult->level1;
7766 mlevel2 = mresult->level23;
7767 mlevel3 = mresult->level23 + 16*count2;
7768 memcpy(mlevel1, level1, 32);
7769 memset(mlevel2, 0xFF, 16*count2);
7770 memset(mlevel3, 0, 128*count3);
7771 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007772 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007773 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007774 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7775 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007776 /* unmapped character */
7777 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007778 o1 = ch>>11;
7779 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780 i2 = 16*mlevel1[o1] + o2;
7781 if (mlevel2[i2] == 0xFF)
7782 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007783 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007784 i3 = 128*mlevel2[i2] + o3;
7785 mlevel3[i3] = i;
7786 }
7787 return result;
7788}
7789
7790static int
Victor Stinner22168992011-11-20 17:09:18 +01007791encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007792{
7793 struct encoding_map *map = (struct encoding_map*)mapping;
7794 int l1 = c>>11;
7795 int l2 = (c>>7) & 0xF;
7796 int l3 = c & 0x7F;
7797 int i;
7798
Victor Stinner22168992011-11-20 17:09:18 +01007799 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007800 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007801 if (c == 0)
7802 return 0;
7803 /* level 1*/
7804 i = map->level1[l1];
7805 if (i == 0xFF) {
7806 return -1;
7807 }
7808 /* level 2*/
7809 i = map->level23[16*i+l2];
7810 if (i == 0xFF) {
7811 return -1;
7812 }
7813 /* level 3 */
7814 i = map->level23[16*map->count2 + 128*i + l3];
7815 if (i == 0) {
7816 return -1;
7817 }
7818 return i;
7819}
7820
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007821/* Lookup the character ch in the mapping. If the character
7822 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007823 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007824static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007825charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826{
Christian Heimes217cfd12007-12-02 14:31:20 +00007827 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007828 PyObject *x;
7829
7830 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007832 x = PyObject_GetItem(mapping, w);
7833 Py_DECREF(w);
7834 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007835 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7836 /* No mapping found means: mapping is undefined. */
7837 PyErr_Clear();
7838 x = Py_None;
7839 Py_INCREF(x);
7840 return x;
7841 } else
7842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007843 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007844 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007845 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007846 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 long value = PyLong_AS_LONG(x);
7848 if (value < 0 || value > 255) {
7849 PyErr_SetString(PyExc_TypeError,
7850 "character mapping must be in range(256)");
7851 Py_DECREF(x);
7852 return NULL;
7853 }
7854 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007855 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007856 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007858 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 /* wrong return value */
7860 PyErr_Format(PyExc_TypeError,
7861 "character mapping must return integer, bytes or None, not %.400s",
7862 x->ob_type->tp_name);
7863 Py_DECREF(x);
7864 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007865 }
7866}
7867
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007869charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007871 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7872 /* exponentially overallocate to minimize reallocations */
7873 if (requiredsize < 2*outsize)
7874 requiredsize = 2*outsize;
7875 if (_PyBytes_Resize(outobj, requiredsize))
7876 return -1;
7877 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007878}
7879
Benjamin Peterson14339b62009-01-31 16:36:08 +00007880typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007882} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007883/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007884 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007885 space is available. Return a new reference to the object that
7886 was put in the output buffer, or Py_None, if the mapping was undefined
7887 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007888 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007889static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007890charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007891 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007892{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007893 PyObject *rep;
7894 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007895 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007896
Christian Heimes90aa7642007-12-19 02:45:37 +00007897 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007898 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007899 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007900 if (res == -1)
7901 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 if (outsize<requiredsize)
7903 if (charmapencode_resize(outobj, outpos, requiredsize))
7904 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007905 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 outstart[(*outpos)++] = (char)res;
7907 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007908 }
7909
7910 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007911 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007912 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007913 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 Py_DECREF(rep);
7915 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007917 if (PyLong_Check(rep)) {
7918 Py_ssize_t requiredsize = *outpos+1;
7919 if (outsize<requiredsize)
7920 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7921 Py_DECREF(rep);
7922 return enc_EXCEPTION;
7923 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007924 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007926 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007927 else {
7928 const char *repchars = PyBytes_AS_STRING(rep);
7929 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7930 Py_ssize_t requiredsize = *outpos+repsize;
7931 if (outsize<requiredsize)
7932 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7933 Py_DECREF(rep);
7934 return enc_EXCEPTION;
7935 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007936 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 memcpy(outstart + *outpos, repchars, repsize);
7938 *outpos += repsize;
7939 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007940 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 Py_DECREF(rep);
7942 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007943}
7944
7945/* handle an error in PyUnicode_EncodeCharmap
7946 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007947static int
7948charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007949 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007950 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007951 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007952 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007953{
7954 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007955 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007956 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007957 enum PyUnicode_Kind kind;
7958 void *data;
7959 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007960 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007961 Py_ssize_t collstartpos = *inpos;
7962 Py_ssize_t collendpos = *inpos+1;
7963 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964 char *encoding = "charmap";
7965 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007966 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007967 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007968 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007969
Benjamin Petersonbac79492012-01-14 13:34:47 -05007970 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007971 return -1;
7972 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007973 /* find all unencodable characters */
7974 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007975 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007976 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007977 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007978 val = encoding_map_lookup(ch, mapping);
7979 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007980 break;
7981 ++collendpos;
7982 continue;
7983 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007984
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007985 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7986 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 if (rep==NULL)
7988 return -1;
7989 else if (rep!=Py_None) {
7990 Py_DECREF(rep);
7991 break;
7992 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007993 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007994 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007995 }
7996 /* cache callback name lookup
7997 * (if not done yet, i.e. it's the first error) */
7998 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 if ((errors==NULL) || (!strcmp(errors, "strict")))
8000 *known_errorHandler = 1;
8001 else if (!strcmp(errors, "replace"))
8002 *known_errorHandler = 2;
8003 else if (!strcmp(errors, "ignore"))
8004 *known_errorHandler = 3;
8005 else if (!strcmp(errors, "xmlcharrefreplace"))
8006 *known_errorHandler = 4;
8007 else
8008 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008009 }
8010 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008011 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008012 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008013 return -1;
8014 case 2: /* replace */
8015 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 x = charmapencode_output('?', mapping, res, respos);
8017 if (x==enc_EXCEPTION) {
8018 return -1;
8019 }
8020 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008021 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 return -1;
8023 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008024 }
8025 /* fall through */
8026 case 3: /* ignore */
8027 *inpos = collendpos;
8028 break;
8029 case 4: /* xmlcharrefreplace */
8030 /* generate replacement (temporarily (mis)uses p) */
8031 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008032 char buffer[2+29+1+1];
8033 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008034 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 for (cp = buffer; *cp; ++cp) {
8036 x = charmapencode_output(*cp, mapping, res, respos);
8037 if (x==enc_EXCEPTION)
8038 return -1;
8039 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008040 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 return -1;
8042 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008043 }
8044 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008045 *inpos = collendpos;
8046 break;
8047 default:
8048 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008049 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008051 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008053 if (PyBytes_Check(repunicode)) {
8054 /* Directly copy bytes result to output. */
8055 Py_ssize_t outsize = PyBytes_Size(*res);
8056 Py_ssize_t requiredsize;
8057 repsize = PyBytes_Size(repunicode);
8058 requiredsize = *respos + repsize;
8059 if (requiredsize > outsize)
8060 /* Make room for all additional bytes. */
8061 if (charmapencode_resize(res, respos, requiredsize)) {
8062 Py_DECREF(repunicode);
8063 return -1;
8064 }
8065 memcpy(PyBytes_AsString(*res) + *respos,
8066 PyBytes_AsString(repunicode), repsize);
8067 *respos += repsize;
8068 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008069 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008070 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008071 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008072 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008073 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008074 Py_DECREF(repunicode);
8075 return -1;
8076 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008077 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008078 data = PyUnicode_DATA(repunicode);
8079 kind = PyUnicode_KIND(repunicode);
8080 for (index = 0; index < repsize; index++) {
8081 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8082 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008084 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 return -1;
8086 }
8087 else if (x==enc_FAILED) {
8088 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008089 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 return -1;
8091 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008092 }
8093 *inpos = newpos;
8094 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095 }
8096 return 0;
8097}
8098
Alexander Belopolsky40018472011-02-26 01:02:56 +00008099PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008100_PyUnicode_EncodeCharmap(PyObject *unicode,
8101 PyObject *mapping,
8102 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008103{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008104 /* output object */
8105 PyObject *res = NULL;
8106 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008107 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008108 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008109 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008110 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008111 PyObject *errorHandler = NULL;
8112 PyObject *exc = NULL;
8113 /* the following variable is used for caching string comparisons
8114 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8115 * 3=ignore, 4=xmlcharrefreplace */
8116 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008117
Benjamin Petersonbac79492012-01-14 13:34:47 -05008118 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 return NULL;
8120 size = PyUnicode_GET_LENGTH(unicode);
8121
Guido van Rossumd57fd912000-03-10 22:53:23 +00008122 /* Default to Latin-1 */
8123 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008124 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008125
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008126 /* allocate enough for a simple encoding without
8127 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008128 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008129 if (res == NULL)
8130 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008131 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008133
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008134 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008135 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008137 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 if (x==enc_EXCEPTION) /* error */
8139 goto onError;
8140 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008141 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 &exc,
8143 &known_errorHandler, &errorHandler, errors,
8144 &res, &respos)) {
8145 goto onError;
8146 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 else
8149 /* done with this character => adjust input position */
8150 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008151 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008152
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008153 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008154 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008155 if (_PyBytes_Resize(&res, respos) < 0)
8156 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008157
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008158 Py_XDECREF(exc);
8159 Py_XDECREF(errorHandler);
8160 return res;
8161
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008163 Py_XDECREF(res);
8164 Py_XDECREF(exc);
8165 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008166 return NULL;
8167}
8168
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008169/* Deprecated */
8170PyObject *
8171PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8172 Py_ssize_t size,
8173 PyObject *mapping,
8174 const char *errors)
8175{
8176 PyObject *result;
8177 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8178 if (unicode == NULL)
8179 return NULL;
8180 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8181 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008182 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008183}
8184
Alexander Belopolsky40018472011-02-26 01:02:56 +00008185PyObject *
8186PyUnicode_AsCharmapString(PyObject *unicode,
8187 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008188{
8189 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008190 PyErr_BadArgument();
8191 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008192 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008193 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194}
8195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008197static void
8198make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008199 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008200 Py_ssize_t startpos, Py_ssize_t endpos,
8201 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008202{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008203 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008204 *exceptionObject = _PyUnicodeTranslateError_Create(
8205 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008206 }
8207 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8209 goto onError;
8210 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8211 goto onError;
8212 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8213 goto onError;
8214 return;
8215 onError:
8216 Py_DECREF(*exceptionObject);
8217 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008218 }
8219}
8220
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008222static void
8223raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008224 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008225 Py_ssize_t startpos, Py_ssize_t endpos,
8226 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227{
8228 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008229 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008232}
8233
8234/* error handling callback helper:
8235 build arguments, call the callback and check the arguments,
8236 put the result into newpos and return the replacement string, which
8237 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008238static PyObject *
8239unicode_translate_call_errorhandler(const char *errors,
8240 PyObject **errorHandler,
8241 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008242 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008243 Py_ssize_t startpos, Py_ssize_t endpos,
8244 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008245{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008246 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008248 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249 PyObject *restuple;
8250 PyObject *resunicode;
8251
8252 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008254 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256 }
8257
8258 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008259 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262
8263 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008267 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008268 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 Py_DECREF(restuple);
8270 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 }
8272 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 &resunicode, &i_newpos)) {
8274 Py_DECREF(restuple);
8275 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008277 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008278 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008279 else
8280 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8283 Py_DECREF(restuple);
8284 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008285 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008286 Py_INCREF(resunicode);
8287 Py_DECREF(restuple);
8288 return resunicode;
8289}
8290
8291/* Lookup the character ch in the mapping and put the result in result,
8292 which must be decrefed by the caller.
8293 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008294static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008295charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296{
Christian Heimes217cfd12007-12-02 14:31:20 +00008297 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298 PyObject *x;
8299
8300 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302 x = PyObject_GetItem(mapping, w);
8303 Py_DECREF(w);
8304 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8306 /* No mapping found means: use 1:1 mapping. */
8307 PyErr_Clear();
8308 *result = NULL;
8309 return 0;
8310 } else
8311 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008312 }
8313 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 *result = x;
8315 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008317 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 long value = PyLong_AS_LONG(x);
8319 long max = PyUnicode_GetMax();
8320 if (value < 0 || value > max) {
8321 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008322 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 Py_DECREF(x);
8324 return -1;
8325 }
8326 *result = x;
8327 return 0;
8328 }
8329 else if (PyUnicode_Check(x)) {
8330 *result = x;
8331 return 0;
8332 }
8333 else {
8334 /* wrong return value */
8335 PyErr_SetString(PyExc_TypeError,
8336 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008337 Py_DECREF(x);
8338 return -1;
8339 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008340}
8341/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 if not reallocate and adjust various state variables.
8343 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008344static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008345charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008348 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008349 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008350 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 /* exponentially overallocate to minimize reallocations */
8352 if (requiredsize < 2 * oldsize)
8353 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008354 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8355 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008357 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008358 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 }
8360 return 0;
8361}
8362/* lookup the character, put the result in the output string and adjust
8363 various state variables. Return a new reference to the object that
8364 was put in the output buffer in *result, or Py_None, if the mapping was
8365 undefined (in which case no character was written).
8366 The called must decref result.
8367 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008368static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008369charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8370 PyObject *mapping, Py_UCS4 **output,
8371 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008372 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008374 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8375 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 }
8381 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008383 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 }
8387 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008388 Py_ssize_t repsize;
8389 if (PyUnicode_READY(*res) == -1)
8390 return -1;
8391 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 if (repsize==1) {
8393 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008394 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 }
8396 else if (repsize!=0) {
8397 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008398 Py_ssize_t requiredsize = *opos +
8399 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008401 Py_ssize_t i;
8402 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008404 for(i = 0; i < repsize; i++)
8405 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 return 0;
8411}
8412
Alexander Belopolsky40018472011-02-26 01:02:56 +00008413PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008414_PyUnicode_TranslateCharmap(PyObject *input,
8415 PyObject *mapping,
8416 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008417{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008418 /* input object */
8419 char *idata;
8420 Py_ssize_t size, i;
8421 int kind;
8422 /* output buffer */
8423 Py_UCS4 *output = NULL;
8424 Py_ssize_t osize;
8425 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008427 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 char *reason = "character maps to <undefined>";
8429 PyObject *errorHandler = NULL;
8430 PyObject *exc = NULL;
8431 /* the following variable is used for caching string comparisons
8432 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8433 * 3=ignore, 4=xmlcharrefreplace */
8434 int known_errorHandler = -1;
8435
Guido van Rossumd57fd912000-03-10 22:53:23 +00008436 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 PyErr_BadArgument();
8438 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008439 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008441 if (PyUnicode_READY(input) == -1)
8442 return NULL;
8443 idata = (char*)PyUnicode_DATA(input);
8444 kind = PyUnicode_KIND(input);
8445 size = PyUnicode_GET_LENGTH(input);
8446 i = 0;
8447
8448 if (size == 0) {
8449 Py_INCREF(input);
8450 return input;
8451 }
8452
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 /* allocate enough for a simple 1:1 translation without
8454 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 osize = size;
8456 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8457 opos = 0;
8458 if (output == NULL) {
8459 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008463 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 /* try to encode it */
8465 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008466 if (charmaptranslate_output(input, i, mapping,
8467 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 Py_XDECREF(x);
8469 goto onError;
8470 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008471 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008473 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 else { /* untranslatable character */
8475 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8476 Py_ssize_t repsize;
8477 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008478 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480 Py_ssize_t collstart = i;
8481 Py_ssize_t collend = i+1;
8482 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008483
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 while (collend < size) {
8486 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 goto onError;
8488 Py_XDECREF(x);
8489 if (x!=Py_None)
8490 break;
8491 ++collend;
8492 }
8493 /* cache callback name lookup
8494 * (if not done yet, i.e. it's the first error) */
8495 if (known_errorHandler==-1) {
8496 if ((errors==NULL) || (!strcmp(errors, "strict")))
8497 known_errorHandler = 1;
8498 else if (!strcmp(errors, "replace"))
8499 known_errorHandler = 2;
8500 else if (!strcmp(errors, "ignore"))
8501 known_errorHandler = 3;
8502 else if (!strcmp(errors, "xmlcharrefreplace"))
8503 known_errorHandler = 4;
8504 else
8505 known_errorHandler = 0;
8506 }
8507 switch (known_errorHandler) {
8508 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509 raise_translate_exception(&exc, input, collstart,
8510 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008511 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 case 2: /* replace */
8513 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 for (coll = collstart; coll<collend; coll++)
8515 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 /* fall through */
8517 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008518 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 break;
8520 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008521 /* generate replacement (temporarily (mis)uses i) */
8522 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 char buffer[2+29+1+1];
8524 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8526 if (charmaptranslate_makespace(&output, &osize,
8527 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 goto onError;
8529 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 break;
8534 default:
8535 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 reason, input, &exc,
8537 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008538 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008540 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008541 Py_DECREF(repunicode);
8542 goto onError;
8543 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008545 repsize = PyUnicode_GET_LENGTH(repunicode);
8546 if (charmaptranslate_makespace(&output, &osize,
8547 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 Py_DECREF(repunicode);
8549 goto onError;
8550 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 for (uni2 = 0; repsize-->0; ++uni2)
8552 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8553 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008555 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008556 }
8557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008558 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8559 if (!res)
8560 goto onError;
8561 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 Py_XDECREF(exc);
8563 Py_XDECREF(errorHandler);
8564 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008565
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 Py_XDECREF(exc);
8569 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570 return NULL;
8571}
8572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573/* Deprecated. Use PyUnicode_Translate instead. */
8574PyObject *
8575PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8576 Py_ssize_t size,
8577 PyObject *mapping,
8578 const char *errors)
8579{
Christian Heimes5f520f42012-09-11 14:03:25 +02008580 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8582 if (!unicode)
8583 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008584 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8585 Py_DECREF(unicode);
8586 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587}
8588
Alexander Belopolsky40018472011-02-26 01:02:56 +00008589PyObject *
8590PyUnicode_Translate(PyObject *str,
8591 PyObject *mapping,
8592 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593{
8594 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008595
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596 str = PyUnicode_FromObject(str);
8597 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008598 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600 Py_DECREF(str);
8601 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602}
Tim Petersced69f82003-09-16 20:30:58 +00008603
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008605fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606{
8607 /* No need to call PyUnicode_READY(self) because this function is only
8608 called as a callback from fixup() which does it already. */
8609 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8610 const int kind = PyUnicode_KIND(self);
8611 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008612 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008613 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 Py_ssize_t i;
8615
8616 for (i = 0; i < len; ++i) {
8617 ch = PyUnicode_READ(kind, data, i);
8618 fixed = 0;
8619 if (ch > 127) {
8620 if (Py_UNICODE_ISSPACE(ch))
8621 fixed = ' ';
8622 else {
8623 const int decimal = Py_UNICODE_TODECIMAL(ch);
8624 if (decimal >= 0)
8625 fixed = '0' + decimal;
8626 }
8627 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008628 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008629 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630 PyUnicode_WRITE(kind, data, i, fixed);
8631 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008632 else
8633 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 }
8636
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008637 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638}
8639
8640PyObject *
8641_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8642{
8643 if (!PyUnicode_Check(unicode)) {
8644 PyErr_BadInternalCall();
8645 return NULL;
8646 }
8647 if (PyUnicode_READY(unicode) == -1)
8648 return NULL;
8649 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8650 /* If the string is already ASCII, just return the same string */
8651 Py_INCREF(unicode);
8652 return unicode;
8653 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008654 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655}
8656
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008657PyObject *
8658PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8659 Py_ssize_t length)
8660{
Victor Stinnerf0124502011-11-21 23:12:56 +01008661 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008662 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008663 Py_UCS4 maxchar;
8664 enum PyUnicode_Kind kind;
8665 void *data;
8666
Victor Stinner99d7ad02012-02-22 13:37:39 +01008667 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008668 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008669 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008670 if (ch > 127) {
8671 int decimal = Py_UNICODE_TODECIMAL(ch);
8672 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008673 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008674 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008675 }
8676 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008677
8678 /* Copy to a new string */
8679 decimal = PyUnicode_New(length, maxchar);
8680 if (decimal == NULL)
8681 return decimal;
8682 kind = PyUnicode_KIND(decimal);
8683 data = PyUnicode_DATA(decimal);
8684 /* Iterate over code points */
8685 for (i = 0; i < length; i++) {
8686 Py_UNICODE ch = s[i];
8687 if (ch > 127) {
8688 int decimal = Py_UNICODE_TODECIMAL(ch);
8689 if (decimal >= 0)
8690 ch = '0' + decimal;
8691 }
8692 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008694 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008695}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008696/* --- Decimal Encoder ---------------------------------------------------- */
8697
Alexander Belopolsky40018472011-02-26 01:02:56 +00008698int
8699PyUnicode_EncodeDecimal(Py_UNICODE *s,
8700 Py_ssize_t length,
8701 char *output,
8702 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008703{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008704 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008705 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008706 enum PyUnicode_Kind kind;
8707 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008708
8709 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 PyErr_BadArgument();
8711 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008712 }
8713
Victor Stinner42bf7752011-11-21 22:52:58 +01008714 unicode = PyUnicode_FromUnicode(s, length);
8715 if (unicode == NULL)
8716 return -1;
8717
Benjamin Petersonbac79492012-01-14 13:34:47 -05008718 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008719 Py_DECREF(unicode);
8720 return -1;
8721 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008722 kind = PyUnicode_KIND(unicode);
8723 data = PyUnicode_DATA(unicode);
8724
Victor Stinnerb84d7232011-11-22 01:50:07 +01008725 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008726 PyObject *exc;
8727 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008729 Py_ssize_t startpos;
8730
8731 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008732
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008734 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008735 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008737 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 decimal = Py_UNICODE_TODECIMAL(ch);
8739 if (decimal >= 0) {
8740 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008741 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 continue;
8743 }
8744 if (0 < ch && ch < 256) {
8745 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008746 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 continue;
8748 }
Victor Stinner6345be92011-11-25 20:09:01 +01008749
Victor Stinner42bf7752011-11-21 22:52:58 +01008750 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008751 exc = NULL;
8752 raise_encode_exception(&exc, "decimal", unicode,
8753 startpos, startpos+1,
8754 "invalid decimal Unicode string");
8755 Py_XDECREF(exc);
8756 Py_DECREF(unicode);
8757 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008758 }
8759 /* 0-terminate the output string */
8760 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008761 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008762 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008763}
8764
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765/* --- Helpers ------------------------------------------------------------ */
8766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008768any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 Py_ssize_t start,
8770 Py_ssize_t end)
8771{
8772 int kind1, kind2, kind;
8773 void *buf1, *buf2;
8774 Py_ssize_t len1, len2, result;
8775
8776 kind1 = PyUnicode_KIND(s1);
8777 kind2 = PyUnicode_KIND(s2);
8778 kind = kind1 > kind2 ? kind1 : kind2;
8779 buf1 = PyUnicode_DATA(s1);
8780 buf2 = PyUnicode_DATA(s2);
8781 if (kind1 != kind)
8782 buf1 = _PyUnicode_AsKind(s1, kind);
8783 if (!buf1)
8784 return -2;
8785 if (kind2 != kind)
8786 buf2 = _PyUnicode_AsKind(s2, kind);
8787 if (!buf2) {
8788 if (kind1 != kind) PyMem_Free(buf1);
8789 return -2;
8790 }
8791 len1 = PyUnicode_GET_LENGTH(s1);
8792 len2 = PyUnicode_GET_LENGTH(s2);
8793
Victor Stinner794d5672011-10-10 03:21:36 +02008794 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008795 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008796 case PyUnicode_1BYTE_KIND:
8797 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8798 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8799 else
8800 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8801 break;
8802 case PyUnicode_2BYTE_KIND:
8803 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8804 break;
8805 case PyUnicode_4BYTE_KIND:
8806 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8807 break;
8808 default:
8809 assert(0); result = -2;
8810 }
8811 }
8812 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008813 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008814 case PyUnicode_1BYTE_KIND:
8815 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8816 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8817 else
8818 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8819 break;
8820 case PyUnicode_2BYTE_KIND:
8821 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8822 break;
8823 case PyUnicode_4BYTE_KIND:
8824 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8825 break;
8826 default:
8827 assert(0); result = -2;
8828 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 }
8830
8831 if (kind1 != kind)
8832 PyMem_Free(buf1);
8833 if (kind2 != kind)
8834 PyMem_Free(buf2);
8835
8836 return result;
8837}
8838
8839Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008840_PyUnicode_InsertThousandsGrouping(
8841 PyObject *unicode, Py_ssize_t index,
8842 Py_ssize_t n_buffer,
8843 void *digits, Py_ssize_t n_digits,
8844 Py_ssize_t min_width,
8845 const char *grouping, PyObject *thousands_sep,
8846 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008847{
Victor Stinner41a863c2012-02-24 00:37:51 +01008848 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008849 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008850 Py_ssize_t thousands_sep_len;
8851 Py_ssize_t len;
8852
8853 if (unicode != NULL) {
8854 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008855 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008856 }
8857 else {
8858 kind = PyUnicode_1BYTE_KIND;
8859 data = NULL;
8860 }
8861 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8862 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8863 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8864 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008865 if (thousands_sep_kind < kind) {
8866 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8867 if (!thousands_sep_data)
8868 return -1;
8869 }
8870 else {
8871 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8872 if (!data)
8873 return -1;
8874 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008875 }
8876
Benjamin Petersonead6b532011-12-20 17:23:42 -06008877 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008879 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008880 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008881 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008882 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008883 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008884 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008885 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008886 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008887 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008888 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008889 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008891 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008892 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008893 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008894 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008897 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008898 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008899 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008900 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008901 break;
8902 default:
8903 assert(0);
8904 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008906 if (unicode != NULL && thousands_sep_kind != kind) {
8907 if (thousands_sep_kind < kind)
8908 PyMem_Free(thousands_sep_data);
8909 else
8910 PyMem_Free(data);
8911 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008912 if (unicode == NULL) {
8913 *maxchar = 127;
8914 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008915 *maxchar = MAX_MAXCHAR(*maxchar,
8916 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008917 }
8918 }
8919 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920}
8921
8922
Thomas Wouters477c8d52006-05-27 19:21:47 +00008923/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008924#define ADJUST_INDICES(start, end, len) \
8925 if (end > len) \
8926 end = len; \
8927 else if (end < 0) { \
8928 end += len; \
8929 if (end < 0) \
8930 end = 0; \
8931 } \
8932 if (start < 0) { \
8933 start += len; \
8934 if (start < 0) \
8935 start = 0; \
8936 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008937
Alexander Belopolsky40018472011-02-26 01:02:56 +00008938Py_ssize_t
8939PyUnicode_Count(PyObject *str,
8940 PyObject *substr,
8941 Py_ssize_t start,
8942 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008943{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008944 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008945 PyObject* str_obj;
8946 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008947 int kind1, kind2, kind;
8948 void *buf1 = NULL, *buf2 = NULL;
8949 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008950
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008951 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008952 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008953 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008954 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008955 if (!sub_obj) {
8956 Py_DECREF(str_obj);
8957 return -1;
8958 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008959 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008960 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008961 Py_DECREF(str_obj);
8962 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008963 }
Tim Petersced69f82003-09-16 20:30:58 +00008964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008965 kind1 = PyUnicode_KIND(str_obj);
8966 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008967 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008970 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008971 if (kind2 > kind) {
8972 Py_DECREF(sub_obj);
8973 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008974 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008975 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008976 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978 if (!buf2)
8979 goto onError;
8980 len1 = PyUnicode_GET_LENGTH(str_obj);
8981 len2 = PyUnicode_GET_LENGTH(sub_obj);
8982
8983 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008984 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008985 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008986 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8987 result = asciilib_count(
8988 ((Py_UCS1*)buf1) + start, end - start,
8989 buf2, len2, PY_SSIZE_T_MAX
8990 );
8991 else
8992 result = ucs1lib_count(
8993 ((Py_UCS1*)buf1) + start, end - start,
8994 buf2, len2, PY_SSIZE_T_MAX
8995 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008996 break;
8997 case PyUnicode_2BYTE_KIND:
8998 result = ucs2lib_count(
8999 ((Py_UCS2*)buf1) + start, end - start,
9000 buf2, len2, PY_SSIZE_T_MAX
9001 );
9002 break;
9003 case PyUnicode_4BYTE_KIND:
9004 result = ucs4lib_count(
9005 ((Py_UCS4*)buf1) + start, end - start,
9006 buf2, len2, PY_SSIZE_T_MAX
9007 );
9008 break;
9009 default:
9010 assert(0); result = 0;
9011 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009012
9013 Py_DECREF(sub_obj);
9014 Py_DECREF(str_obj);
9015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 if (kind2 != kind)
9017 PyMem_Free(buf2);
9018
Guido van Rossumd57fd912000-03-10 22:53:23 +00009019 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009020 onError:
9021 Py_DECREF(sub_obj);
9022 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009023 if (kind2 != kind && buf2)
9024 PyMem_Free(buf2);
9025 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026}
9027
Alexander Belopolsky40018472011-02-26 01:02:56 +00009028Py_ssize_t
9029PyUnicode_Find(PyObject *str,
9030 PyObject *sub,
9031 Py_ssize_t start,
9032 Py_ssize_t end,
9033 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009035 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009036
Guido van Rossumd57fd912000-03-10 22:53:23 +00009037 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009038 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009039 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009040 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009041 if (!sub) {
9042 Py_DECREF(str);
9043 return -2;
9044 }
9045 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9046 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 Py_DECREF(str);
9048 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009049 }
Tim Petersced69f82003-09-16 20:30:58 +00009050
Victor Stinner794d5672011-10-10 03:21:36 +02009051 result = any_find_slice(direction,
9052 str, sub, start, end
9053 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009054
Guido van Rossumd57fd912000-03-10 22:53:23 +00009055 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009056 Py_DECREF(sub);
9057
Guido van Rossumd57fd912000-03-10 22:53:23 +00009058 return result;
9059}
9060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061Py_ssize_t
9062PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9063 Py_ssize_t start, Py_ssize_t end,
9064 int direction)
9065{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009067 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 if (PyUnicode_READY(str) == -1)
9069 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009070 if (start < 0 || end < 0) {
9071 PyErr_SetString(PyExc_IndexError, "string index out of range");
9072 return -2;
9073 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 if (end > PyUnicode_GET_LENGTH(str))
9075 end = PyUnicode_GET_LENGTH(str);
9076 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009077 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9078 kind, end-start, ch, direction);
9079 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009081 else
9082 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083}
9084
Alexander Belopolsky40018472011-02-26 01:02:56 +00009085static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009086tailmatch(PyObject *self,
9087 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009088 Py_ssize_t start,
9089 Py_ssize_t end,
9090 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009091{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 int kind_self;
9093 int kind_sub;
9094 void *data_self;
9095 void *data_sub;
9096 Py_ssize_t offset;
9097 Py_ssize_t i;
9098 Py_ssize_t end_sub;
9099
9100 if (PyUnicode_READY(self) == -1 ||
9101 PyUnicode_READY(substring) == -1)
9102 return 0;
9103
9104 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009105 return 1;
9106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9108 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009109 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009110 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 kind_self = PyUnicode_KIND(self);
9113 data_self = PyUnicode_DATA(self);
9114 kind_sub = PyUnicode_KIND(substring);
9115 data_sub = PyUnicode_DATA(substring);
9116 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9117
9118 if (direction > 0)
9119 offset = end;
9120 else
9121 offset = start;
9122
9123 if (PyUnicode_READ(kind_self, data_self, offset) ==
9124 PyUnicode_READ(kind_sub, data_sub, 0) &&
9125 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9126 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9127 /* If both are of the same kind, memcmp is sufficient */
9128 if (kind_self == kind_sub) {
9129 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009130 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009131 data_sub,
9132 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009133 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009134 }
9135 /* otherwise we have to compare each character by first accesing it */
9136 else {
9137 /* We do not need to compare 0 and len(substring)-1 because
9138 the if statement above ensured already that they are equal
9139 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009140 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 for (i = 1; i < end_sub; ++i) {
9142 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9143 PyUnicode_READ(kind_sub, data_sub, i))
9144 return 0;
9145 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009146 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009147 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148 }
9149
9150 return 0;
9151}
9152
Alexander Belopolsky40018472011-02-26 01:02:56 +00009153Py_ssize_t
9154PyUnicode_Tailmatch(PyObject *str,
9155 PyObject *substr,
9156 Py_ssize_t start,
9157 Py_ssize_t end,
9158 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009159{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009160 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009161
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162 str = PyUnicode_FromObject(str);
9163 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009164 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165 substr = PyUnicode_FromObject(substr);
9166 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 Py_DECREF(str);
9168 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009169 }
Tim Petersced69f82003-09-16 20:30:58 +00009170
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009171 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009172 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173 Py_DECREF(str);
9174 Py_DECREF(substr);
9175 return result;
9176}
9177
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178/* Apply fixfct filter to the Unicode object self and return a
9179 reference to the modified object */
9180
Alexander Belopolsky40018472011-02-26 01:02:56 +00009181static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009182fixup(PyObject *self,
9183 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009184{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 PyObject *u;
9186 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009187 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009189 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009190 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009191 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009192 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194 /* fix functions return the new maximum character in a string,
9195 if the kind of the resulting unicode object does not change,
9196 everything is fine. Otherwise we need to change the string kind
9197 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009198 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009199
9200 if (maxchar_new == 0) {
9201 /* no changes */;
9202 if (PyUnicode_CheckExact(self)) {
9203 Py_DECREF(u);
9204 Py_INCREF(self);
9205 return self;
9206 }
9207 else
9208 return u;
9209 }
9210
Victor Stinnere6abb482012-05-02 01:15:40 +02009211 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212
Victor Stinnereaab6042011-12-11 22:22:39 +01009213 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009215
9216 /* In case the maximum character changed, we need to
9217 convert the string to the new category. */
9218 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9219 if (v == NULL) {
9220 Py_DECREF(u);
9221 return NULL;
9222 }
9223 if (maxchar_new > maxchar_old) {
9224 /* If the maxchar increased so that the kind changed, not all
9225 characters are representable anymore and we need to fix the
9226 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009227 _PyUnicode_FastCopyCharacters(v, 0,
9228 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009229 maxchar_old = fixfct(v);
9230 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 }
9232 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009233 _PyUnicode_FastCopyCharacters(v, 0,
9234 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009236 Py_DECREF(u);
9237 assert(_PyUnicode_CheckConsistency(v, 1));
9238 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239}
9240
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009241static PyObject *
9242ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009244 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9245 char *resdata, *data = PyUnicode_DATA(self);
9246 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009247
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009248 res = PyUnicode_New(len, 127);
9249 if (res == NULL)
9250 return NULL;
9251 resdata = PyUnicode_DATA(res);
9252 if (lower)
9253 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009255 _Py_bytes_upper(resdata, data, len);
9256 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257}
9258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009260handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009262 Py_ssize_t j;
9263 int final_sigma;
9264 Py_UCS4 c;
9265 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009266
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009267 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9268
9269 where ! is a negation and \p{xxx} is a character with property xxx.
9270 */
9271 for (j = i - 1; j >= 0; j--) {
9272 c = PyUnicode_READ(kind, data, j);
9273 if (!_PyUnicode_IsCaseIgnorable(c))
9274 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009275 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009276 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9277 if (final_sigma) {
9278 for (j = i + 1; j < length; j++) {
9279 c = PyUnicode_READ(kind, data, j);
9280 if (!_PyUnicode_IsCaseIgnorable(c))
9281 break;
9282 }
9283 final_sigma = j == length || !_PyUnicode_IsCased(c);
9284 }
9285 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009286}
9287
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009288static int
9289lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9290 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009292 /* Obscure special case. */
9293 if (c == 0x3A3) {
9294 mapped[0] = handle_capital_sigma(kind, data, length, i);
9295 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009297 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298}
9299
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009300static Py_ssize_t
9301do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009302{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009303 Py_ssize_t i, k = 0;
9304 int n_res, j;
9305 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009306
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009307 c = PyUnicode_READ(kind, data, 0);
9308 n_res = _PyUnicode_ToUpperFull(c, mapped);
9309 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009310 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009311 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009312 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009313 for (i = 1; i < length; i++) {
9314 c = PyUnicode_READ(kind, data, i);
9315 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9316 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009317 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009318 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009319 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009320 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009321 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322}
9323
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009324static Py_ssize_t
9325do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9326 Py_ssize_t i, k = 0;
9327
9328 for (i = 0; i < length; i++) {
9329 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9330 int n_res, j;
9331 if (Py_UNICODE_ISUPPER(c)) {
9332 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9333 }
9334 else if (Py_UNICODE_ISLOWER(c)) {
9335 n_res = _PyUnicode_ToUpperFull(c, mapped);
9336 }
9337 else {
9338 n_res = 1;
9339 mapped[0] = c;
9340 }
9341 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009342 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009343 res[k++] = mapped[j];
9344 }
9345 }
9346 return k;
9347}
9348
9349static Py_ssize_t
9350do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9351 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009353 Py_ssize_t i, k = 0;
9354
9355 for (i = 0; i < length; i++) {
9356 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9357 int n_res, j;
9358 if (lower)
9359 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9360 else
9361 n_res = _PyUnicode_ToUpperFull(c, mapped);
9362 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009363 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009364 res[k++] = mapped[j];
9365 }
9366 }
9367 return k;
9368}
9369
9370static Py_ssize_t
9371do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9372{
9373 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9374}
9375
9376static Py_ssize_t
9377do_lower(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, 1);
9380}
9381
Benjamin Petersone51757f2012-01-12 21:10:29 -05009382static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009383do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9384{
9385 Py_ssize_t i, k = 0;
9386
9387 for (i = 0; i < length; i++) {
9388 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9389 Py_UCS4 mapped[3];
9390 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9391 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009392 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009393 res[k++] = mapped[j];
9394 }
9395 }
9396 return k;
9397}
9398
9399static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009400do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9401{
9402 Py_ssize_t i, k = 0;
9403 int previous_is_cased;
9404
9405 previous_is_cased = 0;
9406 for (i = 0; i < length; i++) {
9407 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9408 Py_UCS4 mapped[3];
9409 int n_res, j;
9410
9411 if (previous_is_cased)
9412 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9413 else
9414 n_res = _PyUnicode_ToTitleFull(c, mapped);
9415
9416 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009417 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009418 res[k++] = mapped[j];
9419 }
9420
9421 previous_is_cased = _PyUnicode_IsCased(c);
9422 }
9423 return k;
9424}
9425
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009426static PyObject *
9427case_operation(PyObject *self,
9428 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9429{
9430 PyObject *res = NULL;
9431 Py_ssize_t length, newlength = 0;
9432 int kind, outkind;
9433 void *data, *outdata;
9434 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9435
Benjamin Petersoneea48462012-01-16 14:28:50 -05009436 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009437
9438 kind = PyUnicode_KIND(self);
9439 data = PyUnicode_DATA(self);
9440 length = PyUnicode_GET_LENGTH(self);
9441 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9442 if (tmp == NULL)
9443 return PyErr_NoMemory();
9444 newlength = perform(kind, data, length, tmp, &maxchar);
9445 res = PyUnicode_New(newlength, maxchar);
9446 if (res == NULL)
9447 goto leave;
9448 tmpend = tmp + newlength;
9449 outdata = PyUnicode_DATA(res);
9450 outkind = PyUnicode_KIND(res);
9451 switch (outkind) {
9452 case PyUnicode_1BYTE_KIND:
9453 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9454 break;
9455 case PyUnicode_2BYTE_KIND:
9456 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9457 break;
9458 case PyUnicode_4BYTE_KIND:
9459 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9460 break;
9461 default:
9462 assert(0);
9463 break;
9464 }
9465 leave:
9466 PyMem_FREE(tmp);
9467 return res;
9468}
9469
Tim Peters8ce9f162004-08-27 01:49:32 +00009470PyObject *
9471PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009474 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009476 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009477 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9478 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009479 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009481 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009483 int use_memcpy;
9484 unsigned char *res_data = NULL, *sep_data = NULL;
9485 PyObject *last_obj;
9486 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487
Tim Peters05eba1f2004-08-27 21:32:02 +00009488 fseq = PySequence_Fast(seq, "");
9489 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009490 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009491 }
9492
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009493 /* NOTE: the following code can't call back into Python code,
9494 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009495 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009496
Tim Peters05eba1f2004-08-27 21:32:02 +00009497 seqlen = PySequence_Fast_GET_SIZE(fseq);
9498 /* If empty sequence, return u"". */
9499 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009500 Py_DECREF(fseq);
9501 Py_INCREF(unicode_empty);
9502 res = unicode_empty;
9503 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009504 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009505
Tim Peters05eba1f2004-08-27 21:32:02 +00009506 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009507 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009508 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009509 if (seqlen == 1) {
9510 if (PyUnicode_CheckExact(items[0])) {
9511 res = items[0];
9512 Py_INCREF(res);
9513 Py_DECREF(fseq);
9514 return res;
9515 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009516 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009517 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009518 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009519 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009520 /* Set up sep and seplen */
9521 if (separator == NULL) {
9522 /* fall back to a blank space separator */
9523 sep = PyUnicode_FromOrdinal(' ');
9524 if (!sep)
9525 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009526 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009527 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009528 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009529 else {
9530 if (!PyUnicode_Check(separator)) {
9531 PyErr_Format(PyExc_TypeError,
9532 "separator: expected str instance,"
9533 " %.80s found",
9534 Py_TYPE(separator)->tp_name);
9535 goto onError;
9536 }
9537 if (PyUnicode_READY(separator))
9538 goto onError;
9539 sep = separator;
9540 seplen = PyUnicode_GET_LENGTH(separator);
9541 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9542 /* inc refcount to keep this code path symmetric with the
9543 above case of a blank separator */
9544 Py_INCREF(sep);
9545 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009546 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009547 }
9548
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009549 /* There are at least two things to join, or else we have a subclass
9550 * of str in the sequence.
9551 * Do a pre-pass to figure out the total amount of space we'll
9552 * need (sz), and see whether all argument are strings.
9553 */
9554 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009555#ifdef Py_DEBUG
9556 use_memcpy = 0;
9557#else
9558 use_memcpy = 1;
9559#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009560 for (i = 0; i < seqlen; i++) {
9561 const Py_ssize_t old_sz = sz;
9562 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009563 if (!PyUnicode_Check(item)) {
9564 PyErr_Format(PyExc_TypeError,
9565 "sequence item %zd: expected str instance,"
9566 " %.80s found",
9567 i, Py_TYPE(item)->tp_name);
9568 goto onError;
9569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570 if (PyUnicode_READY(item) == -1)
9571 goto onError;
9572 sz += PyUnicode_GET_LENGTH(item);
9573 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009574 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009575 if (i != 0)
9576 sz += seplen;
9577 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9578 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009579 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009580 goto onError;
9581 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009582 if (use_memcpy && last_obj != NULL) {
9583 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9584 use_memcpy = 0;
9585 }
9586 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009587 }
Tim Petersced69f82003-09-16 20:30:58 +00009588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009590 if (res == NULL)
9591 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009592
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009593 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009594#ifdef Py_DEBUG
9595 use_memcpy = 0;
9596#else
9597 if (use_memcpy) {
9598 res_data = PyUnicode_1BYTE_DATA(res);
9599 kind = PyUnicode_KIND(res);
9600 if (seplen != 0)
9601 sep_data = PyUnicode_1BYTE_DATA(sep);
9602 }
9603#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009604 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009605 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009606 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009607 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009608 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009609 if (use_memcpy) {
9610 Py_MEMCPY(res_data,
9611 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009612 kind * seplen);
9613 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009614 }
9615 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009616 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009617 res_offset += seplen;
9618 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009619 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009620 itemlen = PyUnicode_GET_LENGTH(item);
9621 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009622 if (use_memcpy) {
9623 Py_MEMCPY(res_data,
9624 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009625 kind * itemlen);
9626 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009627 }
9628 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009629 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009630 res_offset += itemlen;
9631 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009632 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009633 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009634 if (use_memcpy)
9635 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009636 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009637 else
9638 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009639
Tim Peters05eba1f2004-08-27 21:32:02 +00009640 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009642 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009643 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009644
Benjamin Peterson29060642009-01-31 22:14:21 +00009645 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009646 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009648 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009649 return NULL;
9650}
9651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009652#define FILL(kind, data, value, start, length) \
9653 do { \
9654 Py_ssize_t i_ = 0; \
9655 assert(kind != PyUnicode_WCHAR_KIND); \
9656 switch ((kind)) { \
9657 case PyUnicode_1BYTE_KIND: { \
9658 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009659 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 break; \
9661 } \
9662 case PyUnicode_2BYTE_KIND: { \
9663 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9664 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9665 break; \
9666 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009667 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9669 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9670 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009671 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009672 } \
9673 } \
9674 } while (0)
9675
Victor Stinnerd3f08822012-05-29 12:57:52 +02009676void
9677_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9678 Py_UCS4 fill_char)
9679{
9680 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9681 const void *data = PyUnicode_DATA(unicode);
9682 assert(PyUnicode_IS_READY(unicode));
9683 assert(unicode_modifiable(unicode));
9684 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9685 assert(start >= 0);
9686 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9687 FILL(kind, data, fill_char, start, length);
9688}
9689
Victor Stinner3fe55312012-01-04 00:33:50 +01009690Py_ssize_t
9691PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9692 Py_UCS4 fill_char)
9693{
9694 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009695
9696 if (!PyUnicode_Check(unicode)) {
9697 PyErr_BadInternalCall();
9698 return -1;
9699 }
9700 if (PyUnicode_READY(unicode) == -1)
9701 return -1;
9702 if (unicode_check_modifiable(unicode))
9703 return -1;
9704
Victor Stinnerd3f08822012-05-29 12:57:52 +02009705 if (start < 0) {
9706 PyErr_SetString(PyExc_IndexError, "string index out of range");
9707 return -1;
9708 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009709 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9710 PyErr_SetString(PyExc_ValueError,
9711 "fill character is bigger than "
9712 "the string maximum character");
9713 return -1;
9714 }
9715
9716 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9717 length = Py_MIN(maxlen, length);
9718 if (length <= 0)
9719 return 0;
9720
Victor Stinnerd3f08822012-05-29 12:57:52 +02009721 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009722 return length;
9723}
9724
Victor Stinner9310abb2011-10-05 00:59:23 +02009725static PyObject *
9726pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009727 Py_ssize_t left,
9728 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009729 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009730{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731 PyObject *u;
9732 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009733 int kind;
9734 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009735
9736 if (left < 0)
9737 left = 0;
9738 if (right < 0)
9739 right = 0;
9740
Victor Stinnerc4b49542011-12-11 22:44:26 +01009741 if (left == 0 && right == 0)
9742 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009744 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9745 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009746 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9747 return NULL;
9748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009750 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009752 if (!u)
9753 return NULL;
9754
9755 kind = PyUnicode_KIND(u);
9756 data = PyUnicode_DATA(u);
9757 if (left)
9758 FILL(kind, data, fill, 0, left);
9759 if (right)
9760 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009761 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009762 assert(_PyUnicode_CheckConsistency(u, 1));
9763 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764}
9765
Alexander Belopolsky40018472011-02-26 01:02:56 +00009766PyObject *
9767PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009769 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770
9771 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009772 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009773 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009774 if (PyUnicode_READY(string) == -1) {
9775 Py_DECREF(string);
9776 return NULL;
9777 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009778
Benjamin Petersonead6b532011-12-20 17:23:42 -06009779 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009781 if (PyUnicode_IS_ASCII(string))
9782 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009783 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009784 PyUnicode_GET_LENGTH(string), keepends);
9785 else
9786 list = ucs1lib_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);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009789 break;
9790 case PyUnicode_2BYTE_KIND:
9791 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009792 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009793 PyUnicode_GET_LENGTH(string), keepends);
9794 break;
9795 case PyUnicode_4BYTE_KIND:
9796 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009797 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 PyUnicode_GET_LENGTH(string), keepends);
9799 break;
9800 default:
9801 assert(0);
9802 list = 0;
9803 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804 Py_DECREF(string);
9805 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806}
9807
Alexander Belopolsky40018472011-02-26 01:02:56 +00009808static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009809split(PyObject *self,
9810 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009811 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 int kind1, kind2, kind;
9814 void *buf1, *buf2;
9815 Py_ssize_t len1, len2;
9816 PyObject* out;
9817
Guido van Rossumd57fd912000-03-10 22:53:23 +00009818 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009819 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 if (PyUnicode_READY(self) == -1)
9822 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009823
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009825 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009827 if (PyUnicode_IS_ASCII(self))
9828 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009829 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009830 PyUnicode_GET_LENGTH(self), maxcount
9831 );
9832 else
9833 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009834 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009835 PyUnicode_GET_LENGTH(self), maxcount
9836 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 case PyUnicode_2BYTE_KIND:
9838 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009839 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009840 PyUnicode_GET_LENGTH(self), maxcount
9841 );
9842 case PyUnicode_4BYTE_KIND:
9843 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009844 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 PyUnicode_GET_LENGTH(self), maxcount
9846 );
9847 default:
9848 assert(0);
9849 return NULL;
9850 }
9851
9852 if (PyUnicode_READY(substring) == -1)
9853 return NULL;
9854
9855 kind1 = PyUnicode_KIND(self);
9856 kind2 = PyUnicode_KIND(substring);
9857 kind = kind1 > kind2 ? kind1 : kind2;
9858 buf1 = PyUnicode_DATA(self);
9859 buf2 = PyUnicode_DATA(substring);
9860 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009861 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 if (!buf1)
9863 return NULL;
9864 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009865 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 if (!buf2) {
9867 if (kind1 != kind) PyMem_Free(buf1);
9868 return NULL;
9869 }
9870 len1 = PyUnicode_GET_LENGTH(self);
9871 len2 = PyUnicode_GET_LENGTH(substring);
9872
Benjamin Petersonead6b532011-12-20 17:23:42 -06009873 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009875 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9876 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009877 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009878 else
9879 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009880 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 break;
9882 case PyUnicode_2BYTE_KIND:
9883 out = ucs2lib_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_4BYTE_KIND:
9887 out = ucs4lib_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 default:
9891 out = NULL;
9892 }
9893 if (kind1 != kind)
9894 PyMem_Free(buf1);
9895 if (kind2 != kind)
9896 PyMem_Free(buf2);
9897 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009898}
9899
Alexander Belopolsky40018472011-02-26 01:02:56 +00009900static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009901rsplit(PyObject *self,
9902 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009903 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009904{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 int kind1, kind2, kind;
9906 void *buf1, *buf2;
9907 Py_ssize_t len1, len2;
9908 PyObject* out;
9909
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009910 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009911 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009912
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 if (PyUnicode_READY(self) == -1)
9914 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009917 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009919 if (PyUnicode_IS_ASCII(self))
9920 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009921 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009922 PyUnicode_GET_LENGTH(self), maxcount
9923 );
9924 else
9925 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009926 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009927 PyUnicode_GET_LENGTH(self), maxcount
9928 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009929 case PyUnicode_2BYTE_KIND:
9930 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009931 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 PyUnicode_GET_LENGTH(self), maxcount
9933 );
9934 case PyUnicode_4BYTE_KIND:
9935 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009936 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 PyUnicode_GET_LENGTH(self), maxcount
9938 );
9939 default:
9940 assert(0);
9941 return NULL;
9942 }
9943
9944 if (PyUnicode_READY(substring) == -1)
9945 return NULL;
9946
9947 kind1 = PyUnicode_KIND(self);
9948 kind2 = PyUnicode_KIND(substring);
9949 kind = kind1 > kind2 ? kind1 : kind2;
9950 buf1 = PyUnicode_DATA(self);
9951 buf2 = PyUnicode_DATA(substring);
9952 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009953 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954 if (!buf1)
9955 return NULL;
9956 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009957 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 if (!buf2) {
9959 if (kind1 != kind) PyMem_Free(buf1);
9960 return NULL;
9961 }
9962 len1 = PyUnicode_GET_LENGTH(self);
9963 len2 = PyUnicode_GET_LENGTH(substring);
9964
Benjamin Petersonead6b532011-12-20 17:23:42 -06009965 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009967 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9968 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009969 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009970 else
9971 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009972 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 break;
9974 case PyUnicode_2BYTE_KIND:
9975 out = ucs2lib_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_4BYTE_KIND:
9979 out = ucs4lib_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 default:
9983 out = NULL;
9984 }
9985 if (kind1 != kind)
9986 PyMem_Free(buf1);
9987 if (kind2 != kind)
9988 PyMem_Free(buf2);
9989 return out;
9990}
9991
9992static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009993anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9994 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009996 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009998 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9999 return asciilib_find(buf1, len1, buf2, len2, offset);
10000 else
10001 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 case PyUnicode_2BYTE_KIND:
10003 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10004 case PyUnicode_4BYTE_KIND:
10005 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10006 }
10007 assert(0);
10008 return -1;
10009}
10010
10011static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010012anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10013 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010015 switch (kind) {
10016 case PyUnicode_1BYTE_KIND:
10017 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10018 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10019 else
10020 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10021 case PyUnicode_2BYTE_KIND:
10022 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10023 case PyUnicode_4BYTE_KIND:
10024 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10025 }
10026 assert(0);
10027 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010028}
10029
Alexander Belopolsky40018472011-02-26 01:02:56 +000010030static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031replace(PyObject *self, PyObject *str1,
10032 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 PyObject *u;
10035 char *sbuf = PyUnicode_DATA(self);
10036 char *buf1 = PyUnicode_DATA(str1);
10037 char *buf2 = PyUnicode_DATA(str2);
10038 int srelease = 0, release1 = 0, release2 = 0;
10039 int skind = PyUnicode_KIND(self);
10040 int kind1 = PyUnicode_KIND(str1);
10041 int kind2 = PyUnicode_KIND(str2);
10042 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10043 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10044 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010045 int mayshrink;
10046 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047
10048 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010049 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010051 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010052
Victor Stinner59de0ee2011-10-07 10:01:28 +020010053 if (str1 == str2)
10054 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 if (skind < kind1)
10056 /* substring too wide to be present */
10057 goto nothing;
10058
Victor Stinner49a0a212011-10-12 23:46:10 +020010059 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10060 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10061 /* Replacing str1 with str2 may cause a maxchar reduction in the
10062 result string. */
10063 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010064 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010067 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010069 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010071 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010072 Py_UCS4 u1, u2;
10073 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010074 Py_ssize_t index, pos;
10075 char *src;
10076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010078 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10079 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010080 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010081 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010083 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010085 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010087
10088 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10089 index = 0;
10090 src = sbuf;
10091 while (--maxcount)
10092 {
10093 pos++;
10094 src += pos * PyUnicode_KIND(self);
10095 slen -= pos;
10096 index += pos;
10097 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10098 if (pos < 0)
10099 break;
10100 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10101 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010102 }
10103 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 int rkind = skind;
10105 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010106 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 if (kind1 < rkind) {
10109 /* widen substring */
10110 buf1 = _PyUnicode_AsKind(str1, rkind);
10111 if (!buf1) goto error;
10112 release1 = 1;
10113 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010114 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010115 if (i < 0)
10116 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 if (rkind > kind2) {
10118 /* widen replacement */
10119 buf2 = _PyUnicode_AsKind(str2, rkind);
10120 if (!buf2) goto error;
10121 release2 = 1;
10122 }
10123 else if (rkind < kind2) {
10124 /* widen self and buf1 */
10125 rkind = kind2;
10126 if (release1) PyMem_Free(buf1);
10127 sbuf = _PyUnicode_AsKind(self, rkind);
10128 if (!sbuf) goto error;
10129 srelease = 1;
10130 buf1 = _PyUnicode_AsKind(str1, rkind);
10131 if (!buf1) goto error;
10132 release1 = 1;
10133 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010134 u = PyUnicode_New(slen, maxchar);
10135 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010137 assert(PyUnicode_KIND(u) == rkind);
10138 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010139
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010140 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010141 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010142 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010144 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010146
10147 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010149 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010151 if (i == -1)
10152 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010153 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010155 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010157 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010158 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010159 }
10160 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 Py_ssize_t n, i, j, ires;
10162 Py_ssize_t product, new_size;
10163 int rkind = skind;
10164 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010167 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 buf1 = _PyUnicode_AsKind(str1, rkind);
10169 if (!buf1) goto error;
10170 release1 = 1;
10171 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010172 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010173 if (n == 0)
10174 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010176 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 buf2 = _PyUnicode_AsKind(str2, rkind);
10178 if (!buf2) goto error;
10179 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010180 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010182 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 rkind = kind2;
10184 sbuf = _PyUnicode_AsKind(self, rkind);
10185 if (!sbuf) goto error;
10186 srelease = 1;
10187 if (release1) PyMem_Free(buf1);
10188 buf1 = _PyUnicode_AsKind(str1, rkind);
10189 if (!buf1) goto error;
10190 release1 = 1;
10191 }
10192 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10193 PyUnicode_GET_LENGTH(str1))); */
10194 product = n * (len2-len1);
10195 if ((product / (len2-len1)) != n) {
10196 PyErr_SetString(PyExc_OverflowError,
10197 "replace string is too long");
10198 goto error;
10199 }
10200 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010201 if (new_size == 0) {
10202 Py_INCREF(unicode_empty);
10203 u = unicode_empty;
10204 goto done;
10205 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10207 PyErr_SetString(PyExc_OverflowError,
10208 "replace string is too long");
10209 goto error;
10210 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010211 u = PyUnicode_New(new_size, maxchar);
10212 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010214 assert(PyUnicode_KIND(u) == rkind);
10215 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 ires = i = 0;
10217 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010218 while (n-- > 0) {
10219 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010220 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010221 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010223 if (j == -1)
10224 break;
10225 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010226 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010227 memcpy(res + rkind * ires,
10228 sbuf + rkind * i,
10229 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010231 }
10232 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010234 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010236 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010243 memcpy(res + rkind * ires,
10244 sbuf + rkind * i,
10245 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010246 }
10247 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010248 /* interleave */
10249 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010250 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010252 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010254 if (--n <= 0)
10255 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010256 memcpy(res + rkind * ires,
10257 sbuf + rkind * i,
10258 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 ires++;
10260 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010262 memcpy(res + rkind * ires,
10263 sbuf + rkind * i,
10264 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010265 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010266 }
10267
10268 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010269 unicode_adjust_maxchar(&u);
10270 if (u == NULL)
10271 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010272 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010273
10274 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 if (srelease)
10276 PyMem_FREE(sbuf);
10277 if (release1)
10278 PyMem_FREE(buf1);
10279 if (release2)
10280 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010281 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010283
Benjamin Peterson29060642009-01-31 22:14:21 +000010284 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010285 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 if (srelease)
10287 PyMem_FREE(sbuf);
10288 if (release1)
10289 PyMem_FREE(buf1);
10290 if (release2)
10291 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010292 return unicode_result_unchanged(self);
10293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 error:
10295 if (srelease && sbuf)
10296 PyMem_FREE(sbuf);
10297 if (release1 && buf1)
10298 PyMem_FREE(buf1);
10299 if (release2 && buf2)
10300 PyMem_FREE(buf2);
10301 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302}
10303
10304/* --- Unicode Object Methods --------------------------------------------- */
10305
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010306PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010307 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010308\n\
10309Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010310characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311
10312static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010313unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010314{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010315 if (PyUnicode_READY(self) == -1)
10316 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010317 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318}
10319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010320PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010321 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322\n\
10323Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010324have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325
10326static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010327unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010328{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010329 if (PyUnicode_READY(self) == -1)
10330 return NULL;
10331 if (PyUnicode_GET_LENGTH(self) == 0)
10332 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010333 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010334}
10335
Benjamin Petersond5890c82012-01-14 13:23:30 -050010336PyDoc_STRVAR(casefold__doc__,
10337 "S.casefold() -> str\n\
10338\n\
10339Return a version of S suitable for caseless comparisons.");
10340
10341static PyObject *
10342unicode_casefold(PyObject *self)
10343{
10344 if (PyUnicode_READY(self) == -1)
10345 return NULL;
10346 if (PyUnicode_IS_ASCII(self))
10347 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010348 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010349}
10350
10351
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010352/* Argument converter. Coerces to a single unicode character */
10353
10354static int
10355convert_uc(PyObject *obj, void *addr)
10356{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010358 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010359
Benjamin Peterson14339b62009-01-31 16:36:08 +000010360 uniobj = PyUnicode_FromObject(obj);
10361 if (uniobj == NULL) {
10362 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010363 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010364 return 0;
10365 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010367 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010368 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010369 Py_DECREF(uniobj);
10370 return 0;
10371 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010373 Py_DECREF(uniobj);
10374 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010375}
10376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010377PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010378 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010380Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010381done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382
10383static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010384unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010386 Py_ssize_t marg, left;
10387 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 Py_UCS4 fillchar = ' ';
10389
Victor Stinnere9a29352011-10-01 02:14:59 +020010390 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392
Benjamin Petersonbac79492012-01-14 13:34:47 -050010393 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394 return NULL;
10395
Victor Stinnerc4b49542011-12-11 22:44:26 +010010396 if (PyUnicode_GET_LENGTH(self) >= width)
10397 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398
Victor Stinnerc4b49542011-12-11 22:44:26 +010010399 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400 left = marg / 2 + (marg & width & 1);
10401
Victor Stinner9310abb2011-10-05 00:59:23 +020010402 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403}
10404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405/* This function assumes that str1 and str2 are readied by the caller. */
10406
Marc-André Lemburge5034372000-08-08 08:04:29 +000010407static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010408unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010409{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 int kind1, kind2;
10411 void *data1, *data2;
10412 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 kind1 = PyUnicode_KIND(str1);
10415 kind2 = PyUnicode_KIND(str2);
10416 data1 = PyUnicode_DATA(str1);
10417 data2 = PyUnicode_DATA(str2);
10418 len1 = PyUnicode_GET_LENGTH(str1);
10419 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 for (i = 0; i < len1 && i < len2; ++i) {
10422 Py_UCS4 c1, c2;
10423 c1 = PyUnicode_READ(kind1, data1, i);
10424 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010425
10426 if (c1 != c2)
10427 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010428 }
10429
10430 return (len1 < len2) ? -1 : (len1 != len2);
10431}
10432
Alexander Belopolsky40018472011-02-26 01:02:56 +000010433int
10434PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10437 if (PyUnicode_READY(left) == -1 ||
10438 PyUnicode_READY(right) == -1)
10439 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010440 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010442 PyErr_Format(PyExc_TypeError,
10443 "Can't compare %.100s and %.100s",
10444 left->ob_type->tp_name,
10445 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010446 return -1;
10447}
10448
Martin v. Löwis5b222132007-06-10 09:51:05 +000010449int
10450PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 Py_ssize_t i;
10453 int kind;
10454 void *data;
10455 Py_UCS4 chr;
10456
Victor Stinner910337b2011-10-03 03:20:16 +020010457 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 if (PyUnicode_READY(uni) == -1)
10459 return -1;
10460 kind = PyUnicode_KIND(uni);
10461 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010462 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10464 if (chr != str[i])
10465 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010466 /* This check keeps Python strings that end in '\0' from comparing equal
10467 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010469 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010470 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010471 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010472 return 0;
10473}
10474
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010475
Benjamin Peterson29060642009-01-31 22:14:21 +000010476#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010477 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010478
Alexander Belopolsky40018472011-02-26 01:02:56 +000010479PyObject *
10480PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010481{
10482 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010483
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010484 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10485 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (PyUnicode_READY(left) == -1 ||
10487 PyUnicode_READY(right) == -1)
10488 return NULL;
10489 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10490 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010491 if (op == Py_EQ) {
10492 Py_INCREF(Py_False);
10493 return Py_False;
10494 }
10495 if (op == Py_NE) {
10496 Py_INCREF(Py_True);
10497 return Py_True;
10498 }
10499 }
10500 if (left == right)
10501 result = 0;
10502 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010503 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010504
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010505 /* Convert the return value to a Boolean */
10506 switch (op) {
10507 case Py_EQ:
10508 v = TEST_COND(result == 0);
10509 break;
10510 case Py_NE:
10511 v = TEST_COND(result != 0);
10512 break;
10513 case Py_LE:
10514 v = TEST_COND(result <= 0);
10515 break;
10516 case Py_GE:
10517 v = TEST_COND(result >= 0);
10518 break;
10519 case Py_LT:
10520 v = TEST_COND(result == -1);
10521 break;
10522 case Py_GT:
10523 v = TEST_COND(result == 1);
10524 break;
10525 default:
10526 PyErr_BadArgument();
10527 return NULL;
10528 }
10529 Py_INCREF(v);
10530 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010531 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010532
Brian Curtindfc80e32011-08-10 20:28:54 -050010533 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010534}
10535
Alexander Belopolsky40018472011-02-26 01:02:56 +000010536int
10537PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010538{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010539 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 int kind1, kind2, kind;
10541 void *buf1, *buf2;
10542 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010543 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010544
10545 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010546 sub = PyUnicode_FromObject(element);
10547 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010548 PyErr_Format(PyExc_TypeError,
10549 "'in <string>' requires string as left operand, not %s",
10550 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010551 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010552 }
10553
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010555 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010556 Py_DECREF(sub);
10557 return -1;
10558 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010559 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10560 Py_DECREF(sub);
10561 Py_DECREF(str);
10562 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010563
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 kind1 = PyUnicode_KIND(str);
10565 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010566 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 buf1 = PyUnicode_DATA(str);
10568 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010569 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010570 if (kind2 > kind) {
10571 Py_DECREF(sub);
10572 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010573 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010574 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010575 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010576 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 if (!buf2) {
10578 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010579 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 return -1;
10581 }
10582 len1 = PyUnicode_GET_LENGTH(str);
10583 len2 = PyUnicode_GET_LENGTH(sub);
10584
Benjamin Petersonead6b532011-12-20 17:23:42 -060010585 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 case PyUnicode_1BYTE_KIND:
10587 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10588 break;
10589 case PyUnicode_2BYTE_KIND:
10590 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10591 break;
10592 case PyUnicode_4BYTE_KIND:
10593 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10594 break;
10595 default:
10596 result = -1;
10597 assert(0);
10598 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010599
10600 Py_DECREF(str);
10601 Py_DECREF(sub);
10602
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (kind2 != kind)
10604 PyMem_Free(buf2);
10605
Guido van Rossum403d68b2000-03-13 15:55:09 +000010606 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010607}
10608
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609/* Concat to string or Unicode object giving a new Unicode object. */
10610
Alexander Belopolsky40018472011-02-26 01:02:56 +000010611PyObject *
10612PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010615 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010616 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617
10618 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010621 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010623 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010624 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625
10626 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010627 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010628 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010631 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010632 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634 }
10635
Victor Stinner488fa492011-12-12 00:01:39 +010010636 u_len = PyUnicode_GET_LENGTH(u);
10637 v_len = PyUnicode_GET_LENGTH(v);
10638 if (u_len > PY_SSIZE_T_MAX - v_len) {
10639 PyErr_SetString(PyExc_OverflowError,
10640 "strings are too large to concat");
10641 goto onError;
10642 }
10643 new_len = u_len + v_len;
10644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010646 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010647 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648
Guido van Rossumd57fd912000-03-10 22:53:23 +000010649 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010650 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010652 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010653 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10654 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010655 Py_DECREF(u);
10656 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010657 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010659
Benjamin Peterson29060642009-01-31 22:14:21 +000010660 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661 Py_XDECREF(u);
10662 Py_XDECREF(v);
10663 return NULL;
10664}
10665
Walter Dörwald1ab83302007-05-18 17:15:44 +000010666void
Victor Stinner23e56682011-10-03 03:54:37 +020010667PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010668{
Victor Stinner23e56682011-10-03 03:54:37 +020010669 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010670 Py_UCS4 maxchar, maxchar2;
10671 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010672
10673 if (p_left == NULL) {
10674 if (!PyErr_Occurred())
10675 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010676 return;
10677 }
Victor Stinner23e56682011-10-03 03:54:37 +020010678 left = *p_left;
10679 if (right == NULL || !PyUnicode_Check(left)) {
10680 if (!PyErr_Occurred())
10681 PyErr_BadInternalCall();
10682 goto error;
10683 }
10684
Benjamin Petersonbac79492012-01-14 13:34:47 -050010685 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010686 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010687 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010688 goto error;
10689
Victor Stinner488fa492011-12-12 00:01:39 +010010690 /* Shortcuts */
10691 if (left == unicode_empty) {
10692 Py_DECREF(left);
10693 Py_INCREF(right);
10694 *p_left = right;
10695 return;
10696 }
10697 if (right == unicode_empty)
10698 return;
10699
10700 left_len = PyUnicode_GET_LENGTH(left);
10701 right_len = PyUnicode_GET_LENGTH(right);
10702 if (left_len > PY_SSIZE_T_MAX - right_len) {
10703 PyErr_SetString(PyExc_OverflowError,
10704 "strings are too large to concat");
10705 goto error;
10706 }
10707 new_len = left_len + right_len;
10708
10709 if (unicode_modifiable(left)
10710 && PyUnicode_CheckExact(right)
10711 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010712 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10713 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010714 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010715 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010716 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10717 {
10718 /* append inplace */
10719 if (unicode_resize(p_left, new_len) != 0) {
10720 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10721 * deallocated so it cannot be put back into
10722 * 'variable'. The MemoryError is raised when there
10723 * is no value in 'variable', which might (very
10724 * remotely) be a cause of incompatibilities.
10725 */
10726 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010727 }
Victor Stinner488fa492011-12-12 00:01:39 +010010728 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010729 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010730 }
Victor Stinner488fa492011-12-12 00:01:39 +010010731 else {
10732 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10733 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010734 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010735
Victor Stinner488fa492011-12-12 00:01:39 +010010736 /* Concat the two Unicode strings */
10737 res = PyUnicode_New(new_len, maxchar);
10738 if (res == NULL)
10739 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010740 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10741 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010742 Py_DECREF(left);
10743 *p_left = res;
10744 }
10745 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010746 return;
10747
10748error:
Victor Stinner488fa492011-12-12 00:01:39 +010010749 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010750}
10751
10752void
10753PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10754{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010755 PyUnicode_Append(pleft, right);
10756 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010757}
10758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010759PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010760 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010762Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010763string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010764interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765
10766static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010767unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010769 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010770 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010771 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 int kind1, kind2, kind;
10774 void *buf1, *buf2;
10775 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776
Jesus Ceaac451502011-04-20 17:09:23 +020010777 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10778 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010779 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781 kind1 = PyUnicode_KIND(self);
10782 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010783 if (kind2 > kind1)
10784 return PyLong_FromLong(0);
10785 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 buf1 = PyUnicode_DATA(self);
10787 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010789 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010790 if (!buf2) {
10791 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 return NULL;
10793 }
10794 len1 = PyUnicode_GET_LENGTH(self);
10795 len2 = PyUnicode_GET_LENGTH(substring);
10796
10797 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010798 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 case PyUnicode_1BYTE_KIND:
10800 iresult = ucs1lib_count(
10801 ((Py_UCS1*)buf1) + start, end - start,
10802 buf2, len2, PY_SSIZE_T_MAX
10803 );
10804 break;
10805 case PyUnicode_2BYTE_KIND:
10806 iresult = ucs2lib_count(
10807 ((Py_UCS2*)buf1) + start, end - start,
10808 buf2, len2, PY_SSIZE_T_MAX
10809 );
10810 break;
10811 case PyUnicode_4BYTE_KIND:
10812 iresult = ucs4lib_count(
10813 ((Py_UCS4*)buf1) + start, end - start,
10814 buf2, len2, PY_SSIZE_T_MAX
10815 );
10816 break;
10817 default:
10818 assert(0); iresult = 0;
10819 }
10820
10821 result = PyLong_FromSsize_t(iresult);
10822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 if (kind2 != kind)
10824 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825
10826 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010827
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828 return result;
10829}
10830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010831PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010832 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010834Encode S using the codec registered for encoding. Default encoding\n\
10835is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010836handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010837a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10838'xmlcharrefreplace' as well as any other name registered with\n\
10839codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840
10841static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010842unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010844 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845 char *encoding = NULL;
10846 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010847
Benjamin Peterson308d6372009-09-18 21:42:35 +000010848 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10849 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010851 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010852}
10853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010854PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010855 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856\n\
10857Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010858If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859
10860static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010861unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010863 Py_ssize_t i, j, line_pos, src_len, incr;
10864 Py_UCS4 ch;
10865 PyObject *u;
10866 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010868 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010869 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010870
10871 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010872 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010873
Antoine Pitrou22425222011-10-04 19:10:51 +020010874 if (PyUnicode_READY(self) == -1)
10875 return NULL;
10876
Thomas Wouters7e474022000-07-16 12:04:32 +000010877 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010878 src_len = PyUnicode_GET_LENGTH(self);
10879 i = j = line_pos = 0;
10880 kind = PyUnicode_KIND(self);
10881 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010882 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010883 for (; i < src_len; i++) {
10884 ch = PyUnicode_READ(kind, src_data, i);
10885 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010886 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010887 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010888 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010889 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 goto overflow;
10891 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010892 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010893 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010895 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010896 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010897 goto overflow;
10898 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010900 if (ch == '\n' || ch == '\r')
10901 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010902 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010903 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010904 if (!found)
10905 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010906
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010908 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909 if (!u)
10910 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010911 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912
Antoine Pitroue71d5742011-10-04 15:55:09 +020010913 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914
Antoine Pitroue71d5742011-10-04 15:55:09 +020010915 for (; i < src_len; i++) {
10916 ch = PyUnicode_READ(kind, src_data, i);
10917 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010919 incr = tabsize - (line_pos % tabsize);
10920 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010921 FILL(kind, dest_data, ' ', j, incr);
10922 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010923 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010924 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010925 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010926 line_pos++;
10927 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010928 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010929 if (ch == '\n' || ch == '\r')
10930 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010932 }
10933 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010934 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010935
Antoine Pitroue71d5742011-10-04 15:55:09 +020010936 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010937 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10938 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939}
10940
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010941PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010942 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943\n\
10944Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010945such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946arguments start and end are interpreted as in slice notation.\n\
10947\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010948Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949
10950static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010951unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010953 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010954 Py_ssize_t start;
10955 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010956 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957
Jesus Ceaac451502011-04-20 17:09:23 +020010958 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10959 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 if (PyUnicode_READY(self) == -1)
10963 return NULL;
10964 if (PyUnicode_READY(substring) == -1)
10965 return NULL;
10966
Victor Stinner7931d9a2011-11-04 00:22:48 +010010967 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968
10969 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010971 if (result == -2)
10972 return NULL;
10973
Christian Heimes217cfd12007-12-02 14:31:20 +000010974 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975}
10976
10977static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010978unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010980 void *data;
10981 enum PyUnicode_Kind kind;
10982 Py_UCS4 ch;
10983 PyObject *res;
10984
10985 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10986 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010988 }
10989 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10990 PyErr_SetString(PyExc_IndexError, "string index out of range");
10991 return NULL;
10992 }
10993 kind = PyUnicode_KIND(self);
10994 data = PyUnicode_DATA(self);
10995 ch = PyUnicode_READ(kind, data, index);
10996 if (ch < 256)
10997 return get_latin1_char(ch);
10998
10999 res = PyUnicode_New(1, ch);
11000 if (res == NULL)
11001 return NULL;
11002 kind = PyUnicode_KIND(res);
11003 data = PyUnicode_DATA(res);
11004 PyUnicode_WRITE(kind, data, 0, ch);
11005 assert(_PyUnicode_CheckConsistency(res, 1));
11006 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007}
11008
Guido van Rossumc2504932007-09-18 19:42:40 +000011009/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011010 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011011static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011012unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013{
Guido van Rossumc2504932007-09-18 19:42:40 +000011014 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011015 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011016
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011017#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011018 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011019#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011020 if (_PyUnicode_HASH(self) != -1)
11021 return _PyUnicode_HASH(self);
11022 if (PyUnicode_READY(self) == -1)
11023 return -1;
11024 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011025 /*
11026 We make the hash of the empty string be 0, rather than using
11027 (prefix ^ suffix), since this slightly obfuscates the hash secret
11028 */
11029 if (len == 0) {
11030 _PyUnicode_HASH(self) = 0;
11031 return 0;
11032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033
11034 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011035#define HASH(P) \
11036 x ^= (Py_uhash_t) *P << 7; \
11037 while (--len >= 0) \
11038 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039
Georg Brandl2fb477c2012-02-21 00:33:36 +010011040 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011041 switch (PyUnicode_KIND(self)) {
11042 case PyUnicode_1BYTE_KIND: {
11043 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11044 HASH(c);
11045 break;
11046 }
11047 case PyUnicode_2BYTE_KIND: {
11048 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11049 HASH(s);
11050 break;
11051 }
11052 default: {
11053 Py_UCS4 *l;
11054 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11055 "Impossible switch case in unicode_hash");
11056 l = PyUnicode_4BYTE_DATA(self);
11057 HASH(l);
11058 break;
11059 }
11060 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011061 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11062 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011063
Guido van Rossumc2504932007-09-18 19:42:40 +000011064 if (x == -1)
11065 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011067 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011071PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011072 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011074Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075
11076static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011077unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011079 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011080 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011081 Py_ssize_t start;
11082 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083
Jesus Ceaac451502011-04-20 17:09:23 +020011084 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11085 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011088 if (PyUnicode_READY(self) == -1)
11089 return NULL;
11090 if (PyUnicode_READY(substring) == -1)
11091 return NULL;
11092
Victor Stinner7931d9a2011-11-04 00:22:48 +010011093 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094
11095 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011097 if (result == -2)
11098 return NULL;
11099
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100 if (result < 0) {
11101 PyErr_SetString(PyExc_ValueError, "substring not found");
11102 return NULL;
11103 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011104
Christian Heimes217cfd12007-12-02 14:31:20 +000011105 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106}
11107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011108PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011109 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011110\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011111Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011112at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113
11114static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011115unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 Py_ssize_t i, length;
11118 int kind;
11119 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120 int cased;
11121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122 if (PyUnicode_READY(self) == -1)
11123 return NULL;
11124 length = PyUnicode_GET_LENGTH(self);
11125 kind = PyUnicode_KIND(self);
11126 data = PyUnicode_DATA(self);
11127
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 if (length == 1)
11130 return PyBool_FromLong(
11131 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011133 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011135 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011136
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 for (i = 0; i < length; i++) {
11139 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011140
Benjamin Peterson29060642009-01-31 22:14:21 +000011141 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11142 return PyBool_FromLong(0);
11143 else if (!cased && Py_UNICODE_ISLOWER(ch))
11144 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011146 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147}
11148
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011149PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011150 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011152Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011153at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154
11155static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011156unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 Py_ssize_t i, length;
11159 int kind;
11160 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161 int cased;
11162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011163 if (PyUnicode_READY(self) == -1)
11164 return NULL;
11165 length = PyUnicode_GET_LENGTH(self);
11166 kind = PyUnicode_KIND(self);
11167 data = PyUnicode_DATA(self);
11168
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (length == 1)
11171 return PyBool_FromLong(
11172 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011174 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011175 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011177
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 for (i = 0; i < length; i++) {
11180 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011181
Benjamin Peterson29060642009-01-31 22:14:21 +000011182 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11183 return PyBool_FromLong(0);
11184 else if (!cased && Py_UNICODE_ISUPPER(ch))
11185 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011187 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188}
11189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011190PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011191 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011193Return True if S is a titlecased string and there is at least one\n\
11194character in S, i.e. upper- and titlecase characters may only\n\
11195follow uncased characters and lowercase characters only cased ones.\n\
11196Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197
11198static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011199unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 Py_ssize_t i, length;
11202 int kind;
11203 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 int cased, previous_is_cased;
11205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206 if (PyUnicode_READY(self) == -1)
11207 return NULL;
11208 length = PyUnicode_GET_LENGTH(self);
11209 kind = PyUnicode_KIND(self);
11210 data = PyUnicode_DATA(self);
11211
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 if (length == 1) {
11214 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11215 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11216 (Py_UNICODE_ISUPPER(ch) != 0));
11217 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011219 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011222
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223 cased = 0;
11224 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 for (i = 0; i < length; i++) {
11226 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011227
Benjamin Peterson29060642009-01-31 22:14:21 +000011228 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11229 if (previous_is_cased)
11230 return PyBool_FromLong(0);
11231 previous_is_cased = 1;
11232 cased = 1;
11233 }
11234 else if (Py_UNICODE_ISLOWER(ch)) {
11235 if (!previous_is_cased)
11236 return PyBool_FromLong(0);
11237 previous_is_cased = 1;
11238 cased = 1;
11239 }
11240 else
11241 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011243 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244}
11245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011246PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011249Return True if all characters in S are whitespace\n\
11250and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251
11252static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011253unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255 Py_ssize_t i, length;
11256 int kind;
11257 void *data;
11258
11259 if (PyUnicode_READY(self) == -1)
11260 return NULL;
11261 length = PyUnicode_GET_LENGTH(self);
11262 kind = PyUnicode_KIND(self);
11263 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011266 if (length == 1)
11267 return PyBool_FromLong(
11268 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011270 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011272 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 for (i = 0; i < length; i++) {
11275 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011276 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011279 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280}
11281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011282PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011283 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011284\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011285Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011286and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011287
11288static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011289unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011290{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011291 Py_ssize_t i, length;
11292 int kind;
11293 void *data;
11294
11295 if (PyUnicode_READY(self) == -1)
11296 return NULL;
11297 length = PyUnicode_GET_LENGTH(self);
11298 kind = PyUnicode_KIND(self);
11299 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011300
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011301 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 if (length == 1)
11303 return PyBool_FromLong(
11304 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011305
11306 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011308 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310 for (i = 0; i < length; i++) {
11311 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011312 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011314 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011315}
11316
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011317PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011318 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011319\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011320Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011321and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
11323static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011324unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011325{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 int kind;
11327 void *data;
11328 Py_ssize_t len, i;
11329
11330 if (PyUnicode_READY(self) == -1)
11331 return NULL;
11332
11333 kind = PyUnicode_KIND(self);
11334 data = PyUnicode_DATA(self);
11335 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011336
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011337 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 if (len == 1) {
11339 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11340 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11341 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011342
11343 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011345 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 for (i = 0; i < len; i++) {
11348 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011349 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011350 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011351 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011352 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353}
11354
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011355PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011356 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011358Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011359False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360
11361static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011362unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 Py_ssize_t i, length;
11365 int kind;
11366 void *data;
11367
11368 if (PyUnicode_READY(self) == -1)
11369 return NULL;
11370 length = PyUnicode_GET_LENGTH(self);
11371 kind = PyUnicode_KIND(self);
11372 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 if (length == 1)
11376 return PyBool_FromLong(
11377 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011379 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011381 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 for (i = 0; i < length; i++) {
11384 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011385 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011387 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388}
11389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011390PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011391 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011393Return True if all characters in S are digits\n\
11394and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
11396static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011397unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 Py_ssize_t i, length;
11400 int kind;
11401 void *data;
11402
11403 if (PyUnicode_READY(self) == -1)
11404 return NULL;
11405 length = PyUnicode_GET_LENGTH(self);
11406 kind = PyUnicode_KIND(self);
11407 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 if (length == 1) {
11411 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11412 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11413 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011415 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011419 for (i = 0; i < length; i++) {
11420 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011421 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011423 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424}
11425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011426PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011427 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011429Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011430False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
11432static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011433unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 Py_ssize_t i, length;
11436 int kind;
11437 void *data;
11438
11439 if (PyUnicode_READY(self) == -1)
11440 return NULL;
11441 length = PyUnicode_GET_LENGTH(self);
11442 kind = PyUnicode_KIND(self);
11443 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 if (length == 1)
11447 return PyBool_FromLong(
11448 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011450 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 for (i = 0; i < length; i++) {
11455 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011458 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459}
11460
Martin v. Löwis47383402007-08-15 07:32:56 +000011461int
11462PyUnicode_IsIdentifier(PyObject *self)
11463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 int kind;
11465 void *data;
11466 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011467 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (PyUnicode_READY(self) == -1) {
11470 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 }
11473
11474 /* Special case for empty strings */
11475 if (PyUnicode_GET_LENGTH(self) == 0)
11476 return 0;
11477 kind = PyUnicode_KIND(self);
11478 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011479
11480 /* PEP 3131 says that the first character must be in
11481 XID_Start and subsequent characters in XID_Continue,
11482 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011483 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011484 letters, digits, underscore). However, given the current
11485 definition of XID_Start and XID_Continue, it is sufficient
11486 to check just for these, except that _ must be allowed
11487 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011489 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011490 return 0;
11491
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011492 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011494 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011495 return 1;
11496}
11497
11498PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011500\n\
11501Return True if S is a valid identifier according\n\
11502to the language definition.");
11503
11504static PyObject*
11505unicode_isidentifier(PyObject *self)
11506{
11507 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11508}
11509
Georg Brandl559e5d72008-06-11 18:37:52 +000011510PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011512\n\
11513Return True if all characters in S are considered\n\
11514printable in repr() or S is empty, False otherwise.");
11515
11516static PyObject*
11517unicode_isprintable(PyObject *self)
11518{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 Py_ssize_t i, length;
11520 int kind;
11521 void *data;
11522
11523 if (PyUnicode_READY(self) == -1)
11524 return NULL;
11525 length = PyUnicode_GET_LENGTH(self);
11526 kind = PyUnicode_KIND(self);
11527 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011528
11529 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 if (length == 1)
11531 return PyBool_FromLong(
11532 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 for (i = 0; i < length; i++) {
11535 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011536 Py_RETURN_FALSE;
11537 }
11538 }
11539 Py_RETURN_TRUE;
11540}
11541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011542PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011543 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544\n\
11545Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011546iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
11548static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011549unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011551 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552}
11553
Martin v. Löwis18e16552006-02-15 17:27:45 +000011554static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011555unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 if (PyUnicode_READY(self) == -1)
11558 return -1;
11559 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560}
11561
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011562PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011565Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011566done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567
11568static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011569unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011571 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 Py_UCS4 fillchar = ' ';
11573
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011574 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575 return NULL;
11576
Benjamin Petersonbac79492012-01-14 13:34:47 -050011577 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011578 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579
Victor Stinnerc4b49542011-12-11 22:44:26 +010011580 if (PyUnicode_GET_LENGTH(self) >= width)
11581 return unicode_result_unchanged(self);
11582
11583 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011586PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011587 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011589Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590
11591static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011592unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011594 if (PyUnicode_READY(self) == -1)
11595 return NULL;
11596 if (PyUnicode_IS_ASCII(self))
11597 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011598 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599}
11600
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011601#define LEFTSTRIP 0
11602#define RIGHTSTRIP 1
11603#define BOTHSTRIP 2
11604
11605/* Arrays indexed by above */
11606static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11607
11608#define STRIPNAME(i) (stripformat[i]+3)
11609
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011610/* externally visible for str.strip(unicode) */
11611PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011612_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 void *data;
11615 int kind;
11616 Py_ssize_t i, j, len;
11617 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11620 return NULL;
11621
11622 kind = PyUnicode_KIND(self);
11623 data = PyUnicode_DATA(self);
11624 len = PyUnicode_GET_LENGTH(self);
11625 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11626 PyUnicode_DATA(sepobj),
11627 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011628
Benjamin Peterson14339b62009-01-31 16:36:08 +000011629 i = 0;
11630 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 while (i < len &&
11632 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011633 i++;
11634 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011635 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011636
Benjamin Peterson14339b62009-01-31 16:36:08 +000011637 j = len;
11638 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 do {
11640 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641 } while (j >= i &&
11642 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011643 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011644 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011645
Victor Stinner7931d9a2011-11-04 00:22:48 +010011646 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647}
11648
11649PyObject*
11650PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11651{
11652 unsigned char *data;
11653 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011654 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655
Victor Stinnerde636f32011-10-01 03:55:54 +020011656 if (PyUnicode_READY(self) == -1)
11657 return NULL;
11658
Victor Stinner684d5fd2012-05-03 02:32:34 +020011659 length = PyUnicode_GET_LENGTH(self);
11660 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011661
Victor Stinner684d5fd2012-05-03 02:32:34 +020011662 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011663 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011664
Victor Stinnerde636f32011-10-01 03:55:54 +020011665 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011666 PyErr_SetString(PyExc_IndexError, "string index out of range");
11667 return NULL;
11668 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011669 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011670 Py_INCREF(unicode_empty);
11671 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011672 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011673
Victor Stinner684d5fd2012-05-03 02:32:34 +020011674 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011675 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011676 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011677 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011678 }
11679 else {
11680 kind = PyUnicode_KIND(self);
11681 data = PyUnicode_1BYTE_DATA(self);
11682 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011683 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011684 length);
11685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
11688static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011689do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691 int kind;
11692 void *data;
11693 Py_ssize_t len, i, j;
11694
11695 if (PyUnicode_READY(self) == -1)
11696 return NULL;
11697
11698 kind = PyUnicode_KIND(self);
11699 data = PyUnicode_DATA(self);
11700 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011701
Benjamin Peterson14339b62009-01-31 16:36:08 +000011702 i = 0;
11703 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011704 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011705 i++;
11706 }
11707 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011708
Benjamin Peterson14339b62009-01-31 16:36:08 +000011709 j = len;
11710 if (striptype != LEFTSTRIP) {
11711 do {
11712 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011714 j++;
11715 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011716
Victor Stinner7931d9a2011-11-04 00:22:48 +010011717 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718}
11719
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011720
11721static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011722do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011723{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011724 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011725
Benjamin Peterson14339b62009-01-31 16:36:08 +000011726 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11727 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011728
Benjamin Peterson14339b62009-01-31 16:36:08 +000011729 if (sep != NULL && sep != Py_None) {
11730 if (PyUnicode_Check(sep))
11731 return _PyUnicode_XStrip(self, striptype, sep);
11732 else {
11733 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 "%s arg must be None or str",
11735 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011736 return NULL;
11737 }
11738 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739
Benjamin Peterson14339b62009-01-31 16:36:08 +000011740 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011741}
11742
11743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011744PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011745 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746\n\
11747Return a copy of the string S with leading and trailing\n\
11748whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011749If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750
11751static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011752unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011753{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011754 if (PyTuple_GET_SIZE(args) == 0)
11755 return do_strip(self, BOTHSTRIP); /* Common case */
11756 else
11757 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011758}
11759
11760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011761PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011762 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011763\n\
11764Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011765If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766
11767static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011768unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011769{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011770 if (PyTuple_GET_SIZE(args) == 0)
11771 return do_strip(self, LEFTSTRIP); /* Common case */
11772 else
11773 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774}
11775
11776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011777PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011778 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011779\n\
11780Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011781If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011782
11783static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011784unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011785{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011786 if (PyTuple_GET_SIZE(args) == 0)
11787 return do_strip(self, RIGHTSTRIP); /* Common case */
11788 else
11789 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790}
11791
11792
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011794unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011796 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798
Georg Brandl222de0f2009-04-12 12:01:50 +000011799 if (len < 1) {
11800 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011801 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011802 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803
Victor Stinnerc4b49542011-12-11 22:44:26 +010011804 /* no repeat, return original string */
11805 if (len == 1)
11806 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011807
Benjamin Petersonbac79492012-01-14 13:34:47 -050011808 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011809 return NULL;
11810
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011811 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011812 PyErr_SetString(PyExc_OverflowError,
11813 "repeated string is too long");
11814 return NULL;
11815 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011817
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011818 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819 if (!u)
11820 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011821 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 if (PyUnicode_GET_LENGTH(str) == 1) {
11824 const int kind = PyUnicode_KIND(str);
11825 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011826 if (kind == PyUnicode_1BYTE_KIND) {
11827 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011828 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011829 }
11830 else if (kind == PyUnicode_2BYTE_KIND) {
11831 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011832 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011833 ucs2[n] = fill_char;
11834 } else {
11835 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11836 assert(kind == PyUnicode_4BYTE_KIND);
11837 for (n = 0; n < len; ++n)
11838 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 }
11841 else {
11842 /* number of characters copied this far */
11843 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011844 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011845 char *to = (char *) PyUnicode_DATA(u);
11846 Py_MEMCPY(to, PyUnicode_DATA(str),
11847 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011849 n = (done <= nchars-done) ? done : nchars-done;
11850 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011851 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011852 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 }
11854
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011855 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011856 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857}
11858
Alexander Belopolsky40018472011-02-26 01:02:56 +000011859PyObject *
11860PyUnicode_Replace(PyObject *obj,
11861 PyObject *subobj,
11862 PyObject *replobj,
11863 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864{
11865 PyObject *self;
11866 PyObject *str1;
11867 PyObject *str2;
11868 PyObject *result;
11869
11870 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011871 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011872 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011874 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011875 Py_DECREF(self);
11876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877 }
11878 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011879 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 Py_DECREF(self);
11881 Py_DECREF(str1);
11882 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011884 if (PyUnicode_READY(self) == -1 ||
11885 PyUnicode_READY(str1) == -1 ||
11886 PyUnicode_READY(str2) == -1)
11887 result = NULL;
11888 else
11889 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890 Py_DECREF(self);
11891 Py_DECREF(str1);
11892 Py_DECREF(str2);
11893 return result;
11894}
11895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011896PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011897 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898\n\
11899Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011900old replaced by new. If the optional argument count is\n\
11901given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902
11903static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 PyObject *str1;
11907 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011908 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909 PyObject *result;
11910
Martin v. Löwis18e16552006-02-15 17:27:45 +000011911 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011913 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011916 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 return NULL;
11918 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011919 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011920 Py_DECREF(str1);
11921 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011922 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011923 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11924 result = NULL;
11925 else
11926 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927
11928 Py_DECREF(str1);
11929 Py_DECREF(str2);
11930 return result;
11931}
11932
Alexander Belopolsky40018472011-02-26 01:02:56 +000011933static PyObject *
11934unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011936 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 Py_ssize_t isize;
11938 Py_ssize_t osize, squote, dquote, i, o;
11939 Py_UCS4 max, quote;
11940 int ikind, okind;
11941 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011944 return NULL;
11945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 isize = PyUnicode_GET_LENGTH(unicode);
11947 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011948
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 /* Compute length of output, quote characters, and
11950 maximum character */
11951 osize = 2; /* quotes */
11952 max = 127;
11953 squote = dquote = 0;
11954 ikind = PyUnicode_KIND(unicode);
11955 for (i = 0; i < isize; i++) {
11956 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11957 switch (ch) {
11958 case '\'': squote++; osize++; break;
11959 case '"': dquote++; osize++; break;
11960 case '\\': case '\t': case '\r': case '\n':
11961 osize += 2; break;
11962 default:
11963 /* Fast-path ASCII */
11964 if (ch < ' ' || ch == 0x7f)
11965 osize += 4; /* \xHH */
11966 else if (ch < 0x7f)
11967 osize++;
11968 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11969 osize++;
11970 max = ch > max ? ch : max;
11971 }
11972 else if (ch < 0x100)
11973 osize += 4; /* \xHH */
11974 else if (ch < 0x10000)
11975 osize += 6; /* \uHHHH */
11976 else
11977 osize += 10; /* \uHHHHHHHH */
11978 }
11979 }
11980
11981 quote = '\'';
11982 if (squote) {
11983 if (dquote)
11984 /* Both squote and dquote present. Use squote,
11985 and escape them */
11986 osize += squote;
11987 else
11988 quote = '"';
11989 }
11990
11991 repr = PyUnicode_New(osize, max);
11992 if (repr == NULL)
11993 return NULL;
11994 okind = PyUnicode_KIND(repr);
11995 odata = PyUnicode_DATA(repr);
11996
11997 PyUnicode_WRITE(okind, odata, 0, quote);
11998 PyUnicode_WRITE(okind, odata, osize-1, quote);
11999
12000 for (i = 0, o = 1; i < isize; i++) {
12001 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012002
12003 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 if ((ch == quote) || (ch == '\\')) {
12005 PyUnicode_WRITE(okind, odata, o++, '\\');
12006 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012007 continue;
12008 }
12009
Benjamin Peterson29060642009-01-31 22:14:21 +000012010 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012011 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 PyUnicode_WRITE(okind, odata, o++, '\\');
12013 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012014 }
12015 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 PyUnicode_WRITE(okind, odata, o++, '\\');
12017 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012018 }
12019 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 PyUnicode_WRITE(okind, odata, o++, '\\');
12021 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012022 }
12023
12024 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012025 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 PyUnicode_WRITE(okind, odata, o++, '\\');
12027 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012028 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12029 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012030 }
12031
Georg Brandl559e5d72008-06-11 18:37:52 +000012032 /* Copy ASCII characters as-is */
12033 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012035 }
12036
Benjamin Peterson29060642009-01-31 22:14:21 +000012037 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012038 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012039 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012040 (categories Z* and C* except ASCII space)
12041 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012043 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012047 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12048 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012049 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012050 /* Map 16-bit characters to '\uxxxx' */
12051 else if (ch <= 0xffff) {
12052 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012053 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12054 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12055 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012057 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012058 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012059 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012060 PyUnicode_WRITE(okind, odata, o++, 'U');
12061 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12062 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12063 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12064 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012069 }
12070 }
12071 /* Copy characters as-is */
12072 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012074 }
12075 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012076 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012078 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012079 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080}
12081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012082PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012083 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084\n\
12085Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012086such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087arguments start and end are interpreted as in slice notation.\n\
12088\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012089Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090
12091static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012092unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012094 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012095 Py_ssize_t start;
12096 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012097 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098
Jesus Ceaac451502011-04-20 17:09:23 +020012099 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12100 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012101 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 if (PyUnicode_READY(self) == -1)
12104 return NULL;
12105 if (PyUnicode_READY(substring) == -1)
12106 return NULL;
12107
Victor Stinner7931d9a2011-11-04 00:22:48 +010012108 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109
12110 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 if (result == -2)
12113 return NULL;
12114
Christian Heimes217cfd12007-12-02 14:31:20 +000012115 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116}
12117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012118PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012119 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012121Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122
12123static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012124unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012126 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012127 Py_ssize_t start;
12128 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012129 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130
Jesus Ceaac451502011-04-20 17:09:23 +020012131 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12132 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012133 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 if (PyUnicode_READY(self) == -1)
12136 return NULL;
12137 if (PyUnicode_READY(substring) == -1)
12138 return NULL;
12139
Victor Stinner7931d9a2011-11-04 00:22:48 +010012140 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141
12142 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 if (result == -2)
12145 return NULL;
12146
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147 if (result < 0) {
12148 PyErr_SetString(PyExc_ValueError, "substring not found");
12149 return NULL;
12150 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151
Christian Heimes217cfd12007-12-02 14:31:20 +000012152 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153}
12154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012155PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012156 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012158Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012159done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160
12161static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012162unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012164 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012165 Py_UCS4 fillchar = ' ';
12166
Victor Stinnere9a29352011-10-01 02:14:59 +020012167 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012169
Benjamin Petersonbac79492012-01-14 13:34:47 -050012170 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171 return NULL;
12172
Victor Stinnerc4b49542011-12-11 22:44:26 +010012173 if (PyUnicode_GET_LENGTH(self) >= width)
12174 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
Victor Stinnerc4b49542011-12-11 22:44:26 +010012176 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177}
12178
Alexander Belopolsky40018472011-02-26 01:02:56 +000012179PyObject *
12180PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181{
12182 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012183
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184 s = PyUnicode_FromObject(s);
12185 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012186 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012187 if (sep != NULL) {
12188 sep = PyUnicode_FromObject(sep);
12189 if (sep == NULL) {
12190 Py_DECREF(s);
12191 return NULL;
12192 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193 }
12194
Victor Stinner9310abb2011-10-05 00:59:23 +020012195 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196
12197 Py_DECREF(s);
12198 Py_XDECREF(sep);
12199 return result;
12200}
12201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012202PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012203 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204\n\
12205Return a list of the words in S, using sep as the\n\
12206delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012207splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012208whitespace string is a separator and empty strings are\n\
12209removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210
12211static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012212unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012214 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012216 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012218 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12219 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220 return NULL;
12221
12222 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012223 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012225 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012227 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228}
12229
Thomas Wouters477c8d52006-05-27 19:21:47 +000012230PyObject *
12231PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12232{
12233 PyObject* str_obj;
12234 PyObject* sep_obj;
12235 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 int kind1, kind2, kind;
12237 void *buf1 = NULL, *buf2 = NULL;
12238 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012239
12240 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012241 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012242 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012243 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012244 if (!sep_obj) {
12245 Py_DECREF(str_obj);
12246 return NULL;
12247 }
12248 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12249 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012250 Py_DECREF(str_obj);
12251 return NULL;
12252 }
12253
Victor Stinner14f8f022011-10-05 20:58:25 +020012254 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012256 kind = Py_MAX(kind1, kind2);
12257 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012259 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012260 if (!buf1)
12261 goto onError;
12262 buf2 = PyUnicode_DATA(sep_obj);
12263 if (kind2 != kind)
12264 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12265 if (!buf2)
12266 goto onError;
12267 len1 = PyUnicode_GET_LENGTH(str_obj);
12268 len2 = PyUnicode_GET_LENGTH(sep_obj);
12269
Benjamin Petersonead6b532011-12-20 17:23:42 -060012270 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012271 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012272 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12273 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12274 else
12275 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276 break;
12277 case PyUnicode_2BYTE_KIND:
12278 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12279 break;
12280 case PyUnicode_4BYTE_KIND:
12281 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12282 break;
12283 default:
12284 assert(0);
12285 out = 0;
12286 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012287
12288 Py_DECREF(sep_obj);
12289 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012290 if (kind1 != kind)
12291 PyMem_Free(buf1);
12292 if (kind2 != kind)
12293 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012294
12295 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 onError:
12297 Py_DECREF(sep_obj);
12298 Py_DECREF(str_obj);
12299 if (kind1 != kind && buf1)
12300 PyMem_Free(buf1);
12301 if (kind2 != kind && buf2)
12302 PyMem_Free(buf2);
12303 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012304}
12305
12306
12307PyObject *
12308PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12309{
12310 PyObject* str_obj;
12311 PyObject* sep_obj;
12312 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 int kind1, kind2, kind;
12314 void *buf1 = NULL, *buf2 = NULL;
12315 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012316
12317 str_obj = PyUnicode_FromObject(str_in);
12318 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012319 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012320 sep_obj = PyUnicode_FromObject(sep_in);
12321 if (!sep_obj) {
12322 Py_DECREF(str_obj);
12323 return NULL;
12324 }
12325
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 kind1 = PyUnicode_KIND(str_in);
12327 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012328 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012329 buf1 = PyUnicode_DATA(str_in);
12330 if (kind1 != kind)
12331 buf1 = _PyUnicode_AsKind(str_in, kind);
12332 if (!buf1)
12333 goto onError;
12334 buf2 = PyUnicode_DATA(sep_obj);
12335 if (kind2 != kind)
12336 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12337 if (!buf2)
12338 goto onError;
12339 len1 = PyUnicode_GET_LENGTH(str_obj);
12340 len2 = PyUnicode_GET_LENGTH(sep_obj);
12341
Benjamin Petersonead6b532011-12-20 17:23:42 -060012342 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012344 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12345 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12346 else
12347 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 break;
12349 case PyUnicode_2BYTE_KIND:
12350 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12351 break;
12352 case PyUnicode_4BYTE_KIND:
12353 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12354 break;
12355 default:
12356 assert(0);
12357 out = 0;
12358 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359
12360 Py_DECREF(sep_obj);
12361 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 if (kind1 != kind)
12363 PyMem_Free(buf1);
12364 if (kind2 != kind)
12365 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012366
12367 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 onError:
12369 Py_DECREF(sep_obj);
12370 Py_DECREF(str_obj);
12371 if (kind1 != kind && buf1)
12372 PyMem_Free(buf1);
12373 if (kind2 != kind && buf2)
12374 PyMem_Free(buf2);
12375 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376}
12377
12378PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012379 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012380\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012381Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012382the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012383found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012384
12385static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012386unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012387{
Victor Stinner9310abb2011-10-05 00:59:23 +020012388 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012389}
12390
12391PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012392 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012394Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012396separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012397
12398static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012399unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012400{
Victor Stinner9310abb2011-10-05 00:59:23 +020012401 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012402}
12403
Alexander Belopolsky40018472011-02-26 01:02:56 +000012404PyObject *
12405PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012406{
12407 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012408
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012409 s = PyUnicode_FromObject(s);
12410 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012411 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012412 if (sep != NULL) {
12413 sep = PyUnicode_FromObject(sep);
12414 if (sep == NULL) {
12415 Py_DECREF(s);
12416 return NULL;
12417 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012418 }
12419
Victor Stinner9310abb2011-10-05 00:59:23 +020012420 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012421
12422 Py_DECREF(s);
12423 Py_XDECREF(sep);
12424 return result;
12425}
12426
12427PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012428 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012429\n\
12430Return a list of the words in S, using sep as the\n\
12431delimiter string, starting at the end of the string and\n\
12432working to the front. If maxsplit is given, at most maxsplit\n\
12433splits are done. If sep is not specified, any whitespace string\n\
12434is a separator.");
12435
12436static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012437unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012438{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012439 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012440 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012441 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012442
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012443 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12444 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012445 return NULL;
12446
12447 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012448 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012449 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012450 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012451 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012452 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012453}
12454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012455PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012456 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457\n\
12458Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012459Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012460is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461
12462static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012463unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012465 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012466 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012467
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012468 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12469 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470 return NULL;
12471
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012472 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473}
12474
12475static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012476PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012478 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479}
12480
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012481PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012482 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483\n\
12484Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012485and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486
12487static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012488unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012490 if (PyUnicode_READY(self) == -1)
12491 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012492 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493}
12494
Georg Brandlceee0772007-11-27 23:48:05 +000012495PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012496 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012497\n\
12498Return a translation table usable for str.translate().\n\
12499If there is only one argument, it must be a dictionary mapping Unicode\n\
12500ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012501Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012502If there are two arguments, they must be strings of equal length, and\n\
12503in the resulting dictionary, each character in x will be mapped to the\n\
12504character at the same position in y. If there is a third argument, it\n\
12505must be a string, whose characters will be mapped to None in the result.");
12506
12507static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012508unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012509{
12510 PyObject *x, *y = NULL, *z = NULL;
12511 PyObject *new = NULL, *key, *value;
12512 Py_ssize_t i = 0;
12513 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012514
Georg Brandlceee0772007-11-27 23:48:05 +000012515 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12516 return NULL;
12517 new = PyDict_New();
12518 if (!new)
12519 return NULL;
12520 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 int x_kind, y_kind, z_kind;
12522 void *x_data, *y_data, *z_data;
12523
Georg Brandlceee0772007-11-27 23:48:05 +000012524 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012525 if (!PyUnicode_Check(x)) {
12526 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12527 "be a string if there is a second argument");
12528 goto err;
12529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012530 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012531 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12532 "arguments must have equal length");
12533 goto err;
12534 }
12535 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 x_kind = PyUnicode_KIND(x);
12537 y_kind = PyUnicode_KIND(y);
12538 x_data = PyUnicode_DATA(x);
12539 y_data = PyUnicode_DATA(y);
12540 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12541 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012542 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012543 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012544 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012545 if (!value) {
12546 Py_DECREF(key);
12547 goto err;
12548 }
Georg Brandlceee0772007-11-27 23:48:05 +000012549 res = PyDict_SetItem(new, key, value);
12550 Py_DECREF(key);
12551 Py_DECREF(value);
12552 if (res < 0)
12553 goto err;
12554 }
12555 /* create entries for deleting chars in z */
12556 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 z_kind = PyUnicode_KIND(z);
12558 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012559 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012561 if (!key)
12562 goto err;
12563 res = PyDict_SetItem(new, key, Py_None);
12564 Py_DECREF(key);
12565 if (res < 0)
12566 goto err;
12567 }
12568 }
12569 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 int kind;
12571 void *data;
12572
Georg Brandlceee0772007-11-27 23:48:05 +000012573 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012574 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012575 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12576 "to maketrans it must be a dict");
12577 goto err;
12578 }
12579 /* copy entries into the new dict, converting string keys to int keys */
12580 while (PyDict_Next(x, &i, &key, &value)) {
12581 if (PyUnicode_Check(key)) {
12582 /* convert string keys to integer keys */
12583 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012584 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012585 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12586 "table must be of length 1");
12587 goto err;
12588 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 kind = PyUnicode_KIND(key);
12590 data = PyUnicode_DATA(key);
12591 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012592 if (!newkey)
12593 goto err;
12594 res = PyDict_SetItem(new, newkey, value);
12595 Py_DECREF(newkey);
12596 if (res < 0)
12597 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012598 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012599 /* just keep integer keys */
12600 if (PyDict_SetItem(new, key, value) < 0)
12601 goto err;
12602 } else {
12603 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12604 "be strings or integers");
12605 goto err;
12606 }
12607 }
12608 }
12609 return new;
12610 err:
12611 Py_DECREF(new);
12612 return NULL;
12613}
12614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012615PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012616 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617\n\
12618Return a copy of the string S, where all characters have been mapped\n\
12619through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012620Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012621Unmapped characters are left untouched. Characters mapped to None\n\
12622are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623
12624static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012627 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628}
12629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012630PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012631 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012633Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634
12635static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012636unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012638 if (PyUnicode_READY(self) == -1)
12639 return NULL;
12640 if (PyUnicode_IS_ASCII(self))
12641 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012642 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643}
12644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012645PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012646 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012648Pad a numeric string S with zeros on the left, to fill a field\n\
12649of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650
12651static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012652unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012654 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012655 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012656 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 int kind;
12658 void *data;
12659 Py_UCS4 chr;
12660
Martin v. Löwis18e16552006-02-15 17:27:45 +000012661 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662 return NULL;
12663
Benjamin Petersonbac79492012-01-14 13:34:47 -050012664 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012665 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666
Victor Stinnerc4b49542011-12-11 22:44:26 +010012667 if (PyUnicode_GET_LENGTH(self) >= width)
12668 return unicode_result_unchanged(self);
12669
12670 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671
12672 u = pad(self, fill, 0, '0');
12673
Walter Dörwald068325e2002-04-15 13:36:47 +000012674 if (u == NULL)
12675 return NULL;
12676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 kind = PyUnicode_KIND(u);
12678 data = PyUnicode_DATA(u);
12679 chr = PyUnicode_READ(kind, data, fill);
12680
12681 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012683 PyUnicode_WRITE(kind, data, 0, chr);
12684 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685 }
12686
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012687 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012688 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690
12691#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012692static PyObject *
12693unicode__decimal2ascii(PyObject *self)
12694{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012696}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697#endif
12698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012699PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012700 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012702Return True if S starts with the specified prefix, False otherwise.\n\
12703With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012704With optional end, stop comparing S at that position.\n\
12705prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706
12707static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012708unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012709 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012711 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012712 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012713 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012714 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012715 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716
Jesus Ceaac451502011-04-20 17:09:23 +020012717 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012718 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012719 if (PyTuple_Check(subobj)) {
12720 Py_ssize_t i;
12721 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012722 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012723 if (substring == NULL)
12724 return NULL;
12725 result = tailmatch(self, substring, start, end, -1);
12726 Py_DECREF(substring);
12727 if (result) {
12728 Py_RETURN_TRUE;
12729 }
12730 }
12731 /* nothing matched */
12732 Py_RETURN_FALSE;
12733 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012734 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012735 if (substring == NULL) {
12736 if (PyErr_ExceptionMatches(PyExc_TypeError))
12737 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12738 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012739 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012740 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012741 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012743 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744}
12745
12746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012747PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012748 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012750Return True if S ends with the specified suffix, False otherwise.\n\
12751With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012752With optional end, stop comparing S at that position.\n\
12753suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754
12755static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012756unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012759 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012760 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012761 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012762 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012763 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764
Jesus Ceaac451502011-04-20 17:09:23 +020012765 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012767 if (PyTuple_Check(subobj)) {
12768 Py_ssize_t i;
12769 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012770 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012772 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012774 result = tailmatch(self, substring, start, end, +1);
12775 Py_DECREF(substring);
12776 if (result) {
12777 Py_RETURN_TRUE;
12778 }
12779 }
12780 Py_RETURN_FALSE;
12781 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012782 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012783 if (substring == NULL) {
12784 if (PyErr_ExceptionMatches(PyExc_TypeError))
12785 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12786 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012787 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012788 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012789 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012791 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792}
12793
Victor Stinner202fdca2012-05-07 12:47:02 +020012794Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012795_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012796{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012797 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012798 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12799 writer->data = PyUnicode_DATA(writer->buffer);
12800 writer->kind = PyUnicode_KIND(writer->buffer);
12801}
12802
Victor Stinnerd3f08822012-05-29 12:57:52 +020012803void
12804_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012805{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012806 memset(writer, 0, sizeof(*writer));
12807#ifdef Py_DEBUG
12808 writer->kind = 5; /* invalid kind */
12809#endif
12810 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012811 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012812}
12813
Victor Stinnerd3f08822012-05-29 12:57:52 +020012814int
12815_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12816 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012817{
12818 Py_ssize_t newlen;
12819 PyObject *newbuffer;
12820
Victor Stinnerd3f08822012-05-29 12:57:52 +020012821 assert(length > 0);
12822
Victor Stinner202fdca2012-05-07 12:47:02 +020012823 if (length > PY_SSIZE_T_MAX - writer->pos) {
12824 PyErr_NoMemory();
12825 return -1;
12826 }
12827 newlen = writer->pos + length;
12828
Victor Stinnerd3f08822012-05-29 12:57:52 +020012829 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012830 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012831 /* overallocate 25% to limit the number of resize */
12832 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12833 newlen += newlen / 4;
12834 if (newlen < writer->min_length)
12835 newlen = writer->min_length;
12836 }
12837 writer->buffer = PyUnicode_New(newlen, maxchar);
12838 if (writer->buffer == NULL)
12839 return -1;
12840 _PyUnicodeWriter_Update(writer);
12841 return 0;
12842 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012843
Victor Stinnerd3f08822012-05-29 12:57:52 +020012844 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012845 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012846 /* overallocate 25% to limit the number of resize */
12847 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12848 newlen += newlen / 4;
12849 if (newlen < writer->min_length)
12850 newlen = writer->min_length;
12851 }
12852
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012853 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012854 /* resize + widen */
12855 newbuffer = PyUnicode_New(newlen, maxchar);
12856 if (newbuffer == NULL)
12857 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012858 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12859 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012860 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012861 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012862 }
12863 else {
12864 newbuffer = resize_compact(writer->buffer, newlen);
12865 if (newbuffer == NULL)
12866 return -1;
12867 }
12868 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012869 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012870 }
12871 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012872 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012873 newbuffer = PyUnicode_New(writer->size, maxchar);
12874 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012875 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012876 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12877 writer->buffer, 0, writer->pos);
12878 Py_DECREF(writer->buffer);
12879 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012880 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012881 }
12882 return 0;
12883}
12884
Victor Stinnerd3f08822012-05-29 12:57:52 +020012885int
12886_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12887{
12888 Py_UCS4 maxchar;
12889 Py_ssize_t len;
12890
12891 if (PyUnicode_READY(str) == -1)
12892 return -1;
12893 len = PyUnicode_GET_LENGTH(str);
12894 if (len == 0)
12895 return 0;
12896 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12897 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012898 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012899 Py_INCREF(str);
12900 writer->buffer = str;
12901 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012902 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012903 writer->size = 0;
12904 writer->pos += len;
12905 return 0;
12906 }
12907 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12908 return -1;
12909 }
12910 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12911 str, 0, len);
12912 writer->pos += len;
12913 return 0;
12914}
12915
12916PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012917_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012918{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012919 if (writer->pos == 0) {
12920 Py_XDECREF(writer->buffer);
12921 Py_INCREF(unicode_empty);
12922 return unicode_empty;
12923 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012924 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012925 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12926 return writer->buffer;
12927 }
12928 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12929 PyObject *newbuffer;
12930 newbuffer = resize_compact(writer->buffer, writer->pos);
12931 if (newbuffer == NULL) {
12932 Py_DECREF(writer->buffer);
12933 return NULL;
12934 }
12935 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012936 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012937 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012938 return writer->buffer;
12939}
12940
Victor Stinnerd3f08822012-05-29 12:57:52 +020012941void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012942_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012943{
12944 Py_CLEAR(writer->buffer);
12945}
12946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012947#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012948
12949PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012950 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012951\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012952Return a formatted version of S, using substitutions from args and kwargs.\n\
12953The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012954
Eric Smith27bbca62010-11-04 17:06:58 +000012955PyDoc_STRVAR(format_map__doc__,
12956 "S.format_map(mapping) -> str\n\
12957\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012958Return a formatted version of S, using substitutions from mapping.\n\
12959The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012960
Eric Smith4a7d76d2008-05-30 18:10:19 +000012961static PyObject *
12962unicode__format__(PyObject* self, PyObject* args)
12963{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012964 PyObject *format_spec;
12965 _PyUnicodeWriter writer;
12966 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012967
12968 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12969 return NULL;
12970
Victor Stinnerd3f08822012-05-29 12:57:52 +020012971 if (PyUnicode_READY(self) == -1)
12972 return NULL;
12973 _PyUnicodeWriter_Init(&writer, 0);
12974 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12975 self, format_spec, 0,
12976 PyUnicode_GET_LENGTH(format_spec));
12977 if (ret == -1) {
12978 _PyUnicodeWriter_Dealloc(&writer);
12979 return NULL;
12980 }
12981 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012982}
12983
Eric Smith8c663262007-08-25 02:26:07 +000012984PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012985 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012986\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012987Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012988
12989static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012990unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012991{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992 Py_ssize_t size;
12993
12994 /* If it's a compact object, account for base structure +
12995 character data. */
12996 if (PyUnicode_IS_COMPACT_ASCII(v))
12997 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12998 else if (PyUnicode_IS_COMPACT(v))
12999 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013000 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 else {
13002 /* If it is a two-block object, account for base object, and
13003 for character block if present. */
13004 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013005 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013006 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013007 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 }
13009 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013010 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013011 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013013 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013014 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013015
13016 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013017}
13018
13019PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013020 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013021
13022static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013023unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013024{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013025 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 if (!copy)
13027 return NULL;
13028 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013029}
13030
Guido van Rossumd57fd912000-03-10 22:53:23 +000013031static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013032 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013033 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013034 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13035 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013036 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13037 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013038 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013039 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13040 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13041 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13042 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13043 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013044 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013045 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13046 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13047 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013048 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013049 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13050 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13051 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013052 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013053 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013054 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013055 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013056 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13057 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13058 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13059 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13060 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13061 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13062 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13063 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13064 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13065 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13066 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13067 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13068 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13069 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013070 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013071 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013072 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013073 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013074 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013075 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013076 {"maketrans", (PyCFunction) unicode_maketrans,
13077 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013078 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013079#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013080 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013081 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013082#endif
13083
Benjamin Peterson14339b62009-01-31 16:36:08 +000013084 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013085 {NULL, NULL}
13086};
13087
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013088static PyObject *
13089unicode_mod(PyObject *v, PyObject *w)
13090{
Brian Curtindfc80e32011-08-10 20:28:54 -050013091 if (!PyUnicode_Check(v))
13092 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013094}
13095
13096static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013097 0, /*nb_add*/
13098 0, /*nb_subtract*/
13099 0, /*nb_multiply*/
13100 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013101};
13102
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013104 (lenfunc) unicode_length, /* sq_length */
13105 PyUnicode_Concat, /* sq_concat */
13106 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13107 (ssizeargfunc) unicode_getitem, /* sq_item */
13108 0, /* sq_slice */
13109 0, /* sq_ass_item */
13110 0, /* sq_ass_slice */
13111 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112};
13113
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013114static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013115unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013117 if (PyUnicode_READY(self) == -1)
13118 return NULL;
13119
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013120 if (PyIndex_Check(item)) {
13121 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013122 if (i == -1 && PyErr_Occurred())
13123 return NULL;
13124 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013125 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013126 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013127 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013128 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013129 PyObject *result;
13130 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013131 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013132 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013134 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013135 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013136 return NULL;
13137 }
13138
13139 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013140 Py_INCREF(unicode_empty);
13141 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013143 slicelength == PyUnicode_GET_LENGTH(self)) {
13144 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013145 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013146 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013147 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013148 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013149 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013150 src_kind = PyUnicode_KIND(self);
13151 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013152 if (!PyUnicode_IS_ASCII(self)) {
13153 kind_limit = kind_maxchar_limit(src_kind);
13154 max_char = 0;
13155 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13156 ch = PyUnicode_READ(src_kind, src_data, cur);
13157 if (ch > max_char) {
13158 max_char = ch;
13159 if (max_char >= kind_limit)
13160 break;
13161 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013162 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013163 }
Victor Stinner55c99112011-10-13 01:17:06 +020013164 else
13165 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013166 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013167 if (result == NULL)
13168 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013169 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013170 dest_data = PyUnicode_DATA(result);
13171
13172 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013173 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13174 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013175 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013176 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013177 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013178 } else {
13179 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13180 return NULL;
13181 }
13182}
13183
13184static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013185 (lenfunc)unicode_length, /* mp_length */
13186 (binaryfunc)unicode_subscript, /* mp_subscript */
13187 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013188};
13189
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191/* Helpers for PyUnicode_Format() */
13192
13193static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013194getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013196 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013198 (*p_argidx)++;
13199 if (arglen < 0)
13200 return args;
13201 else
13202 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203 }
13204 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013205 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206 return NULL;
13207}
13208
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013209/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210
Victor Stinnerd3f08822012-05-29 12:57:52 +020013211static int
13212formatfloat(PyObject *v, int flags, int prec, int type,
13213 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013215 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013217 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013218
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219 x = PyFloat_AsDouble(v);
13220 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013221 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013222
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013224 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013225
Eric Smith0923d1d2009-04-16 20:16:10 +000013226 p = PyOS_double_to_string(x, type, prec,
13227 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013228 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013229 return -1;
13230 len = strlen(p);
13231 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013232 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13233 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013234 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013235 }
Victor Stinner184252a2012-06-16 02:57:41 +020013236 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013237 writer->pos += len;
13238 }
13239 else
13240 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013241 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013242 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013243}
13244
Victor Stinnerd0880d52012-04-27 23:40:13 +020013245/* formatlong() emulates the format codes d, u, o, x and X, and
13246 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13247 * Python's regular ints.
13248 * Return value: a new PyUnicodeObject*, or NULL if error.
13249 * The output string is of the form
13250 * "-"? ("0x" | "0X")? digit+
13251 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13252 * set in flags. The case of hex digits will be correct,
13253 * There will be at least prec digits, zero-filled on the left if
13254 * necessary to get that many.
13255 * val object to be converted
13256 * flags bitmask of format flags; only F_ALT is looked at
13257 * prec minimum number of digits; 0-fill on left if needed
13258 * type a character in [duoxX]; u acts the same as d
13259 *
13260 * CAUTION: o, x and X conversions on regular ints can never
13261 * produce a '-' sign, but can for Python's unbounded ints.
13262 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013263static PyObject*
13264formatlong(PyObject *val, int flags, int prec, int type)
13265{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013266 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013267 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013268 Py_ssize_t i;
13269 int sign; /* 1 if '-', else 0 */
13270 int len; /* number of characters */
13271 Py_ssize_t llen;
13272 int numdigits; /* len == numnondigits + numdigits */
13273 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013274
Victor Stinnerd0880d52012-04-27 23:40:13 +020013275 /* Avoid exceeding SSIZE_T_MAX */
13276 if (prec > INT_MAX-3) {
13277 PyErr_SetString(PyExc_OverflowError,
13278 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013279 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013280 }
13281
13282 assert(PyLong_Check(val));
13283
13284 switch (type) {
13285 case 'd':
13286 case 'u':
13287 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013288 if (PyBool_Check(val))
13289 result = PyNumber_ToBase(val, 10);
13290 else
13291 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013292 break;
13293 case 'o':
13294 numnondigits = 2;
13295 result = PyNumber_ToBase(val, 8);
13296 break;
13297 case 'x':
13298 case 'X':
13299 numnondigits = 2;
13300 result = PyNumber_ToBase(val, 16);
13301 break;
13302 default:
13303 assert(!"'type' not in [duoxX]");
13304 }
13305 if (!result)
13306 return NULL;
13307
13308 assert(unicode_modifiable(result));
13309 assert(PyUnicode_IS_READY(result));
13310 assert(PyUnicode_IS_ASCII(result));
13311
13312 /* To modify the string in-place, there can only be one reference. */
13313 if (Py_REFCNT(result) != 1) {
13314 PyErr_BadInternalCall();
13315 return NULL;
13316 }
13317 buf = PyUnicode_DATA(result);
13318 llen = PyUnicode_GET_LENGTH(result);
13319 if (llen > INT_MAX) {
13320 PyErr_SetString(PyExc_ValueError,
13321 "string too large in _PyBytes_FormatLong");
13322 return NULL;
13323 }
13324 len = (int)llen;
13325 sign = buf[0] == '-';
13326 numnondigits += sign;
13327 numdigits = len - numnondigits;
13328 assert(numdigits > 0);
13329
13330 /* Get rid of base marker unless F_ALT */
13331 if (((flags & F_ALT) == 0 &&
13332 (type == 'o' || type == 'x' || type == 'X'))) {
13333 assert(buf[sign] == '0');
13334 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13335 buf[sign+1] == 'o');
13336 numnondigits -= 2;
13337 buf += 2;
13338 len -= 2;
13339 if (sign)
13340 buf[0] = '-';
13341 assert(len == numnondigits + numdigits);
13342 assert(numdigits > 0);
13343 }
13344
13345 /* Fill with leading zeroes to meet minimum width. */
13346 if (prec > numdigits) {
13347 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13348 numnondigits + prec);
13349 char *b1;
13350 if (!r1) {
13351 Py_DECREF(result);
13352 return NULL;
13353 }
13354 b1 = PyBytes_AS_STRING(r1);
13355 for (i = 0; i < numnondigits; ++i)
13356 *b1++ = *buf++;
13357 for (i = 0; i < prec - numdigits; i++)
13358 *b1++ = '0';
13359 for (i = 0; i < numdigits; i++)
13360 *b1++ = *buf++;
13361 *b1 = '\0';
13362 Py_DECREF(result);
13363 result = r1;
13364 buf = PyBytes_AS_STRING(result);
13365 len = numnondigits + prec;
13366 }
13367
13368 /* Fix up case for hex conversions. */
13369 if (type == 'X') {
13370 /* Need to convert all lower case letters to upper case.
13371 and need to convert 0x to 0X (and -0x to -0X). */
13372 for (i = 0; i < len; i++)
13373 if (buf[i] >= 'a' && buf[i] <= 'x')
13374 buf[i] -= 'a'-'A';
13375 }
13376 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13377 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013378 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013379 Py_DECREF(result);
13380 result = unicode;
13381 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013382 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013383}
13384
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013385static Py_UCS4
13386formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013387{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013388 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013389 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013390 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013391 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 goto onError;
13394 }
13395 else {
13396 /* Integer input truncated to a character */
13397 long x;
13398 x = PyLong_AsLong(v);
13399 if (x == -1 && PyErr_Occurred())
13400 goto onError;
13401
Victor Stinner8faf8212011-12-08 22:14:11 +010013402 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 PyErr_SetString(PyExc_OverflowError,
13404 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013405 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 }
13407
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013408 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013409 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013410
Benjamin Peterson29060642009-01-31 22:14:21 +000013411 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013412 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013414 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013415}
13416
Alexander Belopolsky40018472011-02-26 01:02:56 +000013417PyObject *
13418PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013419{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013420 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013423 PyObject *temp = NULL;
13424 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013425 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013426 void *fmt;
13427 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013428 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013429 Py_ssize_t sublen;
13430 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013431
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 PyErr_BadInternalCall();
13434 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013435 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013436 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013437 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013438 return NULL;
Victor Stinner19294072012-10-05 00:09:33 +020013439 if (PyUnicode_READY(uformat) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013440 Py_DECREF(uformat);
Victor Stinner19294072012-10-05 00:09:33 +020013441 return NULL;
13442 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013444 fmt = PyUnicode_DATA(uformat);
13445 fmtkind = PyUnicode_KIND(uformat);
13446 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13447 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013448
Victor Stinnerd3f08822012-05-29 12:57:52 +020013449 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013450
Guido van Rossumd57fd912000-03-10 22:53:23 +000013451 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013452 arglen = PyTuple_Size(args);
13453 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013454 }
13455 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 arglen = -1;
13457 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013458 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013459 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013460 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013461
13462 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013463 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013464 Py_ssize_t nonfmtpos;
13465 nonfmtpos = fmtpos++;
13466 while (fmtcnt >= 0 &&
13467 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13468 fmtpos++;
13469 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013470 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013471 if (fmtcnt < 0)
13472 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013473 sublen = fmtpos - nonfmtpos;
13474 maxchar = _PyUnicode_FindMaxChar(uformat,
13475 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013476 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013477 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013478
Victor Stinnerd3f08822012-05-29 12:57:52 +020013479 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13480 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013481 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013482 }
13483 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013484 /* Got a format specifier */
13485 int flags = 0;
13486 Py_ssize_t width = -1;
13487 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013488 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013489 Py_UCS4 fill;
13490 int sign;
13491 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 int isnumok;
13493 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013494 void *pbuf = NULL;
13495 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013496 Py_UCS4 bufmaxchar;
13497 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013499 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013500 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13501 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013502 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 Py_ssize_t keylen;
13504 PyObject *key;
13505 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013506
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 if (dict == NULL) {
13508 PyErr_SetString(PyExc_TypeError,
13509 "format requires a mapping");
13510 goto onError;
13511 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013512 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013513 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013514 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013515 /* Skip over balanced parentheses */
13516 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013517 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13518 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013519 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013520 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013522 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 if (fmtcnt < 0 || pcount > 0) {
13526 PyErr_SetString(PyExc_ValueError,
13527 "incomplete format key");
13528 goto onError;
13529 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013530 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013531 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 if (key == NULL)
13533 goto onError;
13534 if (args_owned) {
13535 Py_DECREF(args);
13536 args_owned = 0;
13537 }
13538 args = PyObject_GetItem(dict, key);
13539 Py_DECREF(key);
13540 if (args == NULL) {
13541 goto onError;
13542 }
13543 args_owned = 1;
13544 arglen = -1;
13545 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013546 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013547 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013548 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13549 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 case '-': flags |= F_LJUST; continue;
13551 case '+': flags |= F_SIGN; continue;
13552 case ' ': flags |= F_BLANK; continue;
13553 case '#': flags |= F_ALT; continue;
13554 case '0': flags |= F_ZERO; continue;
13555 }
13556 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013557 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 if (c == '*') {
13559 v = getnextarg(args, arglen, &argidx);
13560 if (v == NULL)
13561 goto onError;
13562 if (!PyLong_Check(v)) {
13563 PyErr_SetString(PyExc_TypeError,
13564 "* wants int");
13565 goto onError;
13566 }
13567 width = PyLong_AsLong(v);
13568 if (width == -1 && PyErr_Occurred())
13569 goto onError;
13570 if (width < 0) {
13571 flags |= F_LJUST;
13572 width = -width;
13573 }
13574 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013575 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013576 }
13577 else if (c >= '0' && c <= '9') {
13578 width = c - '0';
13579 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013580 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013581 if (c < '0' || c > '9')
13582 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013583 /* Since c is unsigned, the RHS would end up as unsigned,
13584 mixing signed and unsigned comparison. Since c is between
13585 '0' and '9', casting to int is safe. */
13586 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 PyErr_SetString(PyExc_ValueError,
13588 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013589 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 }
13591 width = width*10 + (c - '0');
13592 }
13593 }
13594 if (c == '.') {
13595 prec = 0;
13596 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013597 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 if (c == '*') {
13599 v = getnextarg(args, arglen, &argidx);
13600 if (v == NULL)
13601 goto onError;
13602 if (!PyLong_Check(v)) {
13603 PyErr_SetString(PyExc_TypeError,
13604 "* wants int");
13605 goto onError;
13606 }
13607 prec = PyLong_AsLong(v);
13608 if (prec == -1 && PyErr_Occurred())
13609 goto onError;
13610 if (prec < 0)
13611 prec = 0;
13612 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013614 }
13615 else if (c >= '0' && c <= '9') {
13616 prec = c - '0';
13617 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013619 if (c < '0' || c > '9')
13620 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013621 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 PyErr_SetString(PyExc_ValueError,
13623 "prec too big");
13624 goto onError;
13625 }
13626 prec = prec*10 + (c - '0');
13627 }
13628 }
13629 } /* prec */
13630 if (fmtcnt >= 0) {
13631 if (c == 'h' || c == 'l' || c == 'L') {
13632 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013633 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 }
13635 }
13636 if (fmtcnt < 0) {
13637 PyErr_SetString(PyExc_ValueError,
13638 "incomplete format");
13639 goto onError;
13640 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013641 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013642 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013643
13644 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013645 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013646 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013647 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13648 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013649 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013650 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013651
Victor Stinneraff3cc62012-04-30 05:19:21 +020013652 v = getnextarg(args, arglen, &argidx);
13653 if (v == NULL)
13654 goto onError;
13655
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013657 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 fill = ' ';
13659 switch (c) {
13660
Benjamin Peterson29060642009-01-31 22:14:21 +000013661 case 's':
13662 case 'r':
13663 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013664 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13665 /* Fast path */
13666 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13667 goto onError;
13668 goto nextarg;
13669 }
13670
Victor Stinner808fc0a2010-03-22 12:50:40 +000013671 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 temp = v;
13673 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013674 }
13675 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 if (c == 's')
13677 temp = PyObject_Str(v);
13678 else if (c == 'r')
13679 temp = PyObject_Repr(v);
13680 else
13681 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013682 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 break;
13684
13685 case 'i':
13686 case 'd':
13687 case 'u':
13688 case 'o':
13689 case 'x':
13690 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013691 if (PyLong_CheckExact(v)
13692 && width == -1 && prec == -1
13693 && !(flags & (F_SIGN | F_BLANK)))
13694 {
13695 /* Fast path */
13696 switch(c)
13697 {
13698 case 'd':
13699 case 'i':
13700 case 'u':
13701 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13702 goto onError;
13703 goto nextarg;
13704 case 'x':
13705 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13706 goto onError;
13707 goto nextarg;
13708 case 'o':
13709 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13710 goto onError;
13711 goto nextarg;
13712 default:
13713 break;
13714 }
13715 }
13716
Benjamin Peterson29060642009-01-31 22:14:21 +000013717 isnumok = 0;
13718 if (PyNumber_Check(v)) {
13719 PyObject *iobj=NULL;
13720
13721 if (PyLong_Check(v)) {
13722 iobj = v;
13723 Py_INCREF(iobj);
13724 }
13725 else {
13726 iobj = PyNumber_Long(v);
13727 }
13728 if (iobj!=NULL) {
13729 if (PyLong_Check(iobj)) {
13730 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013731 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013732 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 }
13735 else {
13736 Py_DECREF(iobj);
13737 }
13738 }
13739 }
13740 if (!isnumok) {
13741 PyErr_Format(PyExc_TypeError,
13742 "%%%c format: a number is required, "
13743 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13744 goto onError;
13745 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013746 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013747 fill = '0';
13748 break;
13749
13750 case 'e':
13751 case 'E':
13752 case 'f':
13753 case 'F':
13754 case 'g':
13755 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013756 if (width == -1 && prec == -1
13757 && !(flags & (F_SIGN | F_BLANK)))
13758 {
13759 /* Fast path */
13760 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13761 goto onError;
13762 goto nextarg;
13763 }
13764
Benjamin Peterson29060642009-01-31 22:14:21 +000013765 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013766 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013767 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013768 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13769 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013770 break;
13771
13772 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013773 {
13774 Py_UCS4 ch = formatchar(v);
13775 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013776 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013777 if (width == -1 && prec == -1) {
13778 /* Fast path */
13779 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13780 goto onError;
13781 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13782 writer.pos += 1;
13783 goto nextarg;
13784 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013785 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013787 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013788
13789 default:
13790 PyErr_Format(PyExc_ValueError,
13791 "unsupported format character '%c' (0x%x) "
13792 "at index %zd",
13793 (31<=c && c<=126) ? (char)c : '?',
13794 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013795 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013796 goto onError;
13797 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013798 if (temp == NULL)
13799 goto onError;
13800 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013801
13802 if (width == -1 && prec == -1
13803 && !(flags & (F_SIGN | F_BLANK)))
13804 {
13805 /* Fast path */
13806 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13807 goto onError;
13808 goto nextarg;
13809 }
13810
Victor Stinneraff3cc62012-04-30 05:19:21 +020013811 if (PyUnicode_READY(temp) == -1) {
13812 Py_CLEAR(temp);
13813 goto onError;
13814 }
13815 kind = PyUnicode_KIND(temp);
13816 pbuf = PyUnicode_DATA(temp);
13817 len = PyUnicode_GET_LENGTH(temp);
13818
13819 if (c == 's' || c == 'r' || c == 'a') {
13820 if (prec >= 0 && len > prec)
13821 len = prec;
13822 }
13823
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013824 /* pbuf is initialized here. */
13825 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013826 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013827 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13828 if (ch == '-' || ch == '+') {
13829 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013830 len--;
13831 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013832 }
13833 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013834 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013835 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013836 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 else
13838 sign = 0;
13839 }
13840 if (width < len)
13841 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013842
13843 /* Compute the length and maximum character of the
13844 written characters */
13845 bufmaxchar = 127;
13846 if (!(flags & F_LJUST)) {
13847 if (sign) {
13848 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013849 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013850 }
13851 else {
13852 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013853 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013854 }
13855 }
13856 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013857 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013858
13859 buflen = width;
13860 if (sign && len == width)
13861 buflen++;
13862
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013863 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013864 goto onError;
13865
13866 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013868 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013869 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13870 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013871 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013872 if (width > len)
13873 width--;
13874 }
13875 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013876 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013877 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013878 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013879 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13880 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13881 writer.pos += 2;
13882 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013883 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013884 width -= 2;
13885 if (width < 0)
13886 width = 0;
13887 len -= 2;
13888 }
13889 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013890 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013891 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13892 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013893 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013894 }
13895 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013896 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013897 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13898 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013899 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013900 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013901 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13902 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013903 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13904 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13905 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013906 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013907 }
13908 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013909
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013910 if (len) {
13911 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13912 temp, pindex, len);
13913 writer.pos += len;
13914 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013915 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013916 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013917 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13918 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013919 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013920
Victor Stinnerd3f08822012-05-29 12:57:52 +020013921nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013922 if (dict && (argidx < arglen) && c != '%') {
13923 PyErr_SetString(PyExc_TypeError,
13924 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013925 goto onError;
13926 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013927 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013928 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013929 } /* until end */
13930 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013931 PyErr_SetString(PyExc_TypeError,
13932 "not all arguments converted during string formatting");
13933 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013934 }
13935
13936 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013937 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938 }
13939 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013940 Py_XDECREF(temp);
13941 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013942 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013943
Benjamin Peterson29060642009-01-31 22:14:21 +000013944 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013946 Py_XDECREF(temp);
13947 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013948 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013949 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013950 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013951 }
13952 return NULL;
13953}
13954
Jeremy Hylton938ace62002-07-17 16:30:39 +000013955static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013956unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13957
Tim Peters6d6c1a32001-08-02 04:15:00 +000013958static PyObject *
13959unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13960{
Benjamin Peterson29060642009-01-31 22:14:21 +000013961 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013962 static char *kwlist[] = {"object", "encoding", "errors", 0};
13963 char *encoding = NULL;
13964 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013965
Benjamin Peterson14339b62009-01-31 16:36:08 +000013966 if (type != &PyUnicode_Type)
13967 return unicode_subtype_new(type, args, kwds);
13968 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013969 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013971 if (x == NULL) {
13972 Py_INCREF(unicode_empty);
13973 return unicode_empty;
13974 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013975 if (encoding == NULL && errors == NULL)
13976 return PyObject_Str(x);
13977 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013978 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013979}
13980
Guido van Rossume023fe02001-08-30 03:12:59 +000013981static PyObject *
13982unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13983{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013984 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013985 Py_ssize_t length, char_size;
13986 int share_wstr, share_utf8;
13987 unsigned int kind;
13988 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013989
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013991
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013992 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013994 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013995 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013996 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013997 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013998 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013999 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014000
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014001 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014002 if (self == NULL) {
14003 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014004 return NULL;
14005 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014006 kind = PyUnicode_KIND(unicode);
14007 length = PyUnicode_GET_LENGTH(unicode);
14008
14009 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014010#ifdef Py_DEBUG
14011 _PyUnicode_HASH(self) = -1;
14012#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014013 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014014#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014015 _PyUnicode_STATE(self).interned = 0;
14016 _PyUnicode_STATE(self).kind = kind;
14017 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014018 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014019 _PyUnicode_STATE(self).ready = 1;
14020 _PyUnicode_WSTR(self) = NULL;
14021 _PyUnicode_UTF8_LENGTH(self) = 0;
14022 _PyUnicode_UTF8(self) = NULL;
14023 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014024 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014025
14026 share_utf8 = 0;
14027 share_wstr = 0;
14028 if (kind == PyUnicode_1BYTE_KIND) {
14029 char_size = 1;
14030 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14031 share_utf8 = 1;
14032 }
14033 else if (kind == PyUnicode_2BYTE_KIND) {
14034 char_size = 2;
14035 if (sizeof(wchar_t) == 2)
14036 share_wstr = 1;
14037 }
14038 else {
14039 assert(kind == PyUnicode_4BYTE_KIND);
14040 char_size = 4;
14041 if (sizeof(wchar_t) == 4)
14042 share_wstr = 1;
14043 }
14044
14045 /* Ensure we won't overflow the length. */
14046 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14047 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014048 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014049 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014050 data = PyObject_MALLOC((length + 1) * char_size);
14051 if (data == NULL) {
14052 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014053 goto onError;
14054 }
14055
Victor Stinnerc3c74152011-10-02 20:39:55 +020014056 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014057 if (share_utf8) {
14058 _PyUnicode_UTF8_LENGTH(self) = length;
14059 _PyUnicode_UTF8(self) = data;
14060 }
14061 if (share_wstr) {
14062 _PyUnicode_WSTR_LENGTH(self) = length;
14063 _PyUnicode_WSTR(self) = (wchar_t *)data;
14064 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014065
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014066 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014067 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014068 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014069#ifdef Py_DEBUG
14070 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14071#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014072 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014073 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014074
14075onError:
14076 Py_DECREF(unicode);
14077 Py_DECREF(self);
14078 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014079}
14080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014081PyDoc_STRVAR(unicode_doc,
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014082 "str(object[, 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{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014142 int i;
14143
Thomas Wouters477c8d52006-05-27 19:21:47 +000014144 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014145 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014146 0x000A, /* LINE FEED */
14147 0x000D, /* CARRIAGE RETURN */
14148 0x001C, /* FILE SEPARATOR */
14149 0x001D, /* GROUP SEPARATOR */
14150 0x001E, /* RECORD SEPARATOR */
14151 0x0085, /* NEXT LINE */
14152 0x2028, /* LINE SEPARATOR */
14153 0x2029, /* PARAGRAPH SEPARATOR */
14154 };
14155
Fred Drakee4315f52000-05-09 19:53:39 +000014156 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014157 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014158 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014159 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014160 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014161
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014162 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014163 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014164 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014165 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014166
14167 /* initialize the linebreak bloom filter */
14168 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014169 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014170 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014171
14172 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014173
14174#ifdef HAVE_MBCS
14175 winver.dwOSVersionInfoSize = sizeof(winver);
14176 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14177 PyErr_SetFromWindowsErr(0);
14178 return -1;
14179 }
14180#endif
14181 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014182}
14183
14184/* Finalize the Unicode implementation */
14185
Christian Heimesa156e092008-02-16 07:38:31 +000014186int
14187PyUnicode_ClearFreeList(void)
14188{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014189 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014190}
14191
Guido van Rossumd57fd912000-03-10 22:53:23 +000014192void
Thomas Wouters78890102000-07-22 19:25:51 +000014193_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014194{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014195 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014196
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014197 Py_XDECREF(unicode_empty);
14198 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014199
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014200 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014201 if (unicode_latin1[i]) {
14202 Py_DECREF(unicode_latin1[i]);
14203 unicode_latin1[i] = NULL;
14204 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014205 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014206 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014207 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014208}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014209
Walter Dörwald16807132007-05-25 13:52:07 +000014210void
14211PyUnicode_InternInPlace(PyObject **p)
14212{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014213 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014215#ifdef Py_DEBUG
14216 assert(s != NULL);
14217 assert(_PyUnicode_CHECK(s));
14218#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014219 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014220 return;
14221#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014222 /* If it's a subclass, we don't really know what putting
14223 it in the interned dict might do. */
14224 if (!PyUnicode_CheckExact(s))
14225 return;
14226 if (PyUnicode_CHECK_INTERNED(s))
14227 return;
14228 if (interned == NULL) {
14229 interned = PyDict_New();
14230 if (interned == NULL) {
14231 PyErr_Clear(); /* Don't leave an exception */
14232 return;
14233 }
14234 }
14235 /* It might be that the GetItem call fails even
14236 though the key is present in the dictionary,
14237 namely when this happens during a stack overflow. */
14238 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014239 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014240 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014241
Benjamin Peterson29060642009-01-31 22:14:21 +000014242 if (t) {
14243 Py_INCREF(t);
14244 Py_DECREF(*p);
14245 *p = t;
14246 return;
14247 }
Walter Dörwald16807132007-05-25 13:52:07 +000014248
Benjamin Peterson14339b62009-01-31 16:36:08 +000014249 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014250 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014251 PyErr_Clear();
14252 PyThreadState_GET()->recursion_critical = 0;
14253 return;
14254 }
14255 PyThreadState_GET()->recursion_critical = 0;
14256 /* The two references in interned are not counted by refcnt.
14257 The deallocator will take care of this */
14258 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014259 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014260}
14261
14262void
14263PyUnicode_InternImmortal(PyObject **p)
14264{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 PyUnicode_InternInPlace(p);
14266 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014267 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014268 Py_INCREF(*p);
14269 }
Walter Dörwald16807132007-05-25 13:52:07 +000014270}
14271
14272PyObject *
14273PyUnicode_InternFromString(const char *cp)
14274{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 PyObject *s = PyUnicode_FromString(cp);
14276 if (s == NULL)
14277 return NULL;
14278 PyUnicode_InternInPlace(&s);
14279 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014280}
14281
Alexander Belopolsky40018472011-02-26 01:02:56 +000014282void
14283_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014284{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014285 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014286 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014287 Py_ssize_t i, n;
14288 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014289
Benjamin Peterson14339b62009-01-31 16:36:08 +000014290 if (interned == NULL || !PyDict_Check(interned))
14291 return;
14292 keys = PyDict_Keys(interned);
14293 if (keys == NULL || !PyList_Check(keys)) {
14294 PyErr_Clear();
14295 return;
14296 }
Walter Dörwald16807132007-05-25 13:52:07 +000014297
Benjamin Peterson14339b62009-01-31 16:36:08 +000014298 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14299 detector, interned unicode strings are not forcibly deallocated;
14300 rather, we give them their stolen references back, and then clear
14301 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014302
Benjamin Peterson14339b62009-01-31 16:36:08 +000014303 n = PyList_GET_SIZE(keys);
14304 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014305 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014306 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014307 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014308 if (PyUnicode_READY(s) == -1) {
14309 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014310 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014311 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014312 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 case SSTATE_NOT_INTERNED:
14314 /* XXX Shouldn't happen */
14315 break;
14316 case SSTATE_INTERNED_IMMORTAL:
14317 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014318 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014319 break;
14320 case SSTATE_INTERNED_MORTAL:
14321 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014322 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014323 break;
14324 default:
14325 Py_FatalError("Inconsistent interned string state.");
14326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014327 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014328 }
14329 fprintf(stderr, "total size of all interned strings: "
14330 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14331 "mortal/immortal\n", mortal_size, immortal_size);
14332 Py_DECREF(keys);
14333 PyDict_Clear(interned);
14334 Py_DECREF(interned);
14335 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014336}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014337
14338
14339/********************* Unicode Iterator **************************/
14340
14341typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014342 PyObject_HEAD
14343 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014344 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014345} unicodeiterobject;
14346
14347static void
14348unicodeiter_dealloc(unicodeiterobject *it)
14349{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014350 _PyObject_GC_UNTRACK(it);
14351 Py_XDECREF(it->it_seq);
14352 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014353}
14354
14355static int
14356unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14357{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014358 Py_VISIT(it->it_seq);
14359 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014360}
14361
14362static PyObject *
14363unicodeiter_next(unicodeiterobject *it)
14364{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014365 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014366
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 assert(it != NULL);
14368 seq = it->it_seq;
14369 if (seq == NULL)
14370 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014371 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014373 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14374 int kind = PyUnicode_KIND(seq);
14375 void *data = PyUnicode_DATA(seq);
14376 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14377 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014378 if (item != NULL)
14379 ++it->it_index;
14380 return item;
14381 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014382
Benjamin Peterson14339b62009-01-31 16:36:08 +000014383 Py_DECREF(seq);
14384 it->it_seq = NULL;
14385 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014386}
14387
14388static PyObject *
14389unicodeiter_len(unicodeiterobject *it)
14390{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014391 Py_ssize_t len = 0;
14392 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014393 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014394 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014395}
14396
14397PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14398
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014399static PyObject *
14400unicodeiter_reduce(unicodeiterobject *it)
14401{
14402 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014403 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014404 it->it_seq, it->it_index);
14405 } else {
14406 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14407 if (u == NULL)
14408 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014409 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014410 }
14411}
14412
14413PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14414
14415static PyObject *
14416unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14417{
14418 Py_ssize_t index = PyLong_AsSsize_t(state);
14419 if (index == -1 && PyErr_Occurred())
14420 return NULL;
14421 if (index < 0)
14422 index = 0;
14423 it->it_index = index;
14424 Py_RETURN_NONE;
14425}
14426
14427PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14428
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014429static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014430 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014431 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014432 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14433 reduce_doc},
14434 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14435 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014436 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014437};
14438
14439PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014440 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14441 "str_iterator", /* tp_name */
14442 sizeof(unicodeiterobject), /* tp_basicsize */
14443 0, /* tp_itemsize */
14444 /* methods */
14445 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14446 0, /* tp_print */
14447 0, /* tp_getattr */
14448 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014449 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014450 0, /* tp_repr */
14451 0, /* tp_as_number */
14452 0, /* tp_as_sequence */
14453 0, /* tp_as_mapping */
14454 0, /* tp_hash */
14455 0, /* tp_call */
14456 0, /* tp_str */
14457 PyObject_GenericGetAttr, /* tp_getattro */
14458 0, /* tp_setattro */
14459 0, /* tp_as_buffer */
14460 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14461 0, /* tp_doc */
14462 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14463 0, /* tp_clear */
14464 0, /* tp_richcompare */
14465 0, /* tp_weaklistoffset */
14466 PyObject_SelfIter, /* tp_iter */
14467 (iternextfunc)unicodeiter_next, /* tp_iternext */
14468 unicodeiter_methods, /* tp_methods */
14469 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014470};
14471
14472static PyObject *
14473unicode_iter(PyObject *seq)
14474{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014475 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014476
Benjamin Peterson14339b62009-01-31 16:36:08 +000014477 if (!PyUnicode_Check(seq)) {
14478 PyErr_BadInternalCall();
14479 return NULL;
14480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014481 if (PyUnicode_READY(seq) == -1)
14482 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014483 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14484 if (it == NULL)
14485 return NULL;
14486 it->it_index = 0;
14487 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014488 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014489 _PyObject_GC_TRACK(it);
14490 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014491}
14492
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014493
14494size_t
14495Py_UNICODE_strlen(const Py_UNICODE *u)
14496{
14497 int res = 0;
14498 while(*u++)
14499 res++;
14500 return res;
14501}
14502
14503Py_UNICODE*
14504Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14505{
14506 Py_UNICODE *u = s1;
14507 while ((*u++ = *s2++));
14508 return s1;
14509}
14510
14511Py_UNICODE*
14512Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14513{
14514 Py_UNICODE *u = s1;
14515 while ((*u++ = *s2++))
14516 if (n-- == 0)
14517 break;
14518 return s1;
14519}
14520
14521Py_UNICODE*
14522Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14523{
14524 Py_UNICODE *u1 = s1;
14525 u1 += Py_UNICODE_strlen(u1);
14526 Py_UNICODE_strcpy(u1, s2);
14527 return s1;
14528}
14529
14530int
14531Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14532{
14533 while (*s1 && *s2 && *s1 == *s2)
14534 s1++, s2++;
14535 if (*s1 && *s2)
14536 return (*s1 < *s2) ? -1 : +1;
14537 if (*s1)
14538 return 1;
14539 if (*s2)
14540 return -1;
14541 return 0;
14542}
14543
14544int
14545Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14546{
14547 register Py_UNICODE u1, u2;
14548 for (; n != 0; n--) {
14549 u1 = *s1;
14550 u2 = *s2;
14551 if (u1 != u2)
14552 return (u1 < u2) ? -1 : +1;
14553 if (u1 == '\0')
14554 return 0;
14555 s1++;
14556 s2++;
14557 }
14558 return 0;
14559}
14560
14561Py_UNICODE*
14562Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14563{
14564 const Py_UNICODE *p;
14565 for (p = s; *p; p++)
14566 if (*p == c)
14567 return (Py_UNICODE*)p;
14568 return NULL;
14569}
14570
14571Py_UNICODE*
14572Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14573{
14574 const Py_UNICODE *p;
14575 p = s + Py_UNICODE_strlen(s);
14576 while (p != s) {
14577 p--;
14578 if (*p == c)
14579 return (Py_UNICODE*)p;
14580 }
14581 return NULL;
14582}
Victor Stinner331ea922010-08-10 16:37:20 +000014583
Victor Stinner71133ff2010-09-01 23:43:53 +000014584Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014585PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014586{
Victor Stinner577db2c2011-10-11 22:12:48 +020014587 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014588 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014590 if (!PyUnicode_Check(unicode)) {
14591 PyErr_BadArgument();
14592 return NULL;
14593 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014594 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014595 if (u == NULL)
14596 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014597 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014598 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014599 PyErr_NoMemory();
14600 return NULL;
14601 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014602 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014603 size *= sizeof(Py_UNICODE);
14604 copy = PyMem_Malloc(size);
14605 if (copy == NULL) {
14606 PyErr_NoMemory();
14607 return NULL;
14608 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014609 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014610 return copy;
14611}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014612
Georg Brandl66c221e2010-10-14 07:04:07 +000014613/* A _string module, to export formatter_parser and formatter_field_name_split
14614 to the string.Formatter class implemented in Python. */
14615
14616static PyMethodDef _string_methods[] = {
14617 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14618 METH_O, PyDoc_STR("split the argument as a field name")},
14619 {"formatter_parser", (PyCFunction) formatter_parser,
14620 METH_O, PyDoc_STR("parse the argument as a format string")},
14621 {NULL, NULL}
14622};
14623
14624static struct PyModuleDef _string_module = {
14625 PyModuleDef_HEAD_INIT,
14626 "_string",
14627 PyDoc_STR("string helper module"),
14628 0,
14629 _string_methods,
14630 NULL,
14631 NULL,
14632 NULL,
14633 NULL
14634};
14635
14636PyMODINIT_FUNC
14637PyInit__string(void)
14638{
14639 return PyModule_Create(&_string_module);
14640}
14641
14642
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014643#ifdef __cplusplus
14644}
14645#endif