blob: 9c6458db82045a966b0f1c726066c21ad083307d [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"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Guido van Rossumd57fd912000-03-10 22:53:23 +000049/* Endianness switches; defaults to little endian */
50
51#ifdef WORDS_BIGENDIAN
52# define BYTEORDER_IS_BIG_ENDIAN
53#else
54# define BYTEORDER_IS_LITTLE_ENDIAN
55#endif
56
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000057/* --- Globals ------------------------------------------------------------
58
59 The globals are initialized by the _PyUnicode_Init() API and should
60 not be used before calling that API.
61
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner910337b2011-10-03 03:20:16 +020069#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020070# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020071#else
72# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
73#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020074
Victor Stinnere90fe6a2011-10-01 16:48:13 +020075#define _PyUnicode_UTF8(op) \
76 (((PyCompactUnicodeObject*)(op))->utf8)
77#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020078 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079 assert(PyUnicode_IS_READY(op)), \
80 PyUnicode_IS_COMPACT_ASCII(op) ? \
81 ((char*)((PyASCIIObject*)(op) + 1)) : \
82 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020083#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020084 (((PyCompactUnicodeObject*)(op))->utf8_length)
85#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020086 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 assert(PyUnicode_IS_READY(op)), \
88 PyUnicode_IS_COMPACT_ASCII(op) ? \
89 ((PyASCIIObject*)(op))->length : \
90 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020091#define _PyUnicode_WSTR(op) \
92 (((PyASCIIObject*)(op))->wstr)
93#define _PyUnicode_WSTR_LENGTH(op) \
94 (((PyCompactUnicodeObject*)(op))->wstr_length)
95#define _PyUnicode_LENGTH(op) \
96 (((PyASCIIObject *)(op))->length)
97#define _PyUnicode_STATE(op) \
98 (((PyASCIIObject *)(op))->state)
99#define _PyUnicode_HASH(op) \
100 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200101#define _PyUnicode_KIND(op) \
102 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200103 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_GET_LENGTH(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200107#define _PyUnicode_DATA_ANY(op) \
108 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109
Victor Stinner910337b2011-10-03 03:20:16 +0200110#undef PyUnicode_READY
111#define PyUnicode_READY(op) \
112 (assert(_PyUnicode_CHECK(op)), \
113 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200114 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100115 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200116
Victor Stinnerc379ead2011-10-03 12:52:27 +0200117#define _PyUnicode_SHARE_UTF8(op) \
118 (assert(_PyUnicode_CHECK(op)), \
119 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
120 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
121#define _PyUnicode_SHARE_WSTR(op) \
122 (assert(_PyUnicode_CHECK(op)), \
123 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
124
Victor Stinner829c0ad2011-10-03 01:08:02 +0200125/* true if the Unicode object has an allocated UTF-8 memory block
126 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200127#define _PyUnicode_HAS_UTF8_MEMORY(op) \
128 (assert(_PyUnicode_CHECK(op)), \
129 (!PyUnicode_IS_COMPACT_ASCII(op) \
130 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200131 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
132
Victor Stinner03490912011-10-03 23:45:12 +0200133/* true if the Unicode object has an allocated wstr memory block
134 (not shared with other data) */
135#define _PyUnicode_HAS_WSTR_MEMORY(op) \
136 (assert(_PyUnicode_CHECK(op)), \
137 (_PyUnicode_WSTR(op) && \
138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200148 to_type *_to = (to_type *) to; \
149 const from_type *_iter = (begin); \
150 const from_type *_end = (end); \
151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
153 _iter + (n & ~ (Py_ssize_t) 3); \
154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200165/* The Unicode string has been modified: reset the hash */
166#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
167
Walter Dörwald16807132007-05-25 13:52:07 +0000168/* This dictionary holds all interned unicode strings. Note that references
169 to strings in this dictionary are *not* counted in the string's ob_refcnt.
170 When the interned string reaches a refcnt of 0 the string deallocation
171 function will delete the reference from this dictionary.
172
173 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000174 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000175*/
176static PyObject *interned;
177
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000178/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200179static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000180
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200181/* List of static strings. */
182static _Py_Identifier *static_strings;
183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* Single character Unicode strings in the Latin-1 range are being
185 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200186static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187
Christian Heimes190d79e2008-01-30 11:58:22 +0000188/* Fast detection of the most frequent whitespace characters */
189const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000190 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000191/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000192/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000193/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000194/* case 0x000C: * FORM FEED */
195/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000196 0, 1, 1, 1, 1, 1, 0, 0,
197 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000198/* case 0x001C: * FILE SEPARATOR */
199/* case 0x001D: * GROUP SEPARATOR */
200/* case 0x001E: * RECORD SEPARATOR */
201/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000204 1, 0, 0, 0, 0, 0, 0, 0,
205 0, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000208
Benjamin Peterson14339b62009-01-31 16:36:08 +0000209 0, 0, 0, 0, 0, 0, 0, 0,
210 0, 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,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000217};
218
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200219/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200220static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200221static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200222static void copy_characters(
223 PyObject *to, Py_ssize_t to_start,
224 PyObject *from, Py_ssize_t from_start,
225 Py_ssize_t how_many);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200226
Alexander Belopolsky40018472011-02-26 01:02:56 +0000227static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200228unicode_fromascii(const unsigned char *s, Py_ssize_t size);
229static PyObject *
230_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
231static PyObject *
232_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
233static PyObject *
234_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
235
236static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000237unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000238 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100239 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000240 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
241
Alexander Belopolsky40018472011-02-26 01:02:56 +0000242static void
243raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300244 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100245 PyObject *unicode,
246 Py_ssize_t startpos, Py_ssize_t endpos,
247 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000248
Christian Heimes190d79e2008-01-30 11:58:22 +0000249/* Same for linebreaks */
250static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000251 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000252/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000253/* 0x000B, * LINE TABULATION */
254/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000255/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000256 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000257 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000258/* 0x001C, * FILE SEPARATOR */
259/* 0x001D, * GROUP SEPARATOR */
260/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000261 0, 0, 0, 0, 1, 1, 1, 0,
262 0, 0, 0, 0, 0, 0, 0, 0,
263 0, 0, 0, 0, 0, 0, 0, 0,
264 0, 0, 0, 0, 0, 0, 0, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000266
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
268 0, 0, 0, 0, 0, 0, 0, 0,
269 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
Christian Heimes190d79e2008-01-30 11:58:22 +0000275};
276
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300277/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
278 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000279Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000280PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000281{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000282#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 /* This is actually an illegal character, so it should
286 not be passed to unichr. */
287 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000288#endif
289}
290
Victor Stinner910337b2011-10-03 03:20:16 +0200291#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200292int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100293_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200294{
295 PyASCIIObject *ascii;
296 unsigned int kind;
297
298 assert(PyUnicode_Check(op));
299
300 ascii = (PyASCIIObject *)op;
301 kind = ascii->state.kind;
302
Victor Stinnera3b334d2011-10-03 13:53:37 +0200303 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200304 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200305 assert(ascii->state.ready == 1);
306 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200307 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200308 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200309 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200310
Victor Stinnera41463c2011-10-04 01:05:08 +0200311 if (ascii->state.compact == 1) {
312 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200313 assert(kind == PyUnicode_1BYTE_KIND
314 || kind == PyUnicode_2BYTE_KIND
315 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200316 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200318 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100319 }
320 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
322
323 data = unicode->data.any;
324 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100325 assert(ascii->length == 0);
326 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 assert(ascii->state.compact == 0);
328 assert(ascii->state.ascii == 0);
329 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100330 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200331 assert(ascii->wstr != NULL);
332 assert(data == NULL);
333 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 }
335 else {
336 assert(kind == PyUnicode_1BYTE_KIND
337 || kind == PyUnicode_2BYTE_KIND
338 || kind == PyUnicode_4BYTE_KIND);
339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ready == 1);
341 assert(data != NULL);
342 if (ascii->state.ascii) {
343 assert (compact->utf8 == data);
344 assert (compact->utf8_length == ascii->length);
345 }
346 else
347 assert (compact->utf8 != data);
348 }
349 }
350 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200351 if (
352#if SIZEOF_WCHAR_T == 2
353 kind == PyUnicode_2BYTE_KIND
354#else
355 kind == PyUnicode_4BYTE_KIND
356#endif
357 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200358 {
359 assert(ascii->wstr == data);
360 assert(compact->wstr_length == ascii->length);
361 } else
362 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200363 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200364
365 if (compact->utf8 == NULL)
366 assert(compact->utf8_length == 0);
367 if (ascii->wstr == NULL)
368 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200369 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200370 /* check that the best kind is used */
371 if (check_content && kind != PyUnicode_WCHAR_KIND)
372 {
373 Py_ssize_t i;
374 Py_UCS4 maxchar = 0;
375 void *data = PyUnicode_DATA(ascii);
376 for (i=0; i < ascii->length; i++)
377 {
378 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
379 if (ch > maxchar)
380 maxchar = ch;
381 }
Victor Stinnerda29cc32011-11-21 14:31:41 +0100382 if (maxchar > 0x10FFFF) {
383 printf("Invalid Unicode string! {");
384 for (i=0; i < ascii->length; i++)
385 {
386 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
387 if (i)
388 printf(", U+%04x", ch);
389 else
390 printf("U+%04x", ch);
391 }
Victor Stinner5bbe5e72011-11-21 22:54:05 +0100392 printf("} (len=%lu)\n", ascii->length);
Victor Stinnerda29cc32011-11-21 14:31:41 +0100393 abort();
394 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100396 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200397 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100398 assert(maxchar <= 255);
399 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 else
401 assert(maxchar < 128);
402 }
Victor Stinner77faf692011-11-20 18:56:05 +0100403 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100405 assert(maxchar <= 0xFFFF);
406 }
407 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200408 assert(maxchar >= 0x10000);
Victor Stinner77faf692011-11-20 18:56:05 +0100409 assert(maxchar <= 0x10FFFF);
410 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200411 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400412 return 1;
413}
Victor Stinner910337b2011-10-03 03:20:16 +0200414#endif
415
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100416static PyObject*
417unicode_result_wchar(PyObject *unicode)
418{
419#ifndef Py_DEBUG
420 Py_ssize_t len;
421
422 assert(Py_REFCNT(unicode) == 1);
423
424 len = _PyUnicode_WSTR_LENGTH(unicode);
425 if (len == 0) {
426 Py_INCREF(unicode_empty);
427 Py_DECREF(unicode);
428 return unicode_empty;
429 }
430
431 if (len == 1) {
432 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
433 if (ch < 256) {
434 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
435 Py_DECREF(unicode);
436 return latin1_char;
437 }
438 }
439
440 if (_PyUnicode_Ready(unicode) < 0) {
441 Py_XDECREF(unicode);
442 return NULL;
443 }
444#else
445 /* don't make the result ready in debug mode to ensure that the caller
446 makes the string ready before using it */
447 assert(_PyUnicode_CheckConsistency(unicode, 1));
448#endif
449 return unicode;
450}
451
452static PyObject*
453unicode_result_ready(PyObject *unicode)
454{
455 Py_ssize_t length;
456
457 length = PyUnicode_GET_LENGTH(unicode);
458 if (length == 0) {
459 if (unicode != unicode_empty) {
460 Py_INCREF(unicode_empty);
461 Py_DECREF(unicode);
462 }
463 return unicode_empty;
464 }
465
466 if (length == 1) {
467 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
468 if (ch < 256) {
469 PyObject *latin1_char = unicode_latin1[ch];
470 if (latin1_char != NULL) {
471 if (unicode != latin1_char) {
472 Py_INCREF(latin1_char);
473 Py_DECREF(unicode);
474 }
475 return latin1_char;
476 }
477 else {
478 assert(_PyUnicode_CheckConsistency(unicode, 1));
479 Py_INCREF(unicode);
480 unicode_latin1[ch] = unicode;
481 return unicode;
482 }
483 }
484 }
485
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 return unicode;
488}
489
490static PyObject*
491unicode_result(PyObject *unicode)
492{
493 assert(_PyUnicode_CHECK(unicode));
494 if (PyUnicode_IS_READY(unicode))
495 return unicode_result_ready(unicode);
496 else
497 return unicode_result_wchar(unicode);
498}
499
Victor Stinner3a50e702011-10-18 21:21:00 +0200500#ifdef HAVE_MBCS
501static OSVERSIONINFOEX winver;
502#endif
503
Thomas Wouters477c8d52006-05-27 19:21:47 +0000504/* --- Bloom Filters ----------------------------------------------------- */
505
506/* stuff to implement simple "bloom filters" for Unicode characters.
507 to keep things simple, we use a single bitmask, using the least 5
508 bits from each unicode characters as the bit index. */
509
510/* the linebreak mask is set up by Unicode_Init below */
511
Antoine Pitrouf068f942010-01-13 14:19:12 +0000512#if LONG_BIT >= 128
513#define BLOOM_WIDTH 128
514#elif LONG_BIT >= 64
515#define BLOOM_WIDTH 64
516#elif LONG_BIT >= 32
517#define BLOOM_WIDTH 32
518#else
519#error "LONG_BIT is smaller than 32"
520#endif
521
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522#define BLOOM_MASK unsigned long
523
524static BLOOM_MASK bloom_linebreak;
525
Antoine Pitrouf068f942010-01-13 14:19:12 +0000526#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
527#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000528
Benjamin Peterson29060642009-01-31 22:14:21 +0000529#define BLOOM_LINEBREAK(ch) \
530 ((ch) < 128U ? ascii_linebreak[(ch)] : \
531 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532
Alexander Belopolsky40018472011-02-26 01:02:56 +0000533Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200534make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535{
536 /* calculate simple bloom-style bitmask for a given unicode string */
537
Antoine Pitrouf068f942010-01-13 14:19:12 +0000538 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539 Py_ssize_t i;
540
541 mask = 0;
542 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200543 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544
545 return mask;
546}
547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200548#define BLOOM_MEMBER(mask, chr, str) \
549 (BLOOM(mask, chr) \
550 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200552/* Compilation of templated routines */
553
554#include "stringlib/asciilib.h"
555#include "stringlib/fastsearch.h"
556#include "stringlib/partition.h"
557#include "stringlib/split.h"
558#include "stringlib/count.h"
559#include "stringlib/find.h"
560#include "stringlib/find_max_char.h"
561#include "stringlib/localeutil.h"
562#include "stringlib/undef.h"
563
564#include "stringlib/ucs1lib.h"
565#include "stringlib/fastsearch.h"
566#include "stringlib/partition.h"
567#include "stringlib/split.h"
568#include "stringlib/count.h"
569#include "stringlib/find.h"
570#include "stringlib/find_max_char.h"
571#include "stringlib/localeutil.h"
572#include "stringlib/undef.h"
573
574#include "stringlib/ucs2lib.h"
575#include "stringlib/fastsearch.h"
576#include "stringlib/partition.h"
577#include "stringlib/split.h"
578#include "stringlib/count.h"
579#include "stringlib/find.h"
580#include "stringlib/find_max_char.h"
581#include "stringlib/localeutil.h"
582#include "stringlib/undef.h"
583
584#include "stringlib/ucs4lib.h"
585#include "stringlib/fastsearch.h"
586#include "stringlib/partition.h"
587#include "stringlib/split.h"
588#include "stringlib/count.h"
589#include "stringlib/find.h"
590#include "stringlib/find_max_char.h"
591#include "stringlib/localeutil.h"
592#include "stringlib/undef.h"
593
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200594#include "stringlib/unicodedefs.h"
595#include "stringlib/fastsearch.h"
596#include "stringlib/count.h"
597#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100598#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200599
Guido van Rossumd57fd912000-03-10 22:53:23 +0000600/* --- Unicode Object ----------------------------------------------------- */
601
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200602static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200603fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200604
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200605Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
606 Py_ssize_t size, Py_UCS4 ch,
607 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200608{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200609 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
610
611 switch (kind) {
612 case PyUnicode_1BYTE_KIND:
613 {
614 Py_UCS1 ch1 = (Py_UCS1) ch;
615 if (ch1 == ch)
616 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
617 else
618 return -1;
619 }
620 case PyUnicode_2BYTE_KIND:
621 {
622 Py_UCS2 ch2 = (Py_UCS2) ch;
623 if (ch2 == ch)
624 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
625 else
626 return -1;
627 }
628 case PyUnicode_4BYTE_KIND:
629 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
630 default:
631 assert(0);
632 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200634}
635
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636static PyObject*
637resize_compact(PyObject *unicode, Py_ssize_t length)
638{
639 Py_ssize_t char_size;
640 Py_ssize_t struct_size;
641 Py_ssize_t new_size;
642 int share_wstr;
643
644 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200645 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200646 if (PyUnicode_IS_COMPACT_ASCII(unicode))
647 struct_size = sizeof(PyASCIIObject);
648 else
649 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200650 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200651
652 _Py_DEC_REFTOTAL;
653 _Py_ForgetReference(unicode);
654
655 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
656 PyErr_NoMemory();
657 return NULL;
658 }
659 new_size = (struct_size + (length + 1) * char_size);
660
661 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
662 if (unicode == NULL) {
663 PyObject_Del(unicode);
664 PyErr_NoMemory();
665 return NULL;
666 }
667 _Py_NewReference(unicode);
668 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200669 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200670 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200671 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
672 _PyUnicode_WSTR_LENGTH(unicode) = length;
673 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
675 length, 0);
676 return unicode;
677}
678
Alexander Belopolsky40018472011-02-26 01:02:56 +0000679static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000681{
Victor Stinner95663112011-10-04 01:03:50 +0200682 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200683 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000685
Victor Stinner95663112011-10-04 01:03:50 +0200686 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200687
688 if (PyUnicode_IS_READY(unicode)) {
689 Py_ssize_t char_size;
690 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200691 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200692 void *data;
693
694 data = _PyUnicode_DATA_ANY(unicode);
695 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200696 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200697 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
698 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200699 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
700 {
701 PyObject_DEL(_PyUnicode_UTF8(unicode));
702 _PyUnicode_UTF8(unicode) = NULL;
703 _PyUnicode_UTF8_LENGTH(unicode) = 0;
704 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200705
706 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
707 PyErr_NoMemory();
708 return -1;
709 }
710 new_size = (length + 1) * char_size;
711
712 data = (PyObject *)PyObject_REALLOC(data, new_size);
713 if (data == NULL) {
714 PyErr_NoMemory();
715 return -1;
716 }
717 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200718 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200719 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200720 _PyUnicode_WSTR_LENGTH(unicode) = length;
721 }
722 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200723 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200724 _PyUnicode_UTF8_LENGTH(unicode) = length;
725 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200726 _PyUnicode_LENGTH(unicode) = length;
727 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200728 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200729 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200730 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200731 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 }
Victor Stinner95663112011-10-04 01:03:50 +0200733 assert(_PyUnicode_WSTR(unicode) != NULL);
734
735 /* check for integer overflow */
736 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
737 PyErr_NoMemory();
738 return -1;
739 }
740 wstr = _PyUnicode_WSTR(unicode);
741 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
742 if (!wstr) {
743 PyErr_NoMemory();
744 return -1;
745 }
746 _PyUnicode_WSTR(unicode) = wstr;
747 _PyUnicode_WSTR(unicode)[length] = 0;
748 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200749 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000750 return 0;
751}
752
Victor Stinnerfe226c02011-10-03 03:52:20 +0200753static PyObject*
754resize_copy(PyObject *unicode, Py_ssize_t length)
755{
756 Py_ssize_t copy_length;
757 if (PyUnicode_IS_COMPACT(unicode)) {
758 PyObject *copy;
759 assert(PyUnicode_IS_READY(unicode));
760
761 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
762 if (copy == NULL)
763 return NULL;
764
765 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200766 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200767 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200768 }
769 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200770 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200771 assert(_PyUnicode_WSTR(unicode) != NULL);
772 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200773 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774 if (w == NULL)
775 return NULL;
776 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
777 copy_length = Py_MIN(copy_length, length);
778 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
779 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200780 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200781 }
782}
783
Guido van Rossumd57fd912000-03-10 22:53:23 +0000784/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000785 Ux0000 terminated; some code (e.g. new_identifier)
786 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000787
788 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000789 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000790
791*/
792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200793#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200794static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200795#endif
796
Alexander Belopolsky40018472011-02-26 01:02:56 +0000797static PyUnicodeObject *
798_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000799{
800 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200801 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000802
Thomas Wouters477c8d52006-05-27 19:21:47 +0000803 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000804 if (length == 0 && unicode_empty != NULL) {
805 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200806 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000807 }
808
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000809 /* Ensure we won't overflow the size. */
810 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
811 return (PyUnicodeObject *)PyErr_NoMemory();
812 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200813 if (length < 0) {
814 PyErr_SetString(PyExc_SystemError,
815 "Negative size passed to _PyUnicode_New");
816 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000817 }
818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819#ifdef Py_DEBUG
820 ++unicode_old_new_calls;
821#endif
822
823 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
824 if (unicode == NULL)
825 return NULL;
826 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
827 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
828 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000829 PyErr_NoMemory();
830 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832
Jeremy Hyltond8082792003-09-16 19:41:39 +0000833 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000834 * the caller fails before initializing str -- unicode_resize()
835 * reads str[0], and the Keep-Alive optimization can keep memory
836 * allocated for str alive across a call to unicode_dealloc(unicode).
837 * We don't want unicode_resize to read uninitialized memory in
838 * that case.
839 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200840 _PyUnicode_WSTR(unicode)[0] = 0;
841 _PyUnicode_WSTR(unicode)[length] = 0;
842 _PyUnicode_WSTR_LENGTH(unicode) = length;
843 _PyUnicode_HASH(unicode) = -1;
844 _PyUnicode_STATE(unicode).interned = 0;
845 _PyUnicode_STATE(unicode).kind = 0;
846 _PyUnicode_STATE(unicode).compact = 0;
847 _PyUnicode_STATE(unicode).ready = 0;
848 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200849 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200850 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200851 _PyUnicode_UTF8(unicode) = NULL;
852 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100853 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000854 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000855
Benjamin Peterson29060642009-01-31 22:14:21 +0000856 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000857 /* XXX UNREF/NEWREF interface should be more symmetrical */
858 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000859 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000860 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000861 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000862}
863
Victor Stinnerf42dc442011-10-02 23:33:16 +0200864static const char*
865unicode_kind_name(PyObject *unicode)
866{
Victor Stinner42dfd712011-10-03 14:41:45 +0200867 /* don't check consistency: unicode_kind_name() is called from
868 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200869 if (!PyUnicode_IS_COMPACT(unicode))
870 {
871 if (!PyUnicode_IS_READY(unicode))
872 return "wstr";
873 switch(PyUnicode_KIND(unicode))
874 {
875 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200876 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200877 return "legacy ascii";
878 else
879 return "legacy latin1";
880 case PyUnicode_2BYTE_KIND:
881 return "legacy UCS2";
882 case PyUnicode_4BYTE_KIND:
883 return "legacy UCS4";
884 default:
885 return "<legacy invalid kind>";
886 }
887 }
888 assert(PyUnicode_IS_READY(unicode));
889 switch(PyUnicode_KIND(unicode))
890 {
891 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200892 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200893 return "ascii";
894 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200895 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200896 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200897 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200898 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200899 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200900 default:
901 return "<invalid compact kind>";
902 }
903}
904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200906static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200907
908/* Functions wrapping macros for use in debugger */
909char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200910 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200911}
912
913void *_PyUnicode_compact_data(void *unicode) {
914 return _PyUnicode_COMPACT_DATA(unicode);
915}
916void *_PyUnicode_data(void *unicode){
917 printf("obj %p\n", unicode);
918 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
919 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
920 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
921 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
922 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
923 return PyUnicode_DATA(unicode);
924}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200925
926void
927_PyUnicode_Dump(PyObject *op)
928{
929 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200930 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
931 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
932 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200933
Victor Stinnera849a4b2011-10-03 12:12:11 +0200934 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200935 {
936 if (ascii->state.ascii)
937 data = (ascii + 1);
938 else
939 data = (compact + 1);
940 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200941 else
942 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200943 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
944
Victor Stinnera849a4b2011-10-03 12:12:11 +0200945 if (ascii->wstr == data)
946 printf("shared ");
947 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200948
Victor Stinnera3b334d2011-10-03 13:53:37 +0200949 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200950 printf(" (%zu), ", compact->wstr_length);
951 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
952 printf("shared ");
953 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200954 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200955 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200956}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200957#endif
958
959PyObject *
960PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
961{
962 PyObject *obj;
963 PyCompactUnicodeObject *unicode;
964 void *data;
965 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200966 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200967 Py_ssize_t char_size;
968 Py_ssize_t struct_size;
969
970 /* Optimization for empty strings */
971 if (size == 0 && unicode_empty != NULL) {
972 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200973 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 }
975
976#ifdef Py_DEBUG
977 ++unicode_new_new_calls;
978#endif
979
Victor Stinner9e9d6892011-10-04 01:02:02 +0200980 is_ascii = 0;
981 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982 struct_size = sizeof(PyCompactUnicodeObject);
983 if (maxchar < 128) {
984 kind_state = PyUnicode_1BYTE_KIND;
985 char_size = 1;
986 is_ascii = 1;
987 struct_size = sizeof(PyASCIIObject);
988 }
989 else if (maxchar < 256) {
990 kind_state = PyUnicode_1BYTE_KIND;
991 char_size = 1;
992 }
993 else if (maxchar < 65536) {
994 kind_state = PyUnicode_2BYTE_KIND;
995 char_size = 2;
996 if (sizeof(wchar_t) == 2)
997 is_sharing = 1;
998 }
999 else {
1000 kind_state = PyUnicode_4BYTE_KIND;
1001 char_size = 4;
1002 if (sizeof(wchar_t) == 4)
1003 is_sharing = 1;
1004 }
1005
1006 /* Ensure we won't overflow the size. */
1007 if (size < 0) {
1008 PyErr_SetString(PyExc_SystemError,
1009 "Negative size passed to PyUnicode_New");
1010 return NULL;
1011 }
1012 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1013 return PyErr_NoMemory();
1014
1015 /* Duplicated allocation code from _PyObject_New() instead of a call to
1016 * PyObject_New() so we are able to allocate space for the object and
1017 * it's data buffer.
1018 */
1019 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1020 if (obj == NULL)
1021 return PyErr_NoMemory();
1022 obj = PyObject_INIT(obj, &PyUnicode_Type);
1023 if (obj == NULL)
1024 return NULL;
1025
1026 unicode = (PyCompactUnicodeObject *)obj;
1027 if (is_ascii)
1028 data = ((PyASCIIObject*)obj) + 1;
1029 else
1030 data = unicode + 1;
1031 _PyUnicode_LENGTH(unicode) = size;
1032 _PyUnicode_HASH(unicode) = -1;
1033 _PyUnicode_STATE(unicode).interned = 0;
1034 _PyUnicode_STATE(unicode).kind = kind_state;
1035 _PyUnicode_STATE(unicode).compact = 1;
1036 _PyUnicode_STATE(unicode).ready = 1;
1037 _PyUnicode_STATE(unicode).ascii = is_ascii;
1038 if (is_ascii) {
1039 ((char*)data)[size] = 0;
1040 _PyUnicode_WSTR(unicode) = NULL;
1041 }
1042 else if (kind_state == PyUnicode_1BYTE_KIND) {
1043 ((char*)data)[size] = 0;
1044 _PyUnicode_WSTR(unicode) = NULL;
1045 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001047 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 }
1049 else {
1050 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001051 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 if (kind_state == PyUnicode_2BYTE_KIND)
1053 ((Py_UCS2*)data)[size] = 0;
1054 else /* kind_state == PyUnicode_4BYTE_KIND */
1055 ((Py_UCS4*)data)[size] = 0;
1056 if (is_sharing) {
1057 _PyUnicode_WSTR_LENGTH(unicode) = size;
1058 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1059 }
1060 else {
1061 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1062 _PyUnicode_WSTR(unicode) = NULL;
1063 }
1064 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001065 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001066 return obj;
1067}
1068
1069#if SIZEOF_WCHAR_T == 2
1070/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1071 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001072 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073
1074 This function assumes that unicode can hold one more code point than wstr
1075 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001076static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001077unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001078 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079{
1080 const wchar_t *iter;
1081 Py_UCS4 *ucs4_out;
1082
Victor Stinner910337b2011-10-03 03:20:16 +02001083 assert(unicode != NULL);
1084 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1086 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1087
1088 for (iter = begin; iter < end; ) {
1089 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1090 _PyUnicode_GET_LENGTH(unicode)));
1091 if (*iter >= 0xD800 && *iter <= 0xDBFF
1092 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1093 {
1094 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1095 iter += 2;
1096 }
1097 else {
1098 *ucs4_out++ = *iter;
1099 iter++;
1100 }
1101 }
1102 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1103 _PyUnicode_GET_LENGTH(unicode)));
1104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105}
1106#endif
1107
Victor Stinnercd9950f2011-10-02 00:34:53 +02001108static int
1109_PyUnicode_Dirty(PyObject *unicode)
1110{
Victor Stinner910337b2011-10-03 03:20:16 +02001111 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001112 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001113 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001114 "Cannot modify a string having more than 1 reference");
1115 return -1;
1116 }
1117 _PyUnicode_DIRTY(unicode);
1118 return 0;
1119}
1120
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001121static int
1122_copy_characters(PyObject *to, Py_ssize_t to_start,
1123 PyObject *from, Py_ssize_t from_start,
1124 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 unsigned int from_kind, to_kind;
1127 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001128 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001130 assert(PyUnicode_Check(from));
1131 assert(PyUnicode_Check(to));
1132 assert(PyUnicode_IS_READY(from));
1133 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1136 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1137 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001139 if (how_many == 0)
1140 return 0;
1141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001142 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001143 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001145 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001147#ifdef Py_DEBUG
1148 if (!check_maxchar
1149 && (from_kind > to_kind
1150 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1153 Py_UCS4 ch;
1154 Py_ssize_t i;
1155 for (i=0; i < how_many; i++) {
1156 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1157 assert(ch <= to_maxchar);
1158 }
1159 }
1160#endif
1161 fast = (from_kind == to_kind);
1162 if (check_maxchar
1163 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1164 {
1165 /* deny latin1 => ascii */
1166 fast = 0;
1167 }
1168
1169 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001170 Py_MEMCPY((char*)to_data + to_kind * to_start,
1171 (char*)from_data + from_kind * from_start,
1172 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001174 else if (from_kind == PyUnicode_1BYTE_KIND
1175 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001176 {
1177 _PyUnicode_CONVERT_BYTES(
1178 Py_UCS1, Py_UCS2,
1179 PyUnicode_1BYTE_DATA(from) + from_start,
1180 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1181 PyUnicode_2BYTE_DATA(to) + to_start
1182 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001183 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001184 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001185 && to_kind == PyUnicode_4BYTE_KIND)
1186 {
1187 _PyUnicode_CONVERT_BYTES(
1188 Py_UCS1, Py_UCS4,
1189 PyUnicode_1BYTE_DATA(from) + from_start,
1190 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1191 PyUnicode_4BYTE_DATA(to) + to_start
1192 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001193 }
1194 else if (from_kind == PyUnicode_2BYTE_KIND
1195 && to_kind == PyUnicode_4BYTE_KIND)
1196 {
1197 _PyUnicode_CONVERT_BYTES(
1198 Py_UCS2, Py_UCS4,
1199 PyUnicode_2BYTE_DATA(from) + from_start,
1200 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1201 PyUnicode_4BYTE_DATA(to) + to_start
1202 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001203 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001204 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001205 /* check if max_char(from substring) <= max_char(to) */
1206 if (from_kind > to_kind
1207 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001208 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001209 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001210 /* slow path to check for character overflow */
1211 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001212 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001213 Py_ssize_t i;
1214
Victor Stinner56c161a2011-10-06 02:47:11 +02001215#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001216 for (i=0; i < how_many; i++) {
1217 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001218 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001219 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1220 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001221#else
1222 if (!check_maxchar) {
1223 for (i=0; i < how_many; i++) {
1224 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1225 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1226 }
1227 }
1228 else {
1229 for (i=0; i < how_many; i++) {
1230 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1231 if (ch > to_maxchar)
1232 return 1;
1233 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1234 }
1235 }
1236#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001237 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001238 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001239 assert(0 && "inconsistent state");
1240 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001241 }
1242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 return 0;
1244}
1245
1246static void
1247copy_characters(PyObject *to, Py_ssize_t to_start,
1248 PyObject *from, Py_ssize_t from_start,
1249 Py_ssize_t how_many)
1250{
1251 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1252}
1253
1254Py_ssize_t
1255PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1256 PyObject *from, Py_ssize_t from_start,
1257 Py_ssize_t how_many)
1258{
1259 int err;
1260
1261 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1262 PyErr_BadInternalCall();
1263 return -1;
1264 }
1265
1266 if (PyUnicode_READY(from))
1267 return -1;
1268 if (PyUnicode_READY(to))
1269 return -1;
1270
1271 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1272 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1273 PyErr_Format(PyExc_SystemError,
1274 "Cannot write %zi characters at %zi "
1275 "in a string of %zi characters",
1276 how_many, to_start, PyUnicode_GET_LENGTH(to));
1277 return -1;
1278 }
1279
1280 if (how_many == 0)
1281 return 0;
1282
1283 if (_PyUnicode_Dirty(to))
1284 return -1;
1285
1286 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1287 if (err) {
1288 PyErr_Format(PyExc_SystemError,
1289 "Cannot copy %s characters "
1290 "into a string of %s characters",
1291 unicode_kind_name(from),
1292 unicode_kind_name(to));
1293 return -1;
1294 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001295 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296}
1297
Victor Stinner17222162011-09-28 22:15:37 +02001298/* Find the maximum code point and count the number of surrogate pairs so a
1299 correct string length can be computed before converting a string to UCS4.
1300 This function counts single surrogates as a character and not as a pair.
1301
1302 Return 0 on success, or -1 on error. */
1303static int
1304find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1305 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306{
1307 const wchar_t *iter;
1308
Victor Stinnerc53be962011-10-02 21:33:54 +02001309 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 *num_surrogates = 0;
1311 *maxchar = 0;
1312
1313 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001314 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001316#if SIZEOF_WCHAR_T != 2
1317 if (*maxchar >= 0x10000)
1318 return 0;
1319#endif
1320 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001321#if SIZEOF_WCHAR_T == 2
1322 if (*iter >= 0xD800 && *iter <= 0xDBFF
1323 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1324 {
1325 Py_UCS4 surrogate_val;
1326 surrogate_val = (((iter[0] & 0x3FF)<<10)
1327 | (iter[1] & 0x3FF)) + 0x10000;
1328 ++(*num_surrogates);
1329 if (surrogate_val > *maxchar)
1330 *maxchar = surrogate_val;
1331 iter += 2;
1332 }
1333 else
1334 iter++;
1335#else
1336 iter++;
1337#endif
1338 }
1339 return 0;
1340}
1341
1342#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001343static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344#endif
1345
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001346int
1347_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001348{
1349 wchar_t *end;
1350 Py_UCS4 maxchar = 0;
1351 Py_ssize_t num_surrogates;
1352#if SIZEOF_WCHAR_T == 2
1353 Py_ssize_t length_wo_surrogates;
1354#endif
1355
Georg Brandl7597add2011-10-05 16:36:47 +02001356 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001357 strings were created using _PyObject_New() and where no canonical
1358 representation (the str field) has been set yet aka strings
1359 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(_PyUnicode_CHECK(unicode));
1361 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001363 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001364 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001365 /* Actually, it should neither be interned nor be anything else: */
1366 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367
1368#ifdef Py_DEBUG
1369 ++unicode_ready_calls;
1370#endif
1371
1372 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001373 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001374 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376
1377 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001378 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1379 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 PyErr_NoMemory();
1381 return -1;
1382 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001383 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001384 _PyUnicode_WSTR(unicode), end,
1385 PyUnicode_1BYTE_DATA(unicode));
1386 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1387 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1388 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1389 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001390 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001391 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001392 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 }
1394 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001395 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001396 _PyUnicode_UTF8(unicode) = NULL;
1397 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398 }
1399 PyObject_FREE(_PyUnicode_WSTR(unicode));
1400 _PyUnicode_WSTR(unicode) = NULL;
1401 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1402 }
1403 /* In this case we might have to convert down from 4-byte native
1404 wchar_t to 2-byte unicode. */
1405 else if (maxchar < 65536) {
1406 assert(num_surrogates == 0 &&
1407 "FindMaxCharAndNumSurrogatePairs() messed up");
1408
Victor Stinner506f5922011-09-28 22:34:18 +02001409#if SIZEOF_WCHAR_T == 2
1410 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001411 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001412 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1413 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1414 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001415 _PyUnicode_UTF8(unicode) = NULL;
1416 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001417#else
1418 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001419 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001420 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001421 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001422 PyErr_NoMemory();
1423 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 }
Victor Stinner506f5922011-09-28 22:34:18 +02001425 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1426 _PyUnicode_WSTR(unicode), end,
1427 PyUnicode_2BYTE_DATA(unicode));
1428 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1429 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1430 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001431 _PyUnicode_UTF8(unicode) = NULL;
1432 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001433 PyObject_FREE(_PyUnicode_WSTR(unicode));
1434 _PyUnicode_WSTR(unicode) = NULL;
1435 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1436#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437 }
1438 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1439 else {
1440#if SIZEOF_WCHAR_T == 2
1441 /* in case the native representation is 2-bytes, we need to allocate a
1442 new normalized 4-byte version. */
1443 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001444 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1445 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446 PyErr_NoMemory();
1447 return -1;
1448 }
1449 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1450 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001451 _PyUnicode_UTF8(unicode) = NULL;
1452 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001453 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1454 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001455 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 PyObject_FREE(_PyUnicode_WSTR(unicode));
1457 _PyUnicode_WSTR(unicode) = NULL;
1458 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1459#else
1460 assert(num_surrogates == 0);
1461
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001464 _PyUnicode_UTF8(unicode) = NULL;
1465 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1467#endif
1468 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1469 }
1470 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001471 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 return 0;
1473}
1474
Alexander Belopolsky40018472011-02-26 01:02:56 +00001475static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001476unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001477{
Walter Dörwald16807132007-05-25 13:52:07 +00001478 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001479 case SSTATE_NOT_INTERNED:
1480 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001481
Benjamin Peterson29060642009-01-31 22:14:21 +00001482 case SSTATE_INTERNED_MORTAL:
1483 /* revive dead object temporarily for DelItem */
1484 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001485 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001486 Py_FatalError(
1487 "deletion of interned string failed");
1488 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001489
Benjamin Peterson29060642009-01-31 22:14:21 +00001490 case SSTATE_INTERNED_IMMORTAL:
1491 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001492
Benjamin Peterson29060642009-01-31 22:14:21 +00001493 default:
1494 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001495 }
1496
Victor Stinner03490912011-10-03 23:45:12 +02001497 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001498 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001499 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001500 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001501
1502 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001503 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001504 }
1505 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001506 if (_PyUnicode_DATA_ANY(unicode))
1507 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001508 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001509 }
1510}
1511
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512#ifdef Py_DEBUG
1513static int
1514unicode_is_singleton(PyObject *unicode)
1515{
1516 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1517 if (unicode == unicode_empty)
1518 return 1;
1519 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1520 {
1521 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1522 if (ch < 256 && unicode_latin1[ch] == unicode)
1523 return 1;
1524 }
1525 return 0;
1526}
1527#endif
1528
Alexander Belopolsky40018472011-02-26 01:02:56 +00001529static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001530unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001531{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001532 if (Py_REFCNT(unicode) != 1)
1533 return 0;
1534 if (PyUnicode_CHECK_INTERNED(unicode))
1535 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001536#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001537 /* singleton refcount is greater than 1 */
1538 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001539#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001540 return 1;
1541}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001542
Victor Stinnerfe226c02011-10-03 03:52:20 +02001543static int
1544unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1545{
1546 PyObject *unicode;
1547 Py_ssize_t old_length;
1548
1549 assert(p_unicode != NULL);
1550 unicode = *p_unicode;
1551
1552 assert(unicode != NULL);
1553 assert(PyUnicode_Check(unicode));
1554 assert(0 <= length);
1555
Victor Stinner910337b2011-10-03 03:20:16 +02001556 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001557 old_length = PyUnicode_WSTR_LENGTH(unicode);
1558 else
1559 old_length = PyUnicode_GET_LENGTH(unicode);
1560 if (old_length == length)
1561 return 0;
1562
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001563 if (length == 0) {
1564 Py_DECREF(*p_unicode);
1565 *p_unicode = unicode_empty;
1566 Py_INCREF(*p_unicode);
1567 return 0;
1568 }
1569
Victor Stinnerfe226c02011-10-03 03:52:20 +02001570 if (!unicode_resizable(unicode)) {
1571 PyObject *copy = resize_copy(unicode, length);
1572 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001574 Py_DECREF(*p_unicode);
1575 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001577 }
1578
Victor Stinnerfe226c02011-10-03 03:52:20 +02001579 if (PyUnicode_IS_COMPACT(unicode)) {
1580 *p_unicode = resize_compact(unicode, length);
1581 if (*p_unicode == NULL)
1582 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001583 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001584 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001585 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001586 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001587}
1588
Alexander Belopolsky40018472011-02-26 01:02:56 +00001589int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001590PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001591{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592 PyObject *unicode;
1593 if (p_unicode == NULL) {
1594 PyErr_BadInternalCall();
1595 return -1;
1596 }
1597 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001598 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001599 {
1600 PyErr_BadInternalCall();
1601 return -1;
1602 }
1603 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001604}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001605
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001606static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001607unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001608{
1609 PyObject *result;
1610 assert(PyUnicode_IS_READY(*p_unicode));
1611 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1612 return 0;
1613 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1614 maxchar);
1615 if (result == NULL)
1616 return -1;
1617 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1618 PyUnicode_GET_LENGTH(*p_unicode));
1619 Py_DECREF(*p_unicode);
1620 *p_unicode = result;
1621 return 0;
1622}
1623
1624static int
1625unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1626 Py_UCS4 ch)
1627{
1628 if (unicode_widen(p_unicode, ch) < 0)
1629 return -1;
1630 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1631 PyUnicode_DATA(*p_unicode),
1632 (*pos)++, ch);
1633 return 0;
1634}
1635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001636static PyObject*
1637get_latin1_char(unsigned char ch)
1638{
Victor Stinnera464fc12011-10-02 20:39:30 +02001639 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001640 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001641 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 if (!unicode)
1643 return NULL;
1644 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001645 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646 unicode_latin1[ch] = unicode;
1647 }
1648 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001649 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001650}
1651
Alexander Belopolsky40018472011-02-26 01:02:56 +00001652PyObject *
1653PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001654{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001655 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656 Py_UCS4 maxchar = 0;
1657 Py_ssize_t num_surrogates;
1658
1659 if (u == NULL)
1660 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001661
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001662 /* If the Unicode data is known at construction time, we can apply
1663 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 /* Optimization for empty strings */
1666 if (size == 0 && unicode_empty != NULL) {
1667 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001668 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001669 }
Tim Petersced69f82003-09-16 20:30:58 +00001670
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001671 /* Single character Unicode objects in the Latin-1 range are
1672 shared when using this constructor */
1673 if (size == 1 && *u < 256)
1674 return get_latin1_char((unsigned char)*u);
1675
1676 /* If not empty and not single character, copy the Unicode data
1677 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001678 if (find_maxchar_surrogates(u, u + size,
1679 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001680 return NULL;
1681
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001682 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001683 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001684 if (!unicode)
1685 return NULL;
1686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001687 switch (PyUnicode_KIND(unicode)) {
1688 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001689 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1691 break;
1692 case PyUnicode_2BYTE_KIND:
1693#if Py_UNICODE_SIZE == 2
1694 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1695#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001696 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1698#endif
1699 break;
1700 case PyUnicode_4BYTE_KIND:
1701#if SIZEOF_WCHAR_T == 2
1702 /* This is the only case which has to process surrogates, thus
1703 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001704 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705#else
1706 assert(num_surrogates == 0);
1707 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1708#endif
1709 break;
1710 default:
1711 assert(0 && "Impossible state");
1712 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001713
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001714 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001715}
1716
Alexander Belopolsky40018472011-02-26 01:02:56 +00001717PyObject *
1718PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001719{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001720 if (size < 0) {
1721 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001722 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001723 return NULL;
1724 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001725
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001726 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001727 some optimizations which share commonly used objects.
1728 Also, this means the input must be UTF-8, so fall back to the
1729 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001730 if (u != NULL) {
1731
Benjamin Peterson29060642009-01-31 22:14:21 +00001732 /* Optimization for empty strings */
1733 if (size == 0 && unicode_empty != NULL) {
1734 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001735 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001736 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001737
1738 /* Single characters are shared when using this constructor.
1739 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001740 if (size == 1 && (unsigned char)*u < 128)
1741 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001742
1743 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001744 }
1745
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001746 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001747}
1748
Alexander Belopolsky40018472011-02-26 01:02:56 +00001749PyObject *
1750PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001751{
1752 size_t size = strlen(u);
1753 if (size > PY_SSIZE_T_MAX) {
1754 PyErr_SetString(PyExc_OverflowError, "input too long");
1755 return NULL;
1756 }
1757
1758 return PyUnicode_FromStringAndSize(u, size);
1759}
1760
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001761PyObject *
1762_PyUnicode_FromId(_Py_Identifier *id)
1763{
1764 if (!id->object) {
1765 id->object = PyUnicode_FromString(id->string);
1766 if (!id->object)
1767 return NULL;
1768 PyUnicode_InternInPlace(&id->object);
1769 assert(!id->next);
1770 id->next = static_strings;
1771 static_strings = id;
1772 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001773 return id->object;
1774}
1775
1776void
1777_PyUnicode_ClearStaticStrings()
1778{
1779 _Py_Identifier *i;
1780 for (i = static_strings; i; i = i->next) {
1781 Py_DECREF(i->object);
1782 i->object = NULL;
1783 i->next = NULL;
1784 }
1785}
1786
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001787/* Internal function, don't check maximum character */
1788
Victor Stinnere57b1c02011-09-28 22:20:48 +02001789static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001790unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001791{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001792 PyObject *res;
1793#ifdef Py_DEBUG
1794 const unsigned char *p;
1795 const unsigned char *end = s + size;
1796 for (p=s; p < end; p++) {
1797 assert(*p < 128);
1798 }
1799#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001800 if (size == 1)
1801 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001802 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001803 if (!res)
1804 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001805 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001806 return res;
1807}
1808
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001809static Py_UCS4
1810kind_maxchar_limit(unsigned int kind)
1811{
1812 switch(kind) {
1813 case PyUnicode_1BYTE_KIND:
1814 return 0x80;
1815 case PyUnicode_2BYTE_KIND:
1816 return 0x100;
1817 case PyUnicode_4BYTE_KIND:
1818 return 0x10000;
1819 default:
1820 assert(0 && "invalid kind");
1821 return 0x10ffff;
1822 }
1823}
1824
Victor Stinner702c7342011-10-05 13:50:52 +02001825static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001826_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001827{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001829 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001830
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001831 if (size == 0) {
1832 Py_INCREF(unicode_empty);
1833 return unicode_empty;
1834 }
1835 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001836 if (size == 1)
1837 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001838
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001839 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001840 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001841 if (!res)
1842 return NULL;
1843 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001844 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001845 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001846}
1847
Victor Stinnere57b1c02011-09-28 22:20:48 +02001848static PyObject*
1849_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850{
1851 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001852 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001853
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001854 if (size == 0) {
1855 Py_INCREF(unicode_empty);
1856 return unicode_empty;
1857 }
1858 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001859 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001860 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001862 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001863 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001864 if (!res)
1865 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001866 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001868 else {
1869 _PyUnicode_CONVERT_BYTES(
1870 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1871 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001872 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001873 return res;
1874}
1875
Victor Stinnere57b1c02011-09-28 22:20:48 +02001876static PyObject*
1877_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001878{
1879 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001880 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001881
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001882 if (size == 0) {
1883 Py_INCREF(unicode_empty);
1884 return unicode_empty;
1885 }
1886 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001887 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001888 return get_latin1_char((unsigned char)u[0]);
1889
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001890 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001891 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001892 if (!res)
1893 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001894 if (max_char < 256)
1895 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1896 PyUnicode_1BYTE_DATA(res));
1897 else if (max_char < 0x10000)
1898 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1899 PyUnicode_2BYTE_DATA(res));
1900 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001902 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 return res;
1904}
1905
1906PyObject*
1907PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1908{
1909 switch(kind) {
1910 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001911 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001913 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001914 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001915 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001916 default:
1917 assert(0 && "invalid kind");
1918 PyErr_SetString(PyExc_SystemError, "invalid kind");
1919 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001921}
1922
Victor Stinner25a4b292011-10-06 12:31:55 +02001923/* Ensure that a string uses the most efficient storage, if it is not the
1924 case: create a new string with of the right kind. Write NULL into *p_unicode
1925 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001926static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001927unicode_adjust_maxchar(PyObject **p_unicode)
1928{
1929 PyObject *unicode, *copy;
1930 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001931 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001932 unsigned int kind;
1933
1934 assert(p_unicode != NULL);
1935 unicode = *p_unicode;
1936 assert(PyUnicode_IS_READY(unicode));
1937 if (PyUnicode_IS_ASCII(unicode))
1938 return;
1939
1940 len = PyUnicode_GET_LENGTH(unicode);
1941 kind = PyUnicode_KIND(unicode);
1942 if (kind == PyUnicode_1BYTE_KIND) {
1943 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001944 max_char = ucs1lib_find_max_char(u, u + len);
1945 if (max_char >= 128)
1946 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001947 }
1948 else if (kind == PyUnicode_2BYTE_KIND) {
1949 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001950 max_char = ucs2lib_find_max_char(u, u + len);
1951 if (max_char >= 256)
1952 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001953 }
1954 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001955 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001956 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001957 max_char = ucs4lib_find_max_char(u, u + len);
1958 if (max_char >= 0x10000)
1959 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001960 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001961 copy = PyUnicode_New(len, max_char);
1962 copy_characters(copy, 0, unicode, 0, len);
1963 Py_DECREF(unicode);
1964 *p_unicode = copy;
1965}
1966
Victor Stinner034f6cf2011-09-30 02:26:44 +02001967PyObject*
1968PyUnicode_Copy(PyObject *unicode)
1969{
Victor Stinner87af4f22011-11-21 23:03:47 +01001970 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001971 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001972
Victor Stinner034f6cf2011-09-30 02:26:44 +02001973 if (!PyUnicode_Check(unicode)) {
1974 PyErr_BadInternalCall();
1975 return NULL;
1976 }
1977 if (PyUnicode_READY(unicode))
1978 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001979
Victor Stinner87af4f22011-11-21 23:03:47 +01001980 length = PyUnicode_GET_LENGTH(unicode);
1981 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001982 if (!copy)
1983 return NULL;
1984 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1985
Victor Stinner87af4f22011-11-21 23:03:47 +01001986 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1987 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001988 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001989 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001990}
1991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992
Victor Stinnerbc603d12011-10-02 01:00:40 +02001993/* Widen Unicode objects to larger buffers. Don't write terminating null
1994 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995
1996void*
1997_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1998{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001999 Py_ssize_t len;
2000 void *result;
2001 unsigned int skind;
2002
2003 if (PyUnicode_READY(s))
2004 return NULL;
2005
2006 len = PyUnicode_GET_LENGTH(s);
2007 skind = PyUnicode_KIND(s);
2008 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002009 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 return NULL;
2011 }
2012 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002013 case PyUnicode_2BYTE_KIND:
2014 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2015 if (!result)
2016 return PyErr_NoMemory();
2017 assert(skind == PyUnicode_1BYTE_KIND);
2018 _PyUnicode_CONVERT_BYTES(
2019 Py_UCS1, Py_UCS2,
2020 PyUnicode_1BYTE_DATA(s),
2021 PyUnicode_1BYTE_DATA(s) + len,
2022 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002023 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002024 case PyUnicode_4BYTE_KIND:
2025 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2026 if (!result)
2027 return PyErr_NoMemory();
2028 if (skind == PyUnicode_2BYTE_KIND) {
2029 _PyUnicode_CONVERT_BYTES(
2030 Py_UCS2, Py_UCS4,
2031 PyUnicode_2BYTE_DATA(s),
2032 PyUnicode_2BYTE_DATA(s) + len,
2033 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002035 else {
2036 assert(skind == PyUnicode_1BYTE_KIND);
2037 _PyUnicode_CONVERT_BYTES(
2038 Py_UCS1, Py_UCS4,
2039 PyUnicode_1BYTE_DATA(s),
2040 PyUnicode_1BYTE_DATA(s) + len,
2041 result);
2042 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002044 default:
2045 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002046 }
Victor Stinner01698042011-10-04 00:04:26 +02002047 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 return NULL;
2049}
2050
2051static Py_UCS4*
2052as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2053 int copy_null)
2054{
2055 int kind;
2056 void *data;
2057 Py_ssize_t len, targetlen;
2058 if (PyUnicode_READY(string) == -1)
2059 return NULL;
2060 kind = PyUnicode_KIND(string);
2061 data = PyUnicode_DATA(string);
2062 len = PyUnicode_GET_LENGTH(string);
2063 targetlen = len;
2064 if (copy_null)
2065 targetlen++;
2066 if (!target) {
2067 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2068 PyErr_NoMemory();
2069 return NULL;
2070 }
2071 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2072 if (!target) {
2073 PyErr_NoMemory();
2074 return NULL;
2075 }
2076 }
2077 else {
2078 if (targetsize < targetlen) {
2079 PyErr_Format(PyExc_SystemError,
2080 "string is longer than the buffer");
2081 if (copy_null && 0 < targetsize)
2082 target[0] = 0;
2083 return NULL;
2084 }
2085 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002086 if (kind == PyUnicode_1BYTE_KIND) {
2087 Py_UCS1 *start = (Py_UCS1 *) data;
2088 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002089 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002090 else if (kind == PyUnicode_2BYTE_KIND) {
2091 Py_UCS2 *start = (Py_UCS2 *) data;
2092 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2093 }
2094 else {
2095 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002096 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002098 if (copy_null)
2099 target[len] = 0;
2100 return target;
2101}
2102
2103Py_UCS4*
2104PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2105 int copy_null)
2106{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002107 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002108 PyErr_BadInternalCall();
2109 return NULL;
2110 }
2111 return as_ucs4(string, target, targetsize, copy_null);
2112}
2113
2114Py_UCS4*
2115PyUnicode_AsUCS4Copy(PyObject *string)
2116{
2117 return as_ucs4(string, NULL, 0, 1);
2118}
2119
2120#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002121
Alexander Belopolsky40018472011-02-26 01:02:56 +00002122PyObject *
2123PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002124{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002125 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002126 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002127 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002128 PyErr_BadInternalCall();
2129 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002130 }
2131
Martin v. Löwis790465f2008-04-05 20:41:37 +00002132 if (size == -1) {
2133 size = wcslen(w);
2134 }
2135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002136 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002137}
2138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002139#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002140
Walter Dörwald346737f2007-05-31 10:44:43 +00002141static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002142makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2143 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002144{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002145 *fmt++ = '%';
2146 if (width) {
2147 if (zeropad)
2148 *fmt++ = '0';
2149 fmt += sprintf(fmt, "%d", width);
2150 }
2151 if (precision)
2152 fmt += sprintf(fmt, ".%d", precision);
2153 if (longflag)
2154 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002155 else if (longlongflag) {
2156 /* longlongflag should only ever be nonzero on machines with
2157 HAVE_LONG_LONG defined */
2158#ifdef HAVE_LONG_LONG
2159 char *f = PY_FORMAT_LONG_LONG;
2160 while (*f)
2161 *fmt++ = *f++;
2162#else
2163 /* we shouldn't ever get here */
2164 assert(0);
2165 *fmt++ = 'l';
2166#endif
2167 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002168 else if (size_tflag) {
2169 char *f = PY_FORMAT_SIZE_T;
2170 while (*f)
2171 *fmt++ = *f++;
2172 }
2173 *fmt++ = c;
2174 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002175}
2176
Victor Stinner96865452011-03-01 23:44:09 +00002177/* helper for PyUnicode_FromFormatV() */
2178
2179static const char*
2180parse_format_flags(const char *f,
2181 int *p_width, int *p_precision,
2182 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2183{
2184 int width, precision, longflag, longlongflag, size_tflag;
2185
2186 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2187 f++;
2188 width = 0;
2189 while (Py_ISDIGIT((unsigned)*f))
2190 width = (width*10) + *f++ - '0';
2191 precision = 0;
2192 if (*f == '.') {
2193 f++;
2194 while (Py_ISDIGIT((unsigned)*f))
2195 precision = (precision*10) + *f++ - '0';
2196 if (*f == '%') {
2197 /* "%.3%s" => f points to "3" */
2198 f--;
2199 }
2200 }
2201 if (*f == '\0') {
2202 /* bogus format "%.1" => go backward, f points to "1" */
2203 f--;
2204 }
2205 if (p_width != NULL)
2206 *p_width = width;
2207 if (p_precision != NULL)
2208 *p_precision = precision;
2209
2210 /* Handle %ld, %lu, %lld and %llu. */
2211 longflag = 0;
2212 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002213 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002214
2215 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002216 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002217 longflag = 1;
2218 ++f;
2219 }
2220#ifdef HAVE_LONG_LONG
2221 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002222 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002223 longlongflag = 1;
2224 f += 2;
2225 }
2226#endif
2227 }
2228 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002229 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002230 size_tflag = 1;
2231 ++f;
2232 }
2233 if (p_longflag != NULL)
2234 *p_longflag = longflag;
2235 if (p_longlongflag != NULL)
2236 *p_longlongflag = longlongflag;
2237 if (p_size_tflag != NULL)
2238 *p_size_tflag = size_tflag;
2239 return f;
2240}
2241
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002242/* maximum number of characters required for output of %ld. 21 characters
2243 allows for 64-bit integers (in decimal) and an optional sign. */
2244#define MAX_LONG_CHARS 21
2245/* maximum number of characters required for output of %lld.
2246 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2247 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2248#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2249
Walter Dörwaldd2034312007-05-18 16:29:38 +00002250PyObject *
2251PyUnicode_FromFormatV(const char *format, va_list vargs)
2252{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002253 va_list count;
2254 Py_ssize_t callcount = 0;
2255 PyObject **callresults = NULL;
2256 PyObject **callresult = NULL;
2257 Py_ssize_t n = 0;
2258 int width = 0;
2259 int precision = 0;
2260 int zeropad;
2261 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002262 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002263 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002264 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2266 Py_UCS4 argmaxchar;
2267 Py_ssize_t numbersize = 0;
2268 char *numberresults = NULL;
2269 char *numberresult = NULL;
2270 Py_ssize_t i;
2271 int kind;
2272 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002273
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002274 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002275 /* step 1: count the number of %S/%R/%A/%s format specifications
2276 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2277 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002279 * also estimate a upper bound for all the number formats in the string,
2280 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002282 for (f = format; *f; f++) {
2283 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002284 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002285 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2286 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2287 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2288 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002289
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002290 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002291#ifdef HAVE_LONG_LONG
2292 if (longlongflag) {
2293 if (width < MAX_LONG_LONG_CHARS)
2294 width = MAX_LONG_LONG_CHARS;
2295 }
2296 else
2297#endif
2298 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2299 including sign. Decimal takes the most space. This
2300 isn't enough for octal. If a width is specified we
2301 need more (which we allocate later). */
2302 if (width < MAX_LONG_CHARS)
2303 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002304
2305 /* account for the size + '\0' to separate numbers
2306 inside of the numberresults buffer */
2307 numbersize += (width + 1);
2308 }
2309 }
2310 else if ((unsigned char)*f > 127) {
2311 PyErr_Format(PyExc_ValueError,
2312 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2313 "string, got a non-ASCII byte: 0x%02x",
2314 (unsigned char)*f);
2315 return NULL;
2316 }
2317 }
2318 /* step 2: allocate memory for the results of
2319 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2320 if (callcount) {
2321 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2322 if (!callresults) {
2323 PyErr_NoMemory();
2324 return NULL;
2325 }
2326 callresult = callresults;
2327 }
2328 /* step 2.5: allocate memory for the results of formating numbers */
2329 if (numbersize) {
2330 numberresults = PyObject_Malloc(numbersize);
2331 if (!numberresults) {
2332 PyErr_NoMemory();
2333 goto fail;
2334 }
2335 numberresult = numberresults;
2336 }
2337
2338 /* step 3: format numbers and figure out how large a buffer we need */
2339 for (f = format; *f; f++) {
2340 if (*f == '%') {
2341 const char* p;
2342 int longflag;
2343 int longlongflag;
2344 int size_tflag;
2345 int numprinted;
2346
2347 p = f;
2348 zeropad = (f[1] == '0');
2349 f = parse_format_flags(f, &width, &precision,
2350 &longflag, &longlongflag, &size_tflag);
2351 switch (*f) {
2352 case 'c':
2353 {
2354 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002355 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356 n++;
2357 break;
2358 }
2359 case '%':
2360 n++;
2361 break;
2362 case 'i':
2363 case 'd':
2364 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2365 width, precision, *f);
2366 if (longflag)
2367 numprinted = sprintf(numberresult, fmt,
2368 va_arg(count, long));
2369#ifdef HAVE_LONG_LONG
2370 else if (longlongflag)
2371 numprinted = sprintf(numberresult, fmt,
2372 va_arg(count, PY_LONG_LONG));
2373#endif
2374 else if (size_tflag)
2375 numprinted = sprintf(numberresult, fmt,
2376 va_arg(count, Py_ssize_t));
2377 else
2378 numprinted = sprintf(numberresult, fmt,
2379 va_arg(count, int));
2380 n += numprinted;
2381 /* advance by +1 to skip over the '\0' */
2382 numberresult += (numprinted + 1);
2383 assert(*(numberresult - 1) == '\0');
2384 assert(*(numberresult - 2) != '\0');
2385 assert(numprinted >= 0);
2386 assert(numberresult <= numberresults + numbersize);
2387 break;
2388 case 'u':
2389 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2390 width, precision, 'u');
2391 if (longflag)
2392 numprinted = sprintf(numberresult, fmt,
2393 va_arg(count, unsigned long));
2394#ifdef HAVE_LONG_LONG
2395 else if (longlongflag)
2396 numprinted = sprintf(numberresult, fmt,
2397 va_arg(count, unsigned PY_LONG_LONG));
2398#endif
2399 else if (size_tflag)
2400 numprinted = sprintf(numberresult, fmt,
2401 va_arg(count, size_t));
2402 else
2403 numprinted = sprintf(numberresult, fmt,
2404 va_arg(count, unsigned int));
2405 n += numprinted;
2406 numberresult += (numprinted + 1);
2407 assert(*(numberresult - 1) == '\0');
2408 assert(*(numberresult - 2) != '\0');
2409 assert(numprinted >= 0);
2410 assert(numberresult <= numberresults + numbersize);
2411 break;
2412 case 'x':
2413 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2414 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2415 n += numprinted;
2416 numberresult += (numprinted + 1);
2417 assert(*(numberresult - 1) == '\0');
2418 assert(*(numberresult - 2) != '\0');
2419 assert(numprinted >= 0);
2420 assert(numberresult <= numberresults + numbersize);
2421 break;
2422 case 'p':
2423 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2424 /* %p is ill-defined: ensure leading 0x. */
2425 if (numberresult[1] == 'X')
2426 numberresult[1] = 'x';
2427 else if (numberresult[1] != 'x') {
2428 memmove(numberresult + 2, numberresult,
2429 strlen(numberresult) + 1);
2430 numberresult[0] = '0';
2431 numberresult[1] = 'x';
2432 numprinted += 2;
2433 }
2434 n += numprinted;
2435 numberresult += (numprinted + 1);
2436 assert(*(numberresult - 1) == '\0');
2437 assert(*(numberresult - 2) != '\0');
2438 assert(numprinted >= 0);
2439 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002440 break;
2441 case 's':
2442 {
2443 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002444 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002445 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2446 if (!str)
2447 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 /* since PyUnicode_DecodeUTF8 returns already flexible
2449 unicode objects, there is no need to call ready on them */
2450 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002451 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002452 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002453 /* Remember the str and switch to the next slot */
2454 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002455 break;
2456 }
2457 case 'U':
2458 {
2459 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002460 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 if (PyUnicode_READY(obj) == -1)
2462 goto fail;
2463 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002464 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002465 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002466 break;
2467 }
2468 case 'V':
2469 {
2470 PyObject *obj = va_arg(count, PyObject *);
2471 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002472 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002473 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002474 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002475 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002476 if (PyUnicode_READY(obj) == -1)
2477 goto fail;
2478 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002479 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002481 *callresult++ = NULL;
2482 }
2483 else {
2484 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2485 if (!str_obj)
2486 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002487 if (PyUnicode_READY(str_obj)) {
2488 Py_DECREF(str_obj);
2489 goto fail;
2490 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002492 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002494 *callresult++ = str_obj;
2495 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002496 break;
2497 }
2498 case 'S':
2499 {
2500 PyObject *obj = va_arg(count, PyObject *);
2501 PyObject *str;
2502 assert(obj);
2503 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002505 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002507 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 /* Remember the str and switch to the next slot */
2510 *callresult++ = str;
2511 break;
2512 }
2513 case 'R':
2514 {
2515 PyObject *obj = va_arg(count, PyObject *);
2516 PyObject *repr;
2517 assert(obj);
2518 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002520 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002521 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002522 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002523 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002524 /* Remember the repr and switch to the next slot */
2525 *callresult++ = repr;
2526 break;
2527 }
2528 case 'A':
2529 {
2530 PyObject *obj = va_arg(count, PyObject *);
2531 PyObject *ascii;
2532 assert(obj);
2533 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002536 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002537 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002538 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002539 /* Remember the repr and switch to the next slot */
2540 *callresult++ = ascii;
2541 break;
2542 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002543 default:
2544 /* if we stumble upon an unknown
2545 formatting code, copy the rest of
2546 the format string to the output
2547 string. (we cannot just skip the
2548 code, since there's no way to know
2549 what's in the argument list) */
2550 n += strlen(p);
2551 goto expand;
2552 }
2553 } else
2554 n++;
2555 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002556 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002557 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002558 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 we don't have to resize the string.
2560 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002561 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002562 if (!string)
2563 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 kind = PyUnicode_KIND(string);
2565 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002566 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002567 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002569 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002570 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002571 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002572
2573 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2575 /* checking for == because the last argument could be a empty
2576 string, which causes i to point to end, the assert at the end of
2577 the loop */
2578 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002579
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 switch (*f) {
2581 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002582 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 const int ordinal = va_arg(vargs, int);
2584 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002585 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002586 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002587 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002588 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002589 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 case 'p':
2592 /* unused, since we already have the result */
2593 if (*f == 'p')
2594 (void) va_arg(vargs, void *);
2595 else
2596 (void) va_arg(vargs, int);
2597 /* extract the result from numberresults and append. */
2598 for (; *numberresult; ++i, ++numberresult)
2599 PyUnicode_WRITE(kind, data, i, *numberresult);
2600 /* skip over the separating '\0' */
2601 assert(*numberresult == '\0');
2602 numberresult++;
2603 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 break;
2605 case 's':
2606 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002607 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002608 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002609 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 size = PyUnicode_GET_LENGTH(*callresult);
2611 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002612 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002613 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002614 /* We're done with the unicode()/repr() => forget it */
2615 Py_DECREF(*callresult);
2616 /* switch to next unicode()/repr() result */
2617 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002618 break;
2619 }
2620 case 'U':
2621 {
2622 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 Py_ssize_t size;
2624 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2625 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002626 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002627 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002628 break;
2629 }
2630 case 'V':
2631 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002634 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002636 size = PyUnicode_GET_LENGTH(obj);
2637 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002638 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002639 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002640 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641 size = PyUnicode_GET_LENGTH(*callresult);
2642 assert(PyUnicode_KIND(*callresult) <=
2643 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002644 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002646 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002648 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002649 break;
2650 }
2651 case 'S':
2652 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002653 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002655 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 /* unused, since we already have the result */
2657 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002659 copy_characters(string, i, *callresult, 0, size);
2660 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002661 /* We're done with the unicode()/repr() => forget it */
2662 Py_DECREF(*callresult);
2663 /* switch to next unicode()/repr() result */
2664 ++callresult;
2665 break;
2666 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 break;
2670 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002671 for (; *p; ++p, ++i)
2672 PyUnicode_WRITE(kind, data, i, *p);
2673 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002674 goto end;
2675 }
Victor Stinner1205f272010-09-11 00:54:47 +00002676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002677 else {
2678 assert(i < PyUnicode_GET_LENGTH(string));
2679 PyUnicode_WRITE(kind, data, i++, *f);
2680 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002682 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002683
Benjamin Peterson29060642009-01-31 22:14:21 +00002684 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002685 if (callresults)
2686 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 if (numberresults)
2688 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002689 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002690 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002691 if (callresults) {
2692 PyObject **callresult2 = callresults;
2693 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002694 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002695 ++callresult2;
2696 }
2697 PyObject_Free(callresults);
2698 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002699 if (numberresults)
2700 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002701 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002702}
2703
Walter Dörwaldd2034312007-05-18 16:29:38 +00002704PyObject *
2705PyUnicode_FromFormat(const char *format, ...)
2706{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 PyObject* ret;
2708 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002709
2710#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002711 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002712#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002713 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002714#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002715 ret = PyUnicode_FromFormatV(format, vargs);
2716 va_end(vargs);
2717 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002718}
2719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720#ifdef HAVE_WCHAR_H
2721
Victor Stinner5593d8a2010-10-02 11:11:27 +00002722/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2723 convert a Unicode object to a wide character string.
2724
Victor Stinnerd88d9832011-09-06 02:00:05 +02002725 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002726 character) required to convert the unicode object. Ignore size argument.
2727
Victor Stinnerd88d9832011-09-06 02:00:05 +02002728 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002729 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002730 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002731static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002732unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002733 wchar_t *w,
2734 Py_ssize_t size)
2735{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002736 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 const wchar_t *wstr;
2738
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002739 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 if (wstr == NULL)
2741 return -1;
2742
Victor Stinner5593d8a2010-10-02 11:11:27 +00002743 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002744 if (size > res)
2745 size = res + 1;
2746 else
2747 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002748 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002749 return res;
2750 }
2751 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002753}
2754
2755Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002756PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002757 wchar_t *w,
2758 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002759{
2760 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002761 PyErr_BadInternalCall();
2762 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002763 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002764 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002765}
2766
Victor Stinner137c34c2010-09-29 10:25:54 +00002767wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002768PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002769 Py_ssize_t *size)
2770{
2771 wchar_t* buffer;
2772 Py_ssize_t buflen;
2773
2774 if (unicode == NULL) {
2775 PyErr_BadInternalCall();
2776 return NULL;
2777 }
2778
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002779 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002780 if (buflen == -1)
2781 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002782 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002783 PyErr_NoMemory();
2784 return NULL;
2785 }
2786
Victor Stinner137c34c2010-09-29 10:25:54 +00002787 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2788 if (buffer == NULL) {
2789 PyErr_NoMemory();
2790 return NULL;
2791 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002792 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793 if (buflen == -1)
2794 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002795 if (size != NULL)
2796 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002797 return buffer;
2798}
2799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002800#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002801
Alexander Belopolsky40018472011-02-26 01:02:56 +00002802PyObject *
2803PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002806 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002807 PyErr_SetString(PyExc_ValueError,
2808 "chr() arg not in range(0x110000)");
2809 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002810 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 if (ordinal < 256)
2813 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002815 v = PyUnicode_New(1, ordinal);
2816 if (v == NULL)
2817 return NULL;
2818 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002819 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002821}
2822
Alexander Belopolsky40018472011-02-26 01:02:56 +00002823PyObject *
2824PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002825{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002826 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002827 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002828 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002829 if (PyUnicode_READY(obj))
2830 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002831 Py_INCREF(obj);
2832 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002833 }
2834 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002835 /* For a Unicode subtype that's not a Unicode object,
2836 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002837 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002838 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002839 PyErr_Format(PyExc_TypeError,
2840 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002841 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002842 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002843}
2844
Alexander Belopolsky40018472011-02-26 01:02:56 +00002845PyObject *
2846PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002847 const char *encoding,
2848 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002849{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002850 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002851 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002852
Guido van Rossumd57fd912000-03-10 22:53:23 +00002853 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002854 PyErr_BadInternalCall();
2855 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002856 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002857
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002858 /* Decoding bytes objects is the most common case and should be fast */
2859 if (PyBytes_Check(obj)) {
2860 if (PyBytes_GET_SIZE(obj) == 0) {
2861 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002862 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002863 }
2864 else {
2865 v = PyUnicode_Decode(
2866 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2867 encoding, errors);
2868 }
2869 return v;
2870 }
2871
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002872 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002873 PyErr_SetString(PyExc_TypeError,
2874 "decoding str is not supported");
2875 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002876 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002877
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002878 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2879 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2880 PyErr_Format(PyExc_TypeError,
2881 "coercing to str: need bytes, bytearray "
2882 "or buffer-like object, %.80s found",
2883 Py_TYPE(obj)->tp_name);
2884 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002885 }
Tim Petersced69f82003-09-16 20:30:58 +00002886
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002887 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002889 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002890 }
Tim Petersced69f82003-09-16 20:30:58 +00002891 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002892 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002893
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002894 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002895 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002896}
2897
Victor Stinner600d3be2010-06-10 12:00:55 +00002898/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002899 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2900 1 on success. */
2901static int
2902normalize_encoding(const char *encoding,
2903 char *lower,
2904 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002905{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002906 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002907 char *l;
2908 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002909
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002910 if (encoding == NULL) {
2911 strcpy(lower, "utf-8");
2912 return 1;
2913 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002914 e = encoding;
2915 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002916 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002917 while (*e) {
2918 if (l == l_end)
2919 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002920 if (Py_ISUPPER(*e)) {
2921 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002922 }
2923 else if (*e == '_') {
2924 *l++ = '-';
2925 e++;
2926 }
2927 else {
2928 *l++ = *e++;
2929 }
2930 }
2931 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002932 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002933}
2934
Alexander Belopolsky40018472011-02-26 01:02:56 +00002935PyObject *
2936PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002937 Py_ssize_t size,
2938 const char *encoding,
2939 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002940{
2941 PyObject *buffer = NULL, *unicode;
2942 Py_buffer info;
2943 char lower[11]; /* Enough for any encoding shortcut */
2944
Fred Drakee4315f52000-05-09 19:53:39 +00002945 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002946 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002947 if ((strcmp(lower, "utf-8") == 0) ||
2948 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002949 return PyUnicode_DecodeUTF8(s, size, errors);
2950 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002951 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002952 (strcmp(lower, "iso-8859-1") == 0))
2953 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002954#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002955 else if (strcmp(lower, "mbcs") == 0)
2956 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002957#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002958 else if (strcmp(lower, "ascii") == 0)
2959 return PyUnicode_DecodeASCII(s, size, errors);
2960 else if (strcmp(lower, "utf-16") == 0)
2961 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2962 else if (strcmp(lower, "utf-32") == 0)
2963 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2964 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002965
2966 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002967 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002968 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002969 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002970 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002971 if (buffer == NULL)
2972 goto onError;
2973 unicode = PyCodec_Decode(buffer, encoding, errors);
2974 if (unicode == NULL)
2975 goto onError;
2976 if (!PyUnicode_Check(unicode)) {
2977 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002978 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002979 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002980 Py_DECREF(unicode);
2981 goto onError;
2982 }
2983 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002984 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002985
Benjamin Peterson29060642009-01-31 22:14:21 +00002986 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002987 Py_XDECREF(buffer);
2988 return NULL;
2989}
2990
Alexander Belopolsky40018472011-02-26 01:02:56 +00002991PyObject *
2992PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002993 const char *encoding,
2994 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002995{
2996 PyObject *v;
2997
2998 if (!PyUnicode_Check(unicode)) {
2999 PyErr_BadArgument();
3000 goto onError;
3001 }
3002
3003 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003004 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003005
3006 /* Decode via the codec registry */
3007 v = PyCodec_Decode(unicode, encoding, errors);
3008 if (v == NULL)
3009 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003010 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003011
Benjamin Peterson29060642009-01-31 22:14:21 +00003012 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003013 return NULL;
3014}
3015
Alexander Belopolsky40018472011-02-26 01:02:56 +00003016PyObject *
3017PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003018 const char *encoding,
3019 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003020{
3021 PyObject *v;
3022
3023 if (!PyUnicode_Check(unicode)) {
3024 PyErr_BadArgument();
3025 goto onError;
3026 }
3027
3028 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003029 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003030
3031 /* Decode via the codec registry */
3032 v = PyCodec_Decode(unicode, encoding, errors);
3033 if (v == NULL)
3034 goto onError;
3035 if (!PyUnicode_Check(v)) {
3036 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003037 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003038 Py_TYPE(v)->tp_name);
3039 Py_DECREF(v);
3040 goto onError;
3041 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003042 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003043
Benjamin Peterson29060642009-01-31 22:14:21 +00003044 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003045 return NULL;
3046}
3047
Alexander Belopolsky40018472011-02-26 01:02:56 +00003048PyObject *
3049PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003050 Py_ssize_t size,
3051 const char *encoding,
3052 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003053{
3054 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003055
Guido van Rossumd57fd912000-03-10 22:53:23 +00003056 unicode = PyUnicode_FromUnicode(s, size);
3057 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003058 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003059 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3060 Py_DECREF(unicode);
3061 return v;
3062}
3063
Alexander Belopolsky40018472011-02-26 01:02:56 +00003064PyObject *
3065PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003066 const char *encoding,
3067 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003068{
3069 PyObject *v;
3070
3071 if (!PyUnicode_Check(unicode)) {
3072 PyErr_BadArgument();
3073 goto onError;
3074 }
3075
3076 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003078
3079 /* Encode via the codec registry */
3080 v = PyCodec_Encode(unicode, encoding, errors);
3081 if (v == NULL)
3082 goto onError;
3083 return v;
3084
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003086 return NULL;
3087}
3088
Victor Stinnerad158722010-10-27 00:25:46 +00003089PyObject *
3090PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003091{
Victor Stinner99b95382011-07-04 14:23:54 +02003092#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003093 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003094#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003095 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003096#else
Victor Stinner793b5312011-04-27 00:24:21 +02003097 PyInterpreterState *interp = PyThreadState_GET()->interp;
3098 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3099 cannot use it to encode and decode filenames before it is loaded. Load
3100 the Python codec requires to encode at least its own filename. Use the C
3101 version of the locale codec until the codec registry is initialized and
3102 the Python codec is loaded.
3103
3104 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3105 cannot only rely on it: check also interp->fscodec_initialized for
3106 subinterpreters. */
3107 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003108 return PyUnicode_AsEncodedString(unicode,
3109 Py_FileSystemDefaultEncoding,
3110 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003111 }
3112 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003113 /* locale encoding with surrogateescape */
3114 wchar_t *wchar;
3115 char *bytes;
3116 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003117 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003118
3119 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3120 if (wchar == NULL)
3121 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003122 bytes = _Py_wchar2char(wchar, &error_pos);
3123 if (bytes == NULL) {
3124 if (error_pos != (size_t)-1) {
3125 char *errmsg = strerror(errno);
3126 PyObject *exc = NULL;
3127 if (errmsg == NULL)
3128 errmsg = "Py_wchar2char() failed";
3129 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003130 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003131 error_pos, error_pos+1,
3132 errmsg);
3133 Py_XDECREF(exc);
3134 }
3135 else
3136 PyErr_NoMemory();
3137 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003138 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003139 }
3140 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003141
3142 bytes_obj = PyBytes_FromString(bytes);
3143 PyMem_Free(bytes);
3144 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003145 }
Victor Stinnerad158722010-10-27 00:25:46 +00003146#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003147}
3148
Alexander Belopolsky40018472011-02-26 01:02:56 +00003149PyObject *
3150PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003151 const char *encoding,
3152 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003153{
3154 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003155 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003156
Guido van Rossumd57fd912000-03-10 22:53:23 +00003157 if (!PyUnicode_Check(unicode)) {
3158 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003159 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003160 }
Fred Drakee4315f52000-05-09 19:53:39 +00003161
Fred Drakee4315f52000-05-09 19:53:39 +00003162 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003163 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003164 if ((strcmp(lower, "utf-8") == 0) ||
3165 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003166 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003167 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003168 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003169 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003170 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003171 }
Victor Stinner37296e82010-06-10 13:36:23 +00003172 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003173 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003174 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003175 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003176#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003177 else if (strcmp(lower, "mbcs") == 0)
3178 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003179#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003180 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003181 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003182 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003183
3184 /* Encode via the codec registry */
3185 v = PyCodec_Encode(unicode, encoding, errors);
3186 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003187 return NULL;
3188
3189 /* The normal path */
3190 if (PyBytes_Check(v))
3191 return v;
3192
3193 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003194 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003195 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003196 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003197
3198 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3199 "encoder %s returned bytearray instead of bytes",
3200 encoding);
3201 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003202 Py_DECREF(v);
3203 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003204 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003205
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003206 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3207 Py_DECREF(v);
3208 return b;
3209 }
3210
3211 PyErr_Format(PyExc_TypeError,
3212 "encoder did not return a bytes object (type=%.400s)",
3213 Py_TYPE(v)->tp_name);
3214 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003215 return NULL;
3216}
3217
Alexander Belopolsky40018472011-02-26 01:02:56 +00003218PyObject *
3219PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003220 const char *encoding,
3221 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003222{
3223 PyObject *v;
3224
3225 if (!PyUnicode_Check(unicode)) {
3226 PyErr_BadArgument();
3227 goto onError;
3228 }
3229
3230 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003231 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003232
3233 /* Encode via the codec registry */
3234 v = PyCodec_Encode(unicode, encoding, errors);
3235 if (v == NULL)
3236 goto onError;
3237 if (!PyUnicode_Check(v)) {
3238 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003239 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003240 Py_TYPE(v)->tp_name);
3241 Py_DECREF(v);
3242 goto onError;
3243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003244 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003245
Benjamin Peterson29060642009-01-31 22:14:21 +00003246 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003247 return NULL;
3248}
3249
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003250PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003251PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003252 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003253 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3254}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003255
Christian Heimes5894ba72007-11-04 11:43:14 +00003256PyObject*
3257PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3258{
Victor Stinner99b95382011-07-04 14:23:54 +02003259#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003260 return PyUnicode_DecodeMBCS(s, size, NULL);
3261#elif defined(__APPLE__)
3262 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3263#else
Victor Stinner793b5312011-04-27 00:24:21 +02003264 PyInterpreterState *interp = PyThreadState_GET()->interp;
3265 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3266 cannot use it to encode and decode filenames before it is loaded. Load
3267 the Python codec requires to encode at least its own filename. Use the C
3268 version of the locale codec until the codec registry is initialized and
3269 the Python codec is loaded.
3270
3271 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3272 cannot only rely on it: check also interp->fscodec_initialized for
3273 subinterpreters. */
3274 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003275 return PyUnicode_Decode(s, size,
3276 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003277 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003278 }
3279 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003280 /* locale encoding with surrogateescape */
3281 wchar_t *wchar;
3282 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003283 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003284
3285 if (s[size] != '\0' || size != strlen(s)) {
3286 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3287 return NULL;
3288 }
3289
Victor Stinner168e1172010-10-16 23:16:16 +00003290 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003291 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003292 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003293
Victor Stinner168e1172010-10-16 23:16:16 +00003294 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003295 PyMem_Free(wchar);
3296 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003297 }
Victor Stinnerad158722010-10-27 00:25:46 +00003298#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003299}
3300
Martin v. Löwis011e8422009-05-05 04:43:17 +00003301
3302int
3303PyUnicode_FSConverter(PyObject* arg, void* addr)
3304{
3305 PyObject *output = NULL;
3306 Py_ssize_t size;
3307 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003308 if (arg == NULL) {
3309 Py_DECREF(*(PyObject**)addr);
3310 return 1;
3311 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003312 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003313 output = arg;
3314 Py_INCREF(output);
3315 }
3316 else {
3317 arg = PyUnicode_FromObject(arg);
3318 if (!arg)
3319 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003321 Py_DECREF(arg);
3322 if (!output)
3323 return 0;
3324 if (!PyBytes_Check(output)) {
3325 Py_DECREF(output);
3326 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3327 return 0;
3328 }
3329 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003330 size = PyBytes_GET_SIZE(output);
3331 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003332 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003333 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003334 Py_DECREF(output);
3335 return 0;
3336 }
3337 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003338 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003339}
3340
3341
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003342int
3343PyUnicode_FSDecoder(PyObject* arg, void* addr)
3344{
3345 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003346 if (arg == NULL) {
3347 Py_DECREF(*(PyObject**)addr);
3348 return 1;
3349 }
3350 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003351 if (PyUnicode_READY(arg))
3352 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003353 output = arg;
3354 Py_INCREF(output);
3355 }
3356 else {
3357 arg = PyBytes_FromObject(arg);
3358 if (!arg)
3359 return 0;
3360 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3361 PyBytes_GET_SIZE(arg));
3362 Py_DECREF(arg);
3363 if (!output)
3364 return 0;
3365 if (!PyUnicode_Check(output)) {
3366 Py_DECREF(output);
3367 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3368 return 0;
3369 }
3370 }
Victor Stinner065836e2011-10-27 01:56:33 +02003371 if (PyUnicode_READY(output) < 0) {
3372 Py_DECREF(output);
3373 return 0;
3374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003375 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003376 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003377 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3378 Py_DECREF(output);
3379 return 0;
3380 }
3381 *(PyObject**)addr = output;
3382 return Py_CLEANUP_SUPPORTED;
3383}
3384
3385
Martin v. Löwis5b222132007-06-10 09:51:05 +00003386char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003388{
Christian Heimesf3863112007-11-22 07:46:41 +00003389 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003390
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003391 if (!PyUnicode_Check(unicode)) {
3392 PyErr_BadArgument();
3393 return NULL;
3394 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003395 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003396 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003397
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003398 if (PyUnicode_UTF8(unicode) == NULL) {
3399 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003400 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3401 if (bytes == NULL)
3402 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003403 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3404 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003405 Py_DECREF(bytes);
3406 return NULL;
3407 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003408 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3409 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3410 PyBytes_AS_STRING(bytes),
3411 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003412 Py_DECREF(bytes);
3413 }
3414
3415 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003416 *psize = PyUnicode_UTF8_LENGTH(unicode);
3417 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003418}
3419
3420char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003421PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003422{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003423 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3424}
3425
3426#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003427static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003428#endif
3429
3430
3431Py_UNICODE *
3432PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003434 const unsigned char *one_byte;
3435#if SIZEOF_WCHAR_T == 4
3436 const Py_UCS2 *two_bytes;
3437#else
3438 const Py_UCS4 *four_bytes;
3439 const Py_UCS4 *ucs4_end;
3440 Py_ssize_t num_surrogates;
3441#endif
3442 wchar_t *w;
3443 wchar_t *wchar_end;
3444
3445 if (!PyUnicode_Check(unicode)) {
3446 PyErr_BadArgument();
3447 return NULL;
3448 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003449 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003450 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003451 assert(_PyUnicode_KIND(unicode) != 0);
3452 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003453
3454#ifdef Py_DEBUG
3455 ++unicode_as_unicode_calls;
3456#endif
3457
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003458 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003459#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003460 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3461 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003462 num_surrogates = 0;
3463
3464 for (; four_bytes < ucs4_end; ++four_bytes) {
3465 if (*four_bytes > 0xFFFF)
3466 ++num_surrogates;
3467 }
3468
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003469 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3470 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3471 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003472 PyErr_NoMemory();
3473 return NULL;
3474 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003475 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003476
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003477 w = _PyUnicode_WSTR(unicode);
3478 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3479 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003480 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3481 if (*four_bytes > 0xFFFF) {
3482 /* encode surrogate pair in this case */
3483 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3484 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3485 }
3486 else
3487 *w = *four_bytes;
3488
3489 if (w > wchar_end) {
3490 assert(0 && "Miscalculated string end");
3491 }
3492 }
3493 *w = 0;
3494#else
3495 /* sizeof(wchar_t) == 4 */
3496 Py_FatalError("Impossible unicode object state, wstr and str "
3497 "should share memory already.");
3498 return NULL;
3499#endif
3500 }
3501 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003502 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3503 (_PyUnicode_LENGTH(unicode) + 1));
3504 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003505 PyErr_NoMemory();
3506 return NULL;
3507 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003508 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3509 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3510 w = _PyUnicode_WSTR(unicode);
3511 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003512
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003513 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3514 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003515 for (; w < wchar_end; ++one_byte, ++w)
3516 *w = *one_byte;
3517 /* null-terminate the wstr */
3518 *w = 0;
3519 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003520 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003521#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003522 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003523 for (; w < wchar_end; ++two_bytes, ++w)
3524 *w = *two_bytes;
3525 /* null-terminate the wstr */
3526 *w = 0;
3527#else
3528 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003529 PyObject_FREE(_PyUnicode_WSTR(unicode));
3530 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531 Py_FatalError("Impossible unicode object state, wstr "
3532 "and str should share memory already.");
3533 return NULL;
3534#endif
3535 }
3536 else {
3537 assert(0 && "This should never happen.");
3538 }
3539 }
3540 }
3541 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003542 *size = PyUnicode_WSTR_LENGTH(unicode);
3543 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003544}
3545
Alexander Belopolsky40018472011-02-26 01:02:56 +00003546Py_UNICODE *
3547PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003548{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003549 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003550}
3551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003552
Alexander Belopolsky40018472011-02-26 01:02:56 +00003553Py_ssize_t
3554PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003555{
3556 if (!PyUnicode_Check(unicode)) {
3557 PyErr_BadArgument();
3558 goto onError;
3559 }
3560 return PyUnicode_GET_SIZE(unicode);
3561
Benjamin Peterson29060642009-01-31 22:14:21 +00003562 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003563 return -1;
3564}
3565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003566Py_ssize_t
3567PyUnicode_GetLength(PyObject *unicode)
3568{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003569 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 PyErr_BadArgument();
3571 return -1;
3572 }
3573
3574 return PyUnicode_GET_LENGTH(unicode);
3575}
3576
3577Py_UCS4
3578PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3579{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003580 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3581 PyErr_BadArgument();
3582 return (Py_UCS4)-1;
3583 }
3584 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3585 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003586 return (Py_UCS4)-1;
3587 }
3588 return PyUnicode_READ_CHAR(unicode, index);
3589}
3590
3591int
3592PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3593{
3594 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003595 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003596 return -1;
3597 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003598 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3599 PyErr_SetString(PyExc_IndexError, "string index out of range");
3600 return -1;
3601 }
3602 if (_PyUnicode_Dirty(unicode))
3603 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003604 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3605 index, ch);
3606 return 0;
3607}
3608
Alexander Belopolsky40018472011-02-26 01:02:56 +00003609const char *
3610PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003611{
Victor Stinner42cb4622010-09-01 19:39:01 +00003612 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003613}
3614
Victor Stinner554f3f02010-06-16 23:33:54 +00003615/* create or adjust a UnicodeDecodeError */
3616static void
3617make_decode_exception(PyObject **exceptionObject,
3618 const char *encoding,
3619 const char *input, Py_ssize_t length,
3620 Py_ssize_t startpos, Py_ssize_t endpos,
3621 const char *reason)
3622{
3623 if (*exceptionObject == NULL) {
3624 *exceptionObject = PyUnicodeDecodeError_Create(
3625 encoding, input, length, startpos, endpos, reason);
3626 }
3627 else {
3628 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3629 goto onError;
3630 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3631 goto onError;
3632 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3633 goto onError;
3634 }
3635 return;
3636
3637onError:
3638 Py_DECREF(*exceptionObject);
3639 *exceptionObject = NULL;
3640}
3641
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642/* error handling callback helper:
3643 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003644 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003645 and adjust various state variables.
3646 return 0 on success, -1 on error
3647*/
3648
Alexander Belopolsky40018472011-02-26 01:02:56 +00003649static int
3650unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003651 const char *encoding, const char *reason,
3652 const char **input, const char **inend, Py_ssize_t *startinpos,
3653 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003654 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003655{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003656 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003657
3658 PyObject *restuple = NULL;
3659 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003660 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003661 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003662 Py_ssize_t requiredsize;
3663 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003664 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003665 int res = -1;
3666
Victor Stinner596a6c42011-11-09 00:02:18 +01003667 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3668 outsize = PyUnicode_GET_LENGTH(*output);
3669 else
3670 outsize = _PyUnicode_WSTR_LENGTH(*output);
3671
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003672 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003673 *errorHandler = PyCodec_LookupError(errors);
3674 if (*errorHandler == NULL)
3675 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003676 }
3677
Victor Stinner554f3f02010-06-16 23:33:54 +00003678 make_decode_exception(exceptionObject,
3679 encoding,
3680 *input, *inend - *input,
3681 *startinpos, *endinpos,
3682 reason);
3683 if (*exceptionObject == NULL)
3684 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003685
3686 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3687 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003688 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003689 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003690 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003691 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003692 }
3693 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003694 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003695 if (PyUnicode_READY(repunicode) < 0)
3696 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003697
3698 /* Copy back the bytes variables, which might have been modified by the
3699 callback */
3700 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3701 if (!inputobj)
3702 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003703 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003704 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003705 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003706 *input = PyBytes_AS_STRING(inputobj);
3707 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003708 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003709 /* we can DECREF safely, as the exception has another reference,
3710 so the object won't go away. */
3711 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003712
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003713 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003714 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003715 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003716 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3717 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003718 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003719
Victor Stinner596a6c42011-11-09 00:02:18 +01003720 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3721 /* need more space? (at least enough for what we
3722 have+the replacement+the rest of the string (starting
3723 at the new input position), so we won't have to check space
3724 when there are no errors in the rest of the string) */
3725 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3726 requiredsize = *outpos + replen + insize-newpos;
3727 if (requiredsize > outsize) {
3728 if (requiredsize<2*outsize)
3729 requiredsize = 2*outsize;
3730 if (unicode_resize(output, requiredsize) < 0)
3731 goto onError;
3732 }
3733 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003734 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003735 copy_characters(*output, *outpos, repunicode, 0, replen);
3736 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003737 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003738 else {
3739 wchar_t *repwstr;
3740 Py_ssize_t repwlen;
3741 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3742 if (repwstr == NULL)
3743 goto onError;
3744 /* need more space? (at least enough for what we
3745 have+the replacement+the rest of the string (starting
3746 at the new input position), so we won't have to check space
3747 when there are no errors in the rest of the string) */
3748 requiredsize = *outpos + repwlen + insize-newpos;
3749 if (requiredsize > outsize) {
3750 if (requiredsize < 2*outsize)
3751 requiredsize = 2*outsize;
3752 if (unicode_resize(output, requiredsize) < 0)
3753 goto onError;
3754 }
3755 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3756 *outpos += repwlen;
3757 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003758 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003759 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003760
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003761 /* we made it! */
3762 res = 0;
3763
Benjamin Peterson29060642009-01-31 22:14:21 +00003764 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003765 Py_XDECREF(restuple);
3766 return res;
3767}
3768
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003769/* --- UTF-7 Codec -------------------------------------------------------- */
3770
Antoine Pitrou244651a2009-05-04 18:56:13 +00003771/* See RFC2152 for details. We encode conservatively and decode liberally. */
3772
3773/* Three simple macros defining base-64. */
3774
3775/* Is c a base-64 character? */
3776
3777#define IS_BASE64(c) \
3778 (((c) >= 'A' && (c) <= 'Z') || \
3779 ((c) >= 'a' && (c) <= 'z') || \
3780 ((c) >= '0' && (c) <= '9') || \
3781 (c) == '+' || (c) == '/')
3782
3783/* given that c is a base-64 character, what is its base-64 value? */
3784
3785#define FROM_BASE64(c) \
3786 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3787 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3788 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3789 (c) == '+' ? 62 : 63)
3790
3791/* What is the base-64 character of the bottom 6 bits of n? */
3792
3793#define TO_BASE64(n) \
3794 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3795
3796/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3797 * decoded as itself. We are permissive on decoding; the only ASCII
3798 * byte not decoding to itself is the + which begins a base64
3799 * string. */
3800
3801#define DECODE_DIRECT(c) \
3802 ((c) <= 127 && (c) != '+')
3803
3804/* The UTF-7 encoder treats ASCII characters differently according to
3805 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3806 * the above). See RFC2152. This array identifies these different
3807 * sets:
3808 * 0 : "Set D"
3809 * alphanumeric and '(),-./:?
3810 * 1 : "Set O"
3811 * !"#$%&*;<=>@[]^_`{|}
3812 * 2 : "whitespace"
3813 * ht nl cr sp
3814 * 3 : special (must be base64 encoded)
3815 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3816 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003817
Tim Petersced69f82003-09-16 20:30:58 +00003818static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003819char utf7_category[128] = {
3820/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3821 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3822/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3823 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3824/* sp ! " # $ % & ' ( ) * + , - . / */
3825 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3826/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3827 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3828/* @ A B C D E F G H I J K L M N O */
3829 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3830/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3831 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3832/* ` a b c d e f g h i j k l m n o */
3833 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3834/* p q r s t u v w x y z { | } ~ del */
3835 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003836};
3837
Antoine Pitrou244651a2009-05-04 18:56:13 +00003838/* ENCODE_DIRECT: this character should be encoded as itself. The
3839 * answer depends on whether we are encoding set O as itself, and also
3840 * on whether we are encoding whitespace as itself. RFC2152 makes it
3841 * clear that the answers to these questions vary between
3842 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003843
Antoine Pitrou244651a2009-05-04 18:56:13 +00003844#define ENCODE_DIRECT(c, directO, directWS) \
3845 ((c) < 128 && (c) > 0 && \
3846 ((utf7_category[(c)] == 0) || \
3847 (directWS && (utf7_category[(c)] == 2)) || \
3848 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003849
Alexander Belopolsky40018472011-02-26 01:02:56 +00003850PyObject *
3851PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003852 Py_ssize_t size,
3853 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003854{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003855 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3856}
3857
Antoine Pitrou244651a2009-05-04 18:56:13 +00003858/* The decoder. The only state we preserve is our read position,
3859 * i.e. how many characters we have consumed. So if we end in the
3860 * middle of a shift sequence we have to back off the read position
3861 * and the output to the beginning of the sequence, otherwise we lose
3862 * all the shift state (seen bits, number of bits seen, high
3863 * surrogate). */
3864
Alexander Belopolsky40018472011-02-26 01:02:56 +00003865PyObject *
3866PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003867 Py_ssize_t size,
3868 const char *errors,
3869 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003870{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003871 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003872 Py_ssize_t startinpos;
3873 Py_ssize_t endinpos;
3874 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003875 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003876 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003877 const char *errmsg = "";
3878 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003879 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003880 unsigned int base64bits = 0;
3881 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003882 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003883 PyObject *errorHandler = NULL;
3884 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003886 /* Start off assuming it's all ASCII. Widen later as necessary. */
3887 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003888 if (!unicode)
3889 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003890 if (size == 0) {
3891 if (consumed)
3892 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003893 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003894 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003895
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003896 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003897 e = s + size;
3898
3899 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003900 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003901 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003902 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003903
Antoine Pitrou244651a2009-05-04 18:56:13 +00003904 if (inShift) { /* in a base-64 section */
3905 if (IS_BASE64(ch)) { /* consume a base-64 character */
3906 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3907 base64bits += 6;
3908 s++;
3909 if (base64bits >= 16) {
3910 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003911 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003912 base64bits -= 16;
3913 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3914 if (surrogate) {
3915 /* expecting a second surrogate */
3916 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003917 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3918 | (outCh & 0x3FF)) + 0x10000;
3919 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3920 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003921 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003922 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003923 }
3924 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003925 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3926 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003927 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003928 }
3929 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003930 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003931 /* first surrogate */
3932 surrogate = outCh;
3933 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003934 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003935 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3936 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003937 }
3938 }
3939 }
3940 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003941 inShift = 0;
3942 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003943 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003944 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3945 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003946 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003947 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003948 if (base64bits > 0) { /* left-over bits */
3949 if (base64bits >= 6) {
3950 /* We've seen at least one base-64 character */
3951 errmsg = "partial character in shift sequence";
3952 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003953 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003954 else {
3955 /* Some bits remain; they should be zero */
3956 if (base64buffer != 0) {
3957 errmsg = "non-zero padding bits in shift sequence";
3958 goto utf7Error;
3959 }
3960 }
3961 }
3962 if (ch != '-') {
3963 /* '-' is absorbed; other terminating
3964 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003965 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3966 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003967 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003968 }
3969 }
3970 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003971 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003972 s++; /* consume '+' */
3973 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003974 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003975 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3976 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003977 }
3978 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003979 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003980 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003981 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003982 }
3983 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003984 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003985 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3986 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003987 s++;
3988 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003989 else {
3990 startinpos = s-starts;
3991 s++;
3992 errmsg = "unexpected special character";
3993 goto utf7Error;
3994 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003995 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003996utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003997 endinpos = s-starts;
3998 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003999 errors, &errorHandler,
4000 "utf7", errmsg,
4001 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004002 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004003 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004004 }
4005
Antoine Pitrou244651a2009-05-04 18:56:13 +00004006 /* end of string */
4007
4008 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4009 /* if we're in an inconsistent state, that's an error */
4010 if (surrogate ||
4011 (base64bits >= 6) ||
4012 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004013 endinpos = size;
4014 if (unicode_decode_call_errorhandler(
4015 errors, &errorHandler,
4016 "utf7", "unterminated shift sequence",
4017 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004018 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004019 goto onError;
4020 if (s < e)
4021 goto restart;
4022 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004023 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004024
4025 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004026 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004027 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004028 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004029 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004030 }
4031 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004032 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004033 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004034 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004035
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004036 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004037 goto onError;
4038
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039 Py_XDECREF(errorHandler);
4040 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004041 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004042
Benjamin Peterson29060642009-01-31 22:14:21 +00004043 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004044 Py_XDECREF(errorHandler);
4045 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004046 Py_DECREF(unicode);
4047 return NULL;
4048}
4049
4050
Alexander Belopolsky40018472011-02-26 01:02:56 +00004051PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004052_PyUnicode_EncodeUTF7(PyObject *str,
4053 int base64SetO,
4054 int base64WhiteSpace,
4055 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004056{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004057 int kind;
4058 void *data;
4059 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004060 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004061 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004062 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004063 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004064 unsigned int base64bits = 0;
4065 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004066 char * out;
4067 char * start;
4068
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004069 if (PyUnicode_READY(str) < 0)
4070 return NULL;
4071 kind = PyUnicode_KIND(str);
4072 data = PyUnicode_DATA(str);
4073 len = PyUnicode_GET_LENGTH(str);
4074
4075 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004076 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004077
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004078 /* It might be possible to tighten this worst case */
4079 allocated = 8 * len;
4080 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004081 return PyErr_NoMemory();
4082
Antoine Pitrou244651a2009-05-04 18:56:13 +00004083 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004084 if (v == NULL)
4085 return NULL;
4086
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004087 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004088 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004089 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004090
Antoine Pitrou244651a2009-05-04 18:56:13 +00004091 if (inShift) {
4092 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4093 /* shifting out */
4094 if (base64bits) { /* output remaining bits */
4095 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4096 base64buffer = 0;
4097 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004098 }
4099 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004100 /* Characters not in the BASE64 set implicitly unshift the sequence
4101 so no '-' is required, except if the character is itself a '-' */
4102 if (IS_BASE64(ch) || ch == '-') {
4103 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004104 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004105 *out++ = (char) ch;
4106 }
4107 else {
4108 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004109 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004110 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004111 else { /* not in a shift sequence */
4112 if (ch == '+') {
4113 *out++ = '+';
4114 *out++ = '-';
4115 }
4116 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4117 *out++ = (char) ch;
4118 }
4119 else {
4120 *out++ = '+';
4121 inShift = 1;
4122 goto encode_char;
4123 }
4124 }
4125 continue;
4126encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004127 if (ch >= 0x10000) {
4128 /* code first surrogate */
4129 base64bits += 16;
4130 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4131 while (base64bits >= 6) {
4132 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4133 base64bits -= 6;
4134 }
4135 /* prepare second surrogate */
4136 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4137 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004138 base64bits += 16;
4139 base64buffer = (base64buffer << 16) | ch;
4140 while (base64bits >= 6) {
4141 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4142 base64bits -= 6;
4143 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004144 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004145 if (base64bits)
4146 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4147 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004148 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004149 if (_PyBytes_Resize(&v, out - start) < 0)
4150 return NULL;
4151 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004152}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004153PyObject *
4154PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4155 Py_ssize_t size,
4156 int base64SetO,
4157 int base64WhiteSpace,
4158 const char *errors)
4159{
4160 PyObject *result;
4161 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4162 if (tmp == NULL)
4163 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004164 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004165 base64WhiteSpace, errors);
4166 Py_DECREF(tmp);
4167 return result;
4168}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004169
Antoine Pitrou244651a2009-05-04 18:56:13 +00004170#undef IS_BASE64
4171#undef FROM_BASE64
4172#undef TO_BASE64
4173#undef DECODE_DIRECT
4174#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004175
Guido van Rossumd57fd912000-03-10 22:53:23 +00004176/* --- UTF-8 Codec -------------------------------------------------------- */
4177
Tim Petersced69f82003-09-16 20:30:58 +00004178static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004179char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004180 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4181 illegal prefix. See RFC 3629 for details */
4182 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4183 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004184 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004185 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4186 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4187 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4188 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004189 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4190 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004191 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4192 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004193 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4194 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4195 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4196 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4197 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004198};
4199
Alexander Belopolsky40018472011-02-26 01:02:56 +00004200PyObject *
4201PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004202 Py_ssize_t size,
4203 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004204{
Walter Dörwald69652032004-09-07 20:24:22 +00004205 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4206}
4207
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004208#include "stringlib/ucs1lib.h"
4209#include "stringlib/codecs.h"
4210#include "stringlib/undef.h"
4211
4212#include "stringlib/ucs2lib.h"
4213#include "stringlib/codecs.h"
4214#include "stringlib/undef.h"
4215
4216#include "stringlib/ucs4lib.h"
4217#include "stringlib/codecs.h"
4218#include "stringlib/undef.h"
4219
Antoine Pitrouab868312009-01-10 15:40:25 +00004220/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4221#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4222
4223/* Mask to quickly check whether a C 'long' contains a
4224 non-ASCII, UTF8-encoded char. */
4225#if (SIZEOF_LONG == 8)
4226# define ASCII_CHAR_MASK 0x8080808080808080L
4227#elif (SIZEOF_LONG == 4)
4228# define ASCII_CHAR_MASK 0x80808080L
4229#else
4230# error C 'long' size should be either 4 or 8!
4231#endif
4232
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004233/* Scans a UTF-8 string and returns the maximum character to be expected
4234 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004235
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004236 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004237 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004238 */
4239static Py_UCS4
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004240utf8_max_char_size_and_char_count(const char *s, Py_ssize_t string_size,
4241 Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004242{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004243 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004244 const unsigned char *p = (const unsigned char *)s;
4245 const unsigned char *end = p + string_size;
4246 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004247
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004248 assert(unicode_size != NULL);
4249
4250 /* By having a cascade of independent loops which fallback onto each
4251 other, we minimize the amount of work done in the average loop
4252 iteration, and we also maximize the CPU's ability to predict
4253 branches correctly (because a given condition will have always the
4254 same boolean outcome except perhaps in the last iteration of the
4255 corresponding loop).
4256 In the general case this brings us rather close to decoding
4257 performance pre-PEP 393, despite the two-pass decoding.
4258
4259 Note that the pure ASCII loop is not duplicated once a non-ASCII
4260 character has been encountered. It is actually a pessimization (by
4261 a significant factor) to use this loop on text with many non-ASCII
4262 characters, and it is important to avoid bad performance on valid
4263 utf-8 data (invalid utf-8 being a different can of worms).
4264 */
4265
4266 /* ASCII */
4267 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004268 /* Only check value if it's not a ASCII char... */
4269 if (*p < 0x80) {
4270 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4271 an explanation. */
4272 if (!((size_t) p & LONG_PTR_MASK)) {
4273 /* Help register allocation */
4274 register const unsigned char *_p = p;
4275 while (_p < aligned_end) {
4276 unsigned long value = *(unsigned long *) _p;
4277 if (value & ASCII_CHAR_MASK)
4278 break;
4279 _p += SIZEOF_LONG;
4280 char_count += SIZEOF_LONG;
4281 }
4282 p = _p;
4283 if (p == end)
4284 break;
4285 }
4286 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004287 if (*p < 0x80)
4288 ++char_count;
4289 else
4290 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004291 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004292 *unicode_size = char_count;
4293 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004294
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004295_ucs1loop:
4296 for (; p < end; ++p) {
4297 if (*p < 0xc4)
4298 char_count += ((*p & 0xc0) != 0x80);
4299 else
4300 goto _ucs2loop;
4301 }
4302 *unicode_size = char_count;
4303 return 255;
4304
4305_ucs2loop:
4306 for (; p < end; ++p) {
4307 if (*p < 0xf0)
4308 char_count += ((*p & 0xc0) != 0x80);
4309 else
4310 goto _ucs4loop;
4311 }
4312 *unicode_size = char_count;
4313 return 65535;
4314
4315_ucs4loop:
4316 for (; p < end; ++p) {
4317 char_count += ((*p & 0xc0) != 0x80);
4318 }
4319 *unicode_size = char_count;
4320 return 65537;
4321}
4322
4323/* Called when we encountered some error that wasn't detected in the original
4324 scan, e.g. an encoded surrogate character. The original maxchar computation
4325 may have been incorrect, so redo it. */
4326static int
4327refit_partial_string(PyObject **unicode, int kind, void *data, Py_ssize_t n)
4328{
4329 PyObject *tmp;
4330 Py_ssize_t k, maxchar;
4331 for (k = 0, maxchar = 0; k < n; k++)
4332 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4333 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(*unicode), maxchar);
4334 if (tmp == NULL)
4335 return -1;
4336 PyUnicode_CopyCharacters(tmp, 0, *unicode, 0, n);
4337 Py_DECREF(*unicode);
4338 *unicode = tmp;
4339 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004340}
4341
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4343 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4344 onError. Potential resizing overallocates, so the result needs to shrink
4345 at the end.
4346*/
4347#define WRITE_MAYBE_FAIL(index, value) \
4348 do { \
4349 if (has_errors) { \
4350 Py_ssize_t pos = index; \
4351 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4352 unicode_resize(&unicode, pos + pos/8) < 0) \
4353 goto onError; \
4354 if (unicode_putchar(&unicode, &pos, value) < 0) \
4355 goto onError; \
4356 } \
4357 else \
4358 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004359 } while (0)
4360
Alexander Belopolsky40018472011-02-26 01:02:56 +00004361PyObject *
4362PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004363 Py_ssize_t size,
4364 const char *errors,
4365 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004366{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004367 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004368 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004369 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004370 Py_ssize_t startinpos;
4371 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004372 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004373 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004374 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004375 PyObject *errorHandler = NULL;
4376 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004377 Py_UCS4 maxchar = 0;
4378 Py_ssize_t unicode_size;
4379 Py_ssize_t i;
4380 int kind;
4381 void *data;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004382 int has_errors = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004383
Walter Dörwald69652032004-09-07 20:24:22 +00004384 if (size == 0) {
4385 if (consumed)
4386 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004387 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004388 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004389 maxchar = utf8_max_char_size_and_char_count(s, size, &unicode_size);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004390 /* When the string is ASCII only, just use memcpy and return.
4391 unicode_size may be != size if there is an incomplete UTF-8
4392 sequence at the end of the ASCII block. */
4393 if (maxchar < 128 && size == unicode_size) {
4394 if (size == 1)
4395 return get_latin1_char((unsigned char)s[0]);
4396
4397 unicode = PyUnicode_New(unicode_size, maxchar);
4398 if (!unicode)
4399 return NULL;
4400 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4401 assert(_PyUnicode_CheckConsistency(unicode, 1));
4402 return unicode;
4403 }
4404
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004405 /* In case of errors, maxchar and size computation might be incorrect;
4406 code below refits and resizes as necessary. */
4407 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 if (!unicode)
4409 return NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004410 kind = PyUnicode_KIND(unicode);
4411 data = PyUnicode_DATA(unicode);
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004412
Guido van Rossumd57fd912000-03-10 22:53:23 +00004413 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004414 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004415 e = s + size;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004416 switch (kind) {
4417 case PyUnicode_1BYTE_KIND:
4418 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4419 break;
4420 case PyUnicode_2BYTE_KIND:
4421 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4422 break;
4423 case PyUnicode_4BYTE_KIND:
4424 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4425 break;
4426 }
4427 if (!has_errors) {
4428 /* Ensure the unicode size calculation was correct */
4429 assert(i == unicode_size);
4430 assert(s == e);
4431 if (consumed)
4432 *consumed = s-starts;
4433 return unicode;
4434 }
4435 /* Fall through to the generic decoding loop for the rest of
4436 the string */
4437 if (refit_partial_string(&unicode, kind, data, i) < 0)
4438 goto onError;
4439
Antoine Pitrouab868312009-01-10 15:40:25 +00004440 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004441
4442 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004443 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004444
4445 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004446 /* Fast path for runs of ASCII characters. Given that common UTF-8
4447 input will consist of an overwhelming majority of ASCII
4448 characters, we try to optimize for this case by checking
4449 as many characters as a C 'long' can contain.
4450 First, check if we can do an aligned read, as most CPUs have
4451 a penalty for unaligned reads.
4452 */
4453 if (!((size_t) s & LONG_PTR_MASK)) {
4454 /* Help register allocation */
4455 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004456 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004457 while (_s < aligned_end) {
4458 /* Read a whole long at a time (either 4 or 8 bytes),
4459 and do a fast unrolled copy if it only contains ASCII
4460 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004461 unsigned long value = *(unsigned long *) _s;
4462 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004463 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004464 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4465 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4466 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4467 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004468#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004469 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4470 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4471 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4472 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004473#endif
4474 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004475 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004476 }
4477 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004478 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004479 if (s == e)
4480 break;
4481 ch = (unsigned char)*s;
4482 }
4483 }
4484
4485 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004486 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004487 s++;
4488 continue;
4489 }
4490
4491 n = utf8_code_length[ch];
4492
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004493 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004494 if (consumed)
4495 break;
4496 else {
4497 errmsg = "unexpected end of data";
4498 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004499 endinpos = startinpos+1;
4500 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4501 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004502 goto utf8Error;
4503 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004504 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004505
4506 switch (n) {
4507
4508 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004509 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 startinpos = s-starts;
4511 endinpos = startinpos+1;
4512 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004513
4514 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004515 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 startinpos = s-starts;
4517 endinpos = startinpos+1;
4518 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004519
4520 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004521 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004522 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004523 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004524 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004525 goto utf8Error;
4526 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004528 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004529 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004530 break;
4531
4532 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004533 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4534 will result in surrogates in range d800-dfff. Surrogates are
4535 not valid UTF-8 so they are rejected.
4536 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4537 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004538 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004539 (s[2] & 0xc0) != 0x80 ||
4540 ((unsigned char)s[0] == 0xE0 &&
4541 (unsigned char)s[1] < 0xA0) ||
4542 ((unsigned char)s[0] == 0xED &&
4543 (unsigned char)s[1] > 0x9F)) {
4544 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004545 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004546 endinpos = startinpos + 1;
4547
4548 /* if s[1] first two bits are 1 and 0, then the invalid
4549 continuation byte is s[2], so increment endinpos by 1,
4550 if not, s[1] is invalid and endinpos doesn't need to
4551 be incremented. */
4552 if ((s[1] & 0xC0) == 0x80)
4553 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 goto utf8Error;
4555 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004556 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004557 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004558 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004559 break;
4560
4561 case 4:
4562 if ((s[1] & 0xc0) != 0x80 ||
4563 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004564 (s[3] & 0xc0) != 0x80 ||
4565 ((unsigned char)s[0] == 0xF0 &&
4566 (unsigned char)s[1] < 0x90) ||
4567 ((unsigned char)s[0] == 0xF4 &&
4568 (unsigned char)s[1] > 0x8F)) {
4569 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004570 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004571 endinpos = startinpos + 1;
4572 if ((s[1] & 0xC0) == 0x80) {
4573 endinpos++;
4574 if ((s[2] & 0xC0) == 0x80)
4575 endinpos++;
4576 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004577 goto utf8Error;
4578 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004579 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004580 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4581 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4582
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004583 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004584 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004585 }
4586 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004587 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004588
Benjamin Peterson29060642009-01-31 22:14:21 +00004589 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004590 if (!has_errors) {
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004591 if (refit_partial_string(&unicode, kind, data, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004592 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004593 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004594 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004595 if (unicode_decode_call_errorhandler(
4596 errors, &errorHandler,
4597 "utf8", errmsg,
4598 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004599 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004600 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004601 /* Update data because unicode_decode_call_errorhandler might have
4602 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004603 data = PyUnicode_DATA(unicode);
4604 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004605 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004607 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004608 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004609
Walter Dörwald69652032004-09-07 20:24:22 +00004610 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004611 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004613 /* Adjust length and ready string when it contained errors and
4614 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004615 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004616 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004617 goto onError;
4618 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004619
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004620 Py_XDECREF(errorHandler);
4621 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004622 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004623 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004624
Benjamin Peterson29060642009-01-31 22:14:21 +00004625 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004626 Py_XDECREF(errorHandler);
4627 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004628 Py_DECREF(unicode);
4629 return NULL;
4630}
4631
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004632#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004633
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004634#ifdef __APPLE__
4635
4636/* Simplified UTF-8 decoder using surrogateescape error handler,
4637 used to decode the command line arguments on Mac OS X. */
4638
4639wchar_t*
4640_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4641{
4642 int n;
4643 const char *e;
4644 wchar_t *unicode, *p;
4645
4646 /* Note: size will always be longer than the resulting Unicode
4647 character count */
4648 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4649 PyErr_NoMemory();
4650 return NULL;
4651 }
4652 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4653 if (!unicode)
4654 return NULL;
4655
4656 /* Unpack UTF-8 encoded data */
4657 p = unicode;
4658 e = s + size;
4659 while (s < e) {
4660 Py_UCS4 ch = (unsigned char)*s;
4661
4662 if (ch < 0x80) {
4663 *p++ = (wchar_t)ch;
4664 s++;
4665 continue;
4666 }
4667
4668 n = utf8_code_length[ch];
4669 if (s + n > e) {
4670 goto surrogateescape;
4671 }
4672
4673 switch (n) {
4674 case 0:
4675 case 1:
4676 goto surrogateescape;
4677
4678 case 2:
4679 if ((s[1] & 0xc0) != 0x80)
4680 goto surrogateescape;
4681 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4682 assert ((ch > 0x007F) && (ch <= 0x07FF));
4683 *p++ = (wchar_t)ch;
4684 break;
4685
4686 case 3:
4687 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4688 will result in surrogates in range d800-dfff. Surrogates are
4689 not valid UTF-8 so they are rejected.
4690 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4691 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4692 if ((s[1] & 0xc0) != 0x80 ||
4693 (s[2] & 0xc0) != 0x80 ||
4694 ((unsigned char)s[0] == 0xE0 &&
4695 (unsigned char)s[1] < 0xA0) ||
4696 ((unsigned char)s[0] == 0xED &&
4697 (unsigned char)s[1] > 0x9F)) {
4698
4699 goto surrogateescape;
4700 }
4701 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4702 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004703 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004704 break;
4705
4706 case 4:
4707 if ((s[1] & 0xc0) != 0x80 ||
4708 (s[2] & 0xc0) != 0x80 ||
4709 (s[3] & 0xc0) != 0x80 ||
4710 ((unsigned char)s[0] == 0xF0 &&
4711 (unsigned char)s[1] < 0x90) ||
4712 ((unsigned char)s[0] == 0xF4 &&
4713 (unsigned char)s[1] > 0x8F)) {
4714 goto surrogateescape;
4715 }
4716 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4717 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4718 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4719
4720#if SIZEOF_WCHAR_T == 4
4721 *p++ = (wchar_t)ch;
4722#else
4723 /* compute and append the two surrogates: */
4724
4725 /* translate from 10000..10FFFF to 0..FFFF */
4726 ch -= 0x10000;
4727
4728 /* high surrogate = top 10 bits added to D800 */
4729 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4730
4731 /* low surrogate = bottom 10 bits added to DC00 */
4732 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4733#endif
4734 break;
4735 }
4736 s += n;
4737 continue;
4738
4739 surrogateescape:
4740 *p++ = 0xDC00 + ch;
4741 s++;
4742 }
4743 *p = L'\0';
4744 return unicode;
4745}
4746
4747#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004748
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004749/* Primary internal function which creates utf8 encoded bytes objects.
4750
4751 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004752 and allocate exactly as much space needed at the end. Else allocate the
4753 maximum possible needed (4 result bytes per Unicode character), and return
4754 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004755*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004756PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004757_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004758{
Tim Peters602f7402002-04-27 18:03:26 +00004759#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004760
Guido van Rossum98297ee2007-11-06 21:34:58 +00004761 Py_ssize_t i; /* index into s of next input byte */
4762 PyObject *result; /* result string object */
4763 char *p; /* next free byte in output buffer */
4764 Py_ssize_t nallocated; /* number of result bytes allocated */
4765 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004766 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004767 PyObject *errorHandler = NULL;
4768 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004769 int kind;
4770 void *data;
4771 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004772 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004774 if (!PyUnicode_Check(unicode)) {
4775 PyErr_BadArgument();
4776 return NULL;
4777 }
4778
4779 if (PyUnicode_READY(unicode) == -1)
4780 return NULL;
4781
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004782 if (PyUnicode_UTF8(unicode))
4783 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4784 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004785
4786 kind = PyUnicode_KIND(unicode);
4787 data = PyUnicode_DATA(unicode);
4788 size = PyUnicode_GET_LENGTH(unicode);
4789
Tim Peters602f7402002-04-27 18:03:26 +00004790 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004791
Tim Peters602f7402002-04-27 18:03:26 +00004792 if (size <= MAX_SHORT_UNICHARS) {
4793 /* Write into the stack buffer; nallocated can't overflow.
4794 * At the end, we'll allocate exactly as much heap space as it
4795 * turns out we need.
4796 */
4797 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004798 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004799 p = stackbuf;
4800 }
4801 else {
4802 /* Overallocate on the heap, and give the excess back at the end. */
4803 nallocated = size * 4;
4804 if (nallocated / 4 != size) /* overflow! */
4805 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004806 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004807 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004808 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004809 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004810 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004811
Tim Peters602f7402002-04-27 18:03:26 +00004812 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004813 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004814
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004815 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004816 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004817 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004818
Guido van Rossumd57fd912000-03-10 22:53:23 +00004819 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004820 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004821 *p++ = (char)(0xc0 | (ch >> 6));
4822 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004823 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004824 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004825 Py_ssize_t repsize, k, startpos;
4826 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827 rep = unicode_encode_call_errorhandler(
4828 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004829 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830 if (!rep)
4831 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004833 if (PyBytes_Check(rep))
4834 repsize = PyBytes_GET_SIZE(rep);
4835 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004836 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004837
4838 if (repsize > 4) {
4839 Py_ssize_t offset;
4840
4841 if (result == NULL)
4842 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004843 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004844 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004846 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4847 /* integer overflow */
4848 PyErr_NoMemory();
4849 goto error;
4850 }
4851 nallocated += repsize - 4;
4852 if (result != NULL) {
4853 if (_PyBytes_Resize(&result, nallocated) < 0)
4854 goto error;
4855 } else {
4856 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004857 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004858 goto error;
4859 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4860 }
4861 p = PyBytes_AS_STRING(result) + offset;
4862 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004864 if (PyBytes_Check(rep)) {
4865 char *prep = PyBytes_AS_STRING(rep);
4866 for(k = repsize; k > 0; k--)
4867 *p++ = *prep++;
4868 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004869 enum PyUnicode_Kind repkind;
4870 void *repdata;
4871
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004872 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004873 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004874 repkind = PyUnicode_KIND(rep);
4875 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004876
4877 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004878 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004879 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004880 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004881 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004882 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004884 goto error;
4885 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004886 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004887 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004888 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004889 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004890 } else if (ch < 0x10000) {
4891 *p++ = (char)(0xe0 | (ch >> 12));
4892 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4893 *p++ = (char)(0x80 | (ch & 0x3f));
4894 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004895 /* Encode UCS4 Unicode ordinals */
4896 *p++ = (char)(0xf0 | (ch >> 18));
4897 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4898 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4899 *p++ = (char)(0x80 | (ch & 0x3f));
4900 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004901 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004902
Guido van Rossum98297ee2007-11-06 21:34:58 +00004903 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004904 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004905 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004906 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004907 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004908 }
4909 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004910 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004911 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004912 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004913 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004914 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004915
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004916 Py_XDECREF(errorHandler);
4917 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004918 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004919 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004920 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004921 Py_XDECREF(errorHandler);
4922 Py_XDECREF(exc);
4923 Py_XDECREF(result);
4924 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004925
Tim Peters602f7402002-04-27 18:03:26 +00004926#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004927}
4928
Alexander Belopolsky40018472011-02-26 01:02:56 +00004929PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004930PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4931 Py_ssize_t size,
4932 const char *errors)
4933{
4934 PyObject *v, *unicode;
4935
4936 unicode = PyUnicode_FromUnicode(s, size);
4937 if (unicode == NULL)
4938 return NULL;
4939 v = _PyUnicode_AsUTF8String(unicode, errors);
4940 Py_DECREF(unicode);
4941 return v;
4942}
4943
4944PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004945PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004946{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004947 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004948}
4949
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950/* --- UTF-32 Codec ------------------------------------------------------- */
4951
4952PyObject *
4953PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004954 Py_ssize_t size,
4955 const char *errors,
4956 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004957{
4958 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4959}
4960
4961PyObject *
4962PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004963 Py_ssize_t size,
4964 const char *errors,
4965 int *byteorder,
4966 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004967{
4968 const char *starts = s;
4969 Py_ssize_t startinpos;
4970 Py_ssize_t endinpos;
4971 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004972 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004973 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004974 int bo = 0; /* assume native ordering by default */
4975 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004976 /* Offsets from q for retrieving bytes in the right order. */
4977#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4978 int iorder[] = {0, 1, 2, 3};
4979#else
4980 int iorder[] = {3, 2, 1, 0};
4981#endif
4982 PyObject *errorHandler = NULL;
4983 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004984
Walter Dörwald41980ca2007-08-16 21:55:45 +00004985 q = (unsigned char *)s;
4986 e = q + size;
4987
4988 if (byteorder)
4989 bo = *byteorder;
4990
4991 /* Check for BOM marks (U+FEFF) in the input and adjust current
4992 byte order setting accordingly. In native mode, the leading BOM
4993 mark is skipped, in all other modes, it is copied to the output
4994 stream as-is (giving a ZWNBSP character). */
4995 if (bo == 0) {
4996 if (size >= 4) {
4997 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004998 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004999#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005000 if (bom == 0x0000FEFF) {
5001 q += 4;
5002 bo = -1;
5003 }
5004 else if (bom == 0xFFFE0000) {
5005 q += 4;
5006 bo = 1;
5007 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005008#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 if (bom == 0x0000FEFF) {
5010 q += 4;
5011 bo = 1;
5012 }
5013 else if (bom == 0xFFFE0000) {
5014 q += 4;
5015 bo = -1;
5016 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005017#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005018 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019 }
5020
5021 if (bo == -1) {
5022 /* force LE */
5023 iorder[0] = 0;
5024 iorder[1] = 1;
5025 iorder[2] = 2;
5026 iorder[3] = 3;
5027 }
5028 else if (bo == 1) {
5029 /* force BE */
5030 iorder[0] = 3;
5031 iorder[1] = 2;
5032 iorder[2] = 1;
5033 iorder[3] = 0;
5034 }
5035
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005036 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005037 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005038 if (!unicode)
5039 return NULL;
5040 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005041 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005042 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005043
Walter Dörwald41980ca2007-08-16 21:55:45 +00005044 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 Py_UCS4 ch;
5046 /* remaining bytes at the end? (size should be divisible by 4) */
5047 if (e-q<4) {
5048 if (consumed)
5049 break;
5050 errmsg = "truncated data";
5051 startinpos = ((const char *)q)-starts;
5052 endinpos = ((const char *)e)-starts;
5053 goto utf32Error;
5054 /* The remaining input chars are ignored if the callback
5055 chooses to skip the input */
5056 }
5057 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5058 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005059
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 if (ch >= 0x110000)
5061 {
5062 errmsg = "codepoint not in range(0x110000)";
5063 startinpos = ((const char *)q)-starts;
5064 endinpos = startinpos+4;
5065 goto utf32Error;
5066 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005067 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5068 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005069 q += 4;
5070 continue;
5071 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 if (unicode_decode_call_errorhandler(
5073 errors, &errorHandler,
5074 "utf32", errmsg,
5075 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005076 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005077 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005078 }
5079
5080 if (byteorder)
5081 *byteorder = bo;
5082
5083 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085
5086 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005087 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088 goto onError;
5089
5090 Py_XDECREF(errorHandler);
5091 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005092 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093
Benjamin Peterson29060642009-01-31 22:14:21 +00005094 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095 Py_DECREF(unicode);
5096 Py_XDECREF(errorHandler);
5097 Py_XDECREF(exc);
5098 return NULL;
5099}
5100
5101PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005102_PyUnicode_EncodeUTF32(PyObject *str,
5103 const char *errors,
5104 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005106 int kind;
5107 void *data;
5108 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005109 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005110 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005111 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112 /* Offsets from p for storing byte pairs in the right order. */
5113#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5114 int iorder[] = {0, 1, 2, 3};
5115#else
5116 int iorder[] = {3, 2, 1, 0};
5117#endif
5118
Benjamin Peterson29060642009-01-31 22:14:21 +00005119#define STORECHAR(CH) \
5120 do { \
5121 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5122 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5123 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5124 p[iorder[0]] = (CH) & 0xff; \
5125 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005126 } while(0)
5127
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005128 if (!PyUnicode_Check(str)) {
5129 PyErr_BadArgument();
5130 return NULL;
5131 }
5132 if (PyUnicode_READY(str) < 0)
5133 return NULL;
5134 kind = PyUnicode_KIND(str);
5135 data = PyUnicode_DATA(str);
5136 len = PyUnicode_GET_LENGTH(str);
5137
5138 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005139 bytesize = nsize * 4;
5140 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005141 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005142 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005143 if (v == NULL)
5144 return NULL;
5145
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005146 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005148 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005149 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005150 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005151
5152 if (byteorder == -1) {
5153 /* force LE */
5154 iorder[0] = 0;
5155 iorder[1] = 1;
5156 iorder[2] = 2;
5157 iorder[3] = 3;
5158 }
5159 else if (byteorder == 1) {
5160 /* force BE */
5161 iorder[0] = 3;
5162 iorder[1] = 2;
5163 iorder[2] = 1;
5164 iorder[3] = 0;
5165 }
5166
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005167 for (i = 0; i < len; i++)
5168 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005169
5170 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005171 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005172#undef STORECHAR
5173}
5174
Alexander Belopolsky40018472011-02-26 01:02:56 +00005175PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005176PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5177 Py_ssize_t size,
5178 const char *errors,
5179 int byteorder)
5180{
5181 PyObject *result;
5182 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5183 if (tmp == NULL)
5184 return NULL;
5185 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5186 Py_DECREF(tmp);
5187 return result;
5188}
5189
5190PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005191PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005192{
Victor Stinnerb960b342011-11-20 19:12:52 +01005193 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005194}
5195
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196/* --- UTF-16 Codec ------------------------------------------------------- */
5197
Tim Peters772747b2001-08-09 22:21:55 +00005198PyObject *
5199PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005200 Py_ssize_t size,
5201 const char *errors,
5202 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005203{
Walter Dörwald69652032004-09-07 20:24:22 +00005204 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5205}
5206
Antoine Pitrouab868312009-01-10 15:40:25 +00005207/* Two masks for fast checking of whether a C 'long' may contain
5208 UTF16-encoded surrogate characters. This is an efficient heuristic,
5209 assuming that non-surrogate characters with a code point >= 0x8000 are
5210 rare in most input.
5211 FAST_CHAR_MASK is used when the input is in native byte ordering,
5212 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005213*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005214#if (SIZEOF_LONG == 8)
5215# define FAST_CHAR_MASK 0x8000800080008000L
5216# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5217#elif (SIZEOF_LONG == 4)
5218# define FAST_CHAR_MASK 0x80008000L
5219# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5220#else
5221# error C 'long' size should be either 4 or 8!
5222#endif
5223
Walter Dörwald69652032004-09-07 20:24:22 +00005224PyObject *
5225PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005226 Py_ssize_t size,
5227 const char *errors,
5228 int *byteorder,
5229 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005230{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005231 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005232 Py_ssize_t startinpos;
5233 Py_ssize_t endinpos;
5234 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005235 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005236 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005237 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005238 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005239 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005240 /* Offsets from q for retrieving byte pairs in the right order. */
5241#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5242 int ihi = 1, ilo = 0;
5243#else
5244 int ihi = 0, ilo = 1;
5245#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005246 PyObject *errorHandler = NULL;
5247 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005248
5249 /* Note: size will always be longer than the resulting Unicode
5250 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005251 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005252 if (!unicode)
5253 return NULL;
5254 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005255 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005256 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005257
Tim Peters772747b2001-08-09 22:21:55 +00005258 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005259 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005260
5261 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005262 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005263
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005264 /* Check for BOM marks (U+FEFF) in the input and adjust current
5265 byte order setting accordingly. In native mode, the leading BOM
5266 mark is skipped, in all other modes, it is copied to the output
5267 stream as-is (giving a ZWNBSP character). */
5268 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005269 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005270 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005271#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005272 if (bom == 0xFEFF) {
5273 q += 2;
5274 bo = -1;
5275 }
5276 else if (bom == 0xFFFE) {
5277 q += 2;
5278 bo = 1;
5279 }
Tim Petersced69f82003-09-16 20:30:58 +00005280#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005281 if (bom == 0xFEFF) {
5282 q += 2;
5283 bo = 1;
5284 }
5285 else if (bom == 0xFFFE) {
5286 q += 2;
5287 bo = -1;
5288 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005289#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005290 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005291 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005292
Tim Peters772747b2001-08-09 22:21:55 +00005293 if (bo == -1) {
5294 /* force LE */
5295 ihi = 1;
5296 ilo = 0;
5297 }
5298 else if (bo == 1) {
5299 /* force BE */
5300 ihi = 0;
5301 ilo = 1;
5302 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005303#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5304 native_ordering = ilo < ihi;
5305#else
5306 native_ordering = ilo > ihi;
5307#endif
Tim Peters772747b2001-08-09 22:21:55 +00005308
Antoine Pitrouab868312009-01-10 15:40:25 +00005309 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005310 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005311 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005312 /* First check for possible aligned read of a C 'long'. Unaligned
5313 reads are more expensive, better to defer to another iteration. */
5314 if (!((size_t) q & LONG_PTR_MASK)) {
5315 /* Fast path for runs of non-surrogate chars. */
5316 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005317 int kind = PyUnicode_KIND(unicode);
5318 void *data = PyUnicode_DATA(unicode);
5319 while (_q < aligned_end) {
5320 unsigned long block = * (unsigned long *) _q;
5321 unsigned short *pblock = (unsigned short*)&block;
5322 Py_UCS4 maxch;
5323 if (native_ordering) {
5324 /* Can use buffer directly */
5325 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005326 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005327 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005328 else {
5329 /* Need to byte-swap */
5330 unsigned char *_p = (unsigned char*)pblock;
5331 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005332 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005333 _p[0] = _q[1];
5334 _p[1] = _q[0];
5335 _p[2] = _q[3];
5336 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005337#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005338 _p[4] = _q[5];
5339 _p[5] = _q[4];
5340 _p[6] = _q[7];
5341 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005342#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005343 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005344 maxch = Py_MAX(pblock[0], pblock[1]);
5345#if SIZEOF_LONG == 8
5346 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5347#endif
5348 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5349 if (unicode_widen(&unicode, maxch) < 0)
5350 goto onError;
5351 kind = PyUnicode_KIND(unicode);
5352 data = PyUnicode_DATA(unicode);
5353 }
5354 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5355 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5356#if SIZEOF_LONG == 8
5357 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5358 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5359#endif
5360 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005361 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005362 q = _q;
5363 if (q >= e)
5364 break;
5365 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005366 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005367
Benjamin Peterson14339b62009-01-31 16:36:08 +00005368 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005369
5370 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005371 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5372 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 continue;
5374 }
5375
5376 /* UTF-16 code pair: */
5377 if (q > e) {
5378 errmsg = "unexpected end of data";
5379 startinpos = (((const char *)q) - 2) - starts;
5380 endinpos = ((const char *)e) + 1 - starts;
5381 goto utf16Error;
5382 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005383 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5384 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005385 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005386 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005387 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005388 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005389 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005390 continue;
5391 }
5392 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005393 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005394 startinpos = (((const char *)q)-4)-starts;
5395 endinpos = startinpos+2;
5396 goto utf16Error;
5397 }
5398
Benjamin Peterson14339b62009-01-31 16:36:08 +00005399 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005400 errmsg = "illegal encoding";
5401 startinpos = (((const char *)q)-2)-starts;
5402 endinpos = startinpos+2;
5403 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005404
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005406 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005407 errors,
5408 &errorHandler,
5409 "utf16", errmsg,
5410 &starts,
5411 (const char **)&e,
5412 &startinpos,
5413 &endinpos,
5414 &exc,
5415 (const char **)&q,
5416 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005417 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005420 /* remaining byte at the end? (size should be even) */
5421 if (e == q) {
5422 if (!consumed) {
5423 errmsg = "truncated data";
5424 startinpos = ((const char *)q) - starts;
5425 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005426 if (unicode_decode_call_errorhandler(
5427 errors,
5428 &errorHandler,
5429 "utf16", errmsg,
5430 &starts,
5431 (const char **)&e,
5432 &startinpos,
5433 &endinpos,
5434 &exc,
5435 (const char **)&q,
5436 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005437 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005438 goto onError;
5439 /* The remaining input chars are ignored if the callback
5440 chooses to skip the input */
5441 }
5442 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005443
5444 if (byteorder)
5445 *byteorder = bo;
5446
Walter Dörwald69652032004-09-07 20:24:22 +00005447 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005448 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005449
Guido van Rossumd57fd912000-03-10 22:53:23 +00005450 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005451 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005452 goto onError;
5453
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005454 Py_XDECREF(errorHandler);
5455 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005456 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005457
Benjamin Peterson29060642009-01-31 22:14:21 +00005458 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005459 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005460 Py_XDECREF(errorHandler);
5461 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005462 return NULL;
5463}
5464
Antoine Pitrouab868312009-01-10 15:40:25 +00005465#undef FAST_CHAR_MASK
5466#undef SWAPPED_FAST_CHAR_MASK
5467
Tim Peters772747b2001-08-09 22:21:55 +00005468PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005469_PyUnicode_EncodeUTF16(PyObject *str,
5470 const char *errors,
5471 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005472{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005473 int kind;
5474 void *data;
5475 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005476 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005477 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005478 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005479 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005480 /* Offsets from p for storing byte pairs in the right order. */
5481#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5482 int ihi = 1, ilo = 0;
5483#else
5484 int ihi = 0, ilo = 1;
5485#endif
5486
Benjamin Peterson29060642009-01-31 22:14:21 +00005487#define STORECHAR(CH) \
5488 do { \
5489 p[ihi] = ((CH) >> 8) & 0xff; \
5490 p[ilo] = (CH) & 0xff; \
5491 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005492 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005494 if (!PyUnicode_Check(str)) {
5495 PyErr_BadArgument();
5496 return NULL;
5497 }
5498 if (PyUnicode_READY(str) < 0)
5499 return NULL;
5500 kind = PyUnicode_KIND(str);
5501 data = PyUnicode_DATA(str);
5502 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005503
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005504 pairs = 0;
5505 if (kind == PyUnicode_4BYTE_KIND)
5506 for (i = 0; i < len; i++)
5507 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5508 pairs++;
5509 /* 2 * (len + pairs + (byteorder == 0)) */
5510 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005511 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005512 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005513 bytesize = nsize * 2;
5514 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005515 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005516 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005517 if (v == NULL)
5518 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005519
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005520 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005521 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005522 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005523 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005524 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005525
5526 if (byteorder == -1) {
5527 /* force LE */
5528 ihi = 1;
5529 ilo = 0;
5530 }
5531 else if (byteorder == 1) {
5532 /* force BE */
5533 ihi = 0;
5534 ilo = 1;
5535 }
5536
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005537 for (i = 0; i < len; i++) {
5538 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5539 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 if (ch >= 0x10000) {
5541 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5542 ch = 0xD800 | ((ch-0x10000) >> 10);
5543 }
Tim Peters772747b2001-08-09 22:21:55 +00005544 STORECHAR(ch);
5545 if (ch2)
5546 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005547 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005548
5549 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005550 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005551#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552}
5553
Alexander Belopolsky40018472011-02-26 01:02:56 +00005554PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005555PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5556 Py_ssize_t size,
5557 const char *errors,
5558 int byteorder)
5559{
5560 PyObject *result;
5561 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5562 if (tmp == NULL)
5563 return NULL;
5564 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5565 Py_DECREF(tmp);
5566 return result;
5567}
5568
5569PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005570PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005572 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005573}
5574
5575/* --- Unicode Escape Codec ----------------------------------------------- */
5576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005577/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5578 if all the escapes in the string make it still a valid ASCII string.
5579 Returns -1 if any escapes were found which cause the string to
5580 pop out of ASCII range. Otherwise returns the length of the
5581 required buffer to hold the string.
5582 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005583static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005584length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5585{
5586 const unsigned char *p = (const unsigned char *)s;
5587 const unsigned char *end = p + size;
5588 Py_ssize_t length = 0;
5589
5590 if (size < 0)
5591 return -1;
5592
5593 for (; p < end; ++p) {
5594 if (*p > 127) {
5595 /* Non-ASCII */
5596 return -1;
5597 }
5598 else if (*p != '\\') {
5599 /* Normal character */
5600 ++length;
5601 }
5602 else {
5603 /* Backslash-escape, check next char */
5604 ++p;
5605 /* Escape sequence reaches till end of string or
5606 non-ASCII follow-up. */
5607 if (p >= end || *p > 127)
5608 return -1;
5609 switch (*p) {
5610 case '\n':
5611 /* backslash + \n result in zero characters */
5612 break;
5613 case '\\': case '\'': case '\"':
5614 case 'b': case 'f': case 't':
5615 case 'n': case 'r': case 'v': case 'a':
5616 ++length;
5617 break;
5618 case '0': case '1': case '2': case '3':
5619 case '4': case '5': case '6': case '7':
5620 case 'x': case 'u': case 'U': case 'N':
5621 /* these do not guarantee ASCII characters */
5622 return -1;
5623 default:
5624 /* count the backslash + the other character */
5625 length += 2;
5626 }
5627 }
5628 }
5629 return length;
5630}
5631
Fredrik Lundh06d12682001-01-24 07:59:11 +00005632static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005633
Alexander Belopolsky40018472011-02-26 01:02:56 +00005634PyObject *
5635PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005636 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005637 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005638{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005639 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005640 Py_ssize_t startinpos;
5641 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005643 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005645 char* message;
5646 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005647 PyObject *errorHandler = NULL;
5648 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005649 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005651
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005652 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005653
5654 /* After length_of_escaped_ascii_string() there are two alternatives,
5655 either the string is pure ASCII with named escapes like \n, etc.
5656 and we determined it's exact size (common case)
5657 or it contains \x, \u, ... escape sequences. then we create a
5658 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005659 if (len >= 0) {
5660 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005661 if (!v)
5662 goto onError;
5663 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005664 }
5665 else {
5666 /* Escaped strings will always be longer than the resulting
5667 Unicode string, so we start with size here and then reduce the
5668 length after conversion to the true value.
5669 (but if the error callback returns a long replacement string
5670 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005671 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005672 if (!v)
5673 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005674 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005675 }
5676
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005678 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005679 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005680 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005681
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682 while (s < end) {
5683 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005684 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005685 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005687 /* The only case in which i == ascii_length is a backslash
5688 followed by a newline. */
5689 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005690
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691 /* Non-escape characters are interpreted as Unicode ordinals */
5692 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005693 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5694 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695 continue;
5696 }
5697
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005698 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005699 /* \ - Escapes */
5700 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005701 c = *s++;
5702 if (s > end)
5703 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005705 /* The only case in which i == ascii_length is a backslash
5706 followed by a newline. */
5707 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005708
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005709 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005710
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005712#define WRITECHAR(ch) \
5713 do { \
5714 if (unicode_putchar(&v, &i, ch) < 0) \
5715 goto onError; \
5716 }while(0)
5717
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005719 case '\\': WRITECHAR('\\'); break;
5720 case '\'': WRITECHAR('\''); break;
5721 case '\"': WRITECHAR('\"'); break;
5722 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005723 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005724 case 'f': WRITECHAR('\014'); break;
5725 case 't': WRITECHAR('\t'); break;
5726 case 'n': WRITECHAR('\n'); break;
5727 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005728 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005729 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005730 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005731 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734 case '0': case '1': case '2': case '3':
5735 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005736 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005737 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005738 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005739 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005740 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005742 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005743 break;
5744
Benjamin Peterson29060642009-01-31 22:14:21 +00005745 /* hex escapes */
5746 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005748 digits = 2;
5749 message = "truncated \\xXX escape";
5750 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005754 digits = 4;
5755 message = "truncated \\uXXXX escape";
5756 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757
Benjamin Peterson29060642009-01-31 22:14:21 +00005758 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005759 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005760 digits = 8;
5761 message = "truncated \\UXXXXXXXX escape";
5762 hexescape:
5763 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005764 if (s+digits>end) {
5765 endinpos = size;
5766 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005767 errors, &errorHandler,
5768 "unicodeescape", "end of string in escape sequence",
5769 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005770 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005771 goto onError;
5772 goto nextByte;
5773 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005774 for (j = 0; j < digits; ++j) {
5775 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005776 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005777 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 errors, &errorHandler,
5780 "unicodeescape", message,
5781 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005782 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005783 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005784 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005785 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005786 }
5787 chr = (chr<<4) & ~0xF;
5788 if (c >= '0' && c <= '9')
5789 chr += c - '0';
5790 else if (c >= 'a' && c <= 'f')
5791 chr += 10 + c - 'a';
5792 else
5793 chr += 10 + c - 'A';
5794 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005795 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005796 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005797 /* _decoding_error will have already written into the
5798 target buffer. */
5799 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005800 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005801 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005802 if (chr <= 0x10ffff) {
5803 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005804 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005805 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005806 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005807 errors, &errorHandler,
5808 "unicodeescape", "illegal Unicode character",
5809 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005810 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005811 goto onError;
5812 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005813 break;
5814
Benjamin Peterson29060642009-01-31 22:14:21 +00005815 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005816 case 'N':
5817 message = "malformed \\N character escape";
5818 if (ucnhash_CAPI == NULL) {
5819 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005820 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5821 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822 if (ucnhash_CAPI == NULL)
5823 goto ucnhashError;
5824 }
5825 if (*s == '{') {
5826 const char *start = s+1;
5827 /* look for the closing brace */
5828 while (*s != '}' && s < end)
5829 s++;
5830 if (s > start && s < end && *s == '}') {
5831 /* found a name. look it up in the unicode database */
5832 message = "unknown Unicode character name";
5833 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005834 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005835 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005836 goto store;
5837 }
5838 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005839 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005840 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005841 errors, &errorHandler,
5842 "unicodeescape", message,
5843 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005844 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005845 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005846 break;
5847
5848 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005849 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005850 message = "\\ at end of string";
5851 s--;
5852 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005854 errors, &errorHandler,
5855 "unicodeescape", message,
5856 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005857 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005858 goto onError;
5859 }
5860 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005861 WRITECHAR('\\');
5862 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005863 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005864 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005867 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005869#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005870
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005871 if (PyUnicode_Resize(&v, i) < 0)
5872 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005873 Py_XDECREF(errorHandler);
5874 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005875 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005876
Benjamin Peterson29060642009-01-31 22:14:21 +00005877 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005878 PyErr_SetString(
5879 PyExc_UnicodeError,
5880 "\\N escapes not supported (can't load unicodedata module)"
5881 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005882 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005883 Py_XDECREF(errorHandler);
5884 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005885 return NULL;
5886
Benjamin Peterson29060642009-01-31 22:14:21 +00005887 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005889 Py_XDECREF(errorHandler);
5890 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 return NULL;
5892}
5893
5894/* Return a Unicode-Escape string version of the Unicode object.
5895
5896 If quotes is true, the string is enclosed in u"" or u'' quotes as
5897 appropriate.
5898
5899*/
5900
Alexander Belopolsky40018472011-02-26 01:02:56 +00005901PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005902PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005905 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005907 int kind;
5908 void *data;
5909 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910
Thomas Wouters89f507f2006-12-13 04:49:30 +00005911 /* Initial allocation is based on the longest-possible unichr
5912 escape.
5913
5914 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5915 unichr, so in this case it's the longest unichr escape. In
5916 narrow (UTF-16) builds this is five chars per source unichr
5917 since there are two unichrs in the surrogate pair, so in narrow
5918 (UTF-16) builds it's not the longest unichr escape.
5919
5920 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5921 so in the narrow (UTF-16) build case it's the longest unichr
5922 escape.
5923 */
5924
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005925 if (!PyUnicode_Check(unicode)) {
5926 PyErr_BadArgument();
5927 return NULL;
5928 }
5929 if (PyUnicode_READY(unicode) < 0)
5930 return NULL;
5931 len = PyUnicode_GET_LENGTH(unicode);
5932 kind = PyUnicode_KIND(unicode);
5933 data = PyUnicode_DATA(unicode);
5934 switch(kind) {
5935 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5936 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5937 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5938 }
5939
5940 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005941 return PyBytes_FromStringAndSize(NULL, 0);
5942
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005943 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005944 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005945
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005946 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005947 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005948 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950 if (repr == NULL)
5951 return NULL;
5952
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005953 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005955 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005956 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005957
Walter Dörwald79e913e2007-05-12 11:08:06 +00005958 /* Escape backslashes */
5959 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 *p++ = '\\';
5961 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005962 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005963 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005964
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005965 /* Map 21-bit characters to '\U00xxxxxx' */
5966 else if (ch >= 0x10000) {
5967 *p++ = '\\';
5968 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005969 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5970 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5971 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5972 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5973 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5974 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5975 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5976 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005978 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005979
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005981 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982 *p++ = '\\';
5983 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005984 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5985 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5986 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5987 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005989
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005990 /* Map special whitespace to '\t', \n', '\r' */
5991 else if (ch == '\t') {
5992 *p++ = '\\';
5993 *p++ = 't';
5994 }
5995 else if (ch == '\n') {
5996 *p++ = '\\';
5997 *p++ = 'n';
5998 }
5999 else if (ch == '\r') {
6000 *p++ = '\\';
6001 *p++ = 'r';
6002 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006003
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006004 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006005 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006007 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006008 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6009 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006010 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006011
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 /* Copy everything else as-is */
6013 else
6014 *p++ = (char) ch;
6015 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006017 assert(p - PyBytes_AS_STRING(repr) > 0);
6018 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6019 return NULL;
6020 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021}
6022
Alexander Belopolsky40018472011-02-26 01:02:56 +00006023PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006024PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6025 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006027 PyObject *result;
6028 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6029 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006031 result = PyUnicode_AsUnicodeEscapeString(tmp);
6032 Py_DECREF(tmp);
6033 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034}
6035
6036/* --- Raw Unicode Escape Codec ------------------------------------------- */
6037
Alexander Belopolsky40018472011-02-26 01:02:56 +00006038PyObject *
6039PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006040 Py_ssize_t size,
6041 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006043 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006044 Py_ssize_t startinpos;
6045 Py_ssize_t endinpos;
6046 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006047 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048 const char *end;
6049 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006050 PyObject *errorHandler = NULL;
6051 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006052
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053 /* Escaped strings will always be longer than the resulting
6054 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006055 length after conversion to the true value. (But decoding error
6056 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006057 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006061 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006062 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 end = s + size;
6064 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 unsigned char c;
6066 Py_UCS4 x;
6067 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006068 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 /* Non-escape characters are interpreted as Unicode ordinals */
6071 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006072 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6073 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006074 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006075 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 startinpos = s-starts;
6077
6078 /* \u-escapes are only interpreted iff the number of leading
6079 backslashes if odd */
6080 bs = s;
6081 for (;s < end;) {
6082 if (*s != '\\')
6083 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006084 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6085 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 }
6087 if (((s - bs) & 1) == 0 ||
6088 s >= end ||
6089 (*s != 'u' && *s != 'U')) {
6090 continue;
6091 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006092 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 count = *s=='u' ? 4 : 8;
6094 s++;
6095
6096 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006097 for (x = 0, i = 0; i < count; ++i, ++s) {
6098 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006099 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006100 endinpos = s-starts;
6101 if (unicode_decode_call_errorhandler(
6102 errors, &errorHandler,
6103 "rawunicodeescape", "truncated \\uXXXX",
6104 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006105 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006106 goto onError;
6107 goto nextByte;
6108 }
6109 x = (x<<4) & ~0xF;
6110 if (c >= '0' && c <= '9')
6111 x += c - '0';
6112 else if (c >= 'a' && c <= 'f')
6113 x += 10 + c - 'a';
6114 else
6115 x += 10 + c - 'A';
6116 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006117 if (x <= 0x10ffff) {
6118 if (unicode_putchar(&v, &outpos, x) < 0)
6119 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006120 } else {
6121 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006122 if (unicode_decode_call_errorhandler(
6123 errors, &errorHandler,
6124 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006125 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006126 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006128 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006129 nextByte:
6130 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006132 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006133 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006134 Py_XDECREF(errorHandler);
6135 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006136 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006137
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006140 Py_XDECREF(errorHandler);
6141 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 return NULL;
6143}
6144
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145
Alexander Belopolsky40018472011-02-26 01:02:56 +00006146PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006149 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 char *p;
6151 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 Py_ssize_t expandsize, pos;
6153 int kind;
6154 void *data;
6155 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 if (!PyUnicode_Check(unicode)) {
6158 PyErr_BadArgument();
6159 return NULL;
6160 }
6161 if (PyUnicode_READY(unicode) < 0)
6162 return NULL;
6163 kind = PyUnicode_KIND(unicode);
6164 data = PyUnicode_DATA(unicode);
6165 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006166
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 switch(kind) {
6168 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6169 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6170 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6171 }
Victor Stinner0e368262011-11-10 20:12:49 +01006172
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006173 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006174 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006175
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006176 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006177 if (repr == NULL)
6178 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006180 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006182 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006183 for (pos = 0; pos < len; pos++) {
6184 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 /* Map 32-bit characters to '\Uxxxxxxxx' */
6186 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006187 *p++ = '\\';
6188 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006189 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6190 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6191 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6192 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6193 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6194 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6195 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6196 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006197 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006198 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200 *p++ = '\\';
6201 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006202 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6203 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6204 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6205 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 /* Copy everything else as-is */
6208 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209 *p++ = (char) ch;
6210 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006211
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006212 assert(p > q);
6213 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006214 return NULL;
6215 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216}
6217
Alexander Belopolsky40018472011-02-26 01:02:56 +00006218PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6220 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006222 PyObject *result;
6223 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6224 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006225 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6227 Py_DECREF(tmp);
6228 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229}
6230
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006231/* --- Unicode Internal Codec ------------------------------------------- */
6232
Alexander Belopolsky40018472011-02-26 01:02:56 +00006233PyObject *
6234_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006235 Py_ssize_t size,
6236 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006237{
6238 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006239 Py_ssize_t startinpos;
6240 Py_ssize_t endinpos;
6241 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006242 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006243 const char *end;
6244 const char *reason;
6245 PyObject *errorHandler = NULL;
6246 PyObject *exc = NULL;
6247
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006248 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006249 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006250 1))
6251 return NULL;
6252
Thomas Wouters89f507f2006-12-13 04:49:30 +00006253 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006254 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006255 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006257 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006258 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006259 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006260 end = s + size;
6261
6262 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006263 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006264 Py_UCS4 ch;
6265 /* We copy the raw representation one byte at a time because the
6266 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006267 ((char *) &uch)[0] = s[0];
6268 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006269#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006270 ((char *) &uch)[2] = s[2];
6271 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006272#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006273 ch = uch;
6274
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006275 /* We have to sanity check the raw data, otherwise doom looms for
6276 some malformed UCS-4 data. */
6277 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006278#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006279 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006280#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006281 end-s < Py_UNICODE_SIZE
6282 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006284 startinpos = s - starts;
6285 if (end-s < Py_UNICODE_SIZE) {
6286 endinpos = end-starts;
6287 reason = "truncated input";
6288 }
6289 else {
6290 endinpos = s - starts + Py_UNICODE_SIZE;
6291 reason = "illegal code point (> 0x10FFFF)";
6292 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293 if (unicode_decode_call_errorhandler(
6294 errors, &errorHandler,
6295 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006296 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006297 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006298 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006299 continue;
6300 }
6301
6302 s += Py_UNICODE_SIZE;
6303#ifndef Py_UNICODE_WIDE
6304 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6305 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006306 Py_UNICODE uch2;
6307 ((char *) &uch2)[0] = s[0];
6308 ((char *) &uch2)[1] = s[1];
6309 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006310 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006311 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006313 }
6314 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006315#endif
6316
6317 if (unicode_putchar(&v, &outpos, ch) < 0)
6318 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006319 }
6320
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006321 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006322 goto onError;
6323 Py_XDECREF(errorHandler);
6324 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006325 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006326
Benjamin Peterson29060642009-01-31 22:14:21 +00006327 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328 Py_XDECREF(v);
6329 Py_XDECREF(errorHandler);
6330 Py_XDECREF(exc);
6331 return NULL;
6332}
6333
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334/* --- Latin-1 Codec ------------------------------------------------------ */
6335
Alexander Belopolsky40018472011-02-26 01:02:56 +00006336PyObject *
6337PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006338 Py_ssize_t size,
6339 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006340{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006341 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006342 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343}
6344
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006345/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006346static void
6347make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006348 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006349 PyObject *unicode,
6350 Py_ssize_t startpos, Py_ssize_t endpos,
6351 const char *reason)
6352{
6353 if (*exceptionObject == NULL) {
6354 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006355 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006356 encoding, unicode, startpos, endpos, reason);
6357 }
6358 else {
6359 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6360 goto onError;
6361 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6362 goto onError;
6363 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6364 goto onError;
6365 return;
6366 onError:
6367 Py_DECREF(*exceptionObject);
6368 *exceptionObject = NULL;
6369 }
6370}
6371
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006373static void
6374raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006375 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006376 PyObject *unicode,
6377 Py_ssize_t startpos, Py_ssize_t endpos,
6378 const char *reason)
6379{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006380 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006381 encoding, unicode, startpos, endpos, reason);
6382 if (*exceptionObject != NULL)
6383 PyCodec_StrictErrors(*exceptionObject);
6384}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006385
6386/* error handling callback helper:
6387 build arguments, call the callback and check the arguments,
6388 put the result into newpos and return the replacement string, which
6389 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006390static PyObject *
6391unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006392 PyObject **errorHandler,
6393 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006394 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006395 Py_ssize_t startpos, Py_ssize_t endpos,
6396 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006398 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006399 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006400 PyObject *restuple;
6401 PyObject *resunicode;
6402
6403 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006404 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407 }
6408
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006409 if (PyUnicode_READY(unicode) < 0)
6410 return NULL;
6411 len = PyUnicode_GET_LENGTH(unicode);
6412
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006413 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006414 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006415 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417
6418 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006423 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 Py_DECREF(restuple);
6425 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006427 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 &resunicode, newpos)) {
6429 Py_DECREF(restuple);
6430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006432 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6433 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6434 Py_DECREF(restuple);
6435 return NULL;
6436 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006437 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006438 *newpos = len + *newpos;
6439 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6441 Py_DECREF(restuple);
6442 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006443 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006444 Py_INCREF(resunicode);
6445 Py_DECREF(restuple);
6446 return resunicode;
6447}
6448
Alexander Belopolsky40018472011-02-26 01:02:56 +00006449static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006450unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006451 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006452 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006454 /* input state */
6455 Py_ssize_t pos=0, size;
6456 int kind;
6457 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006458 /* output object */
6459 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006460 /* pointer into the output */
6461 char *str;
6462 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006463 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006464 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6465 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006466 PyObject *errorHandler = NULL;
6467 PyObject *exc = NULL;
6468 /* the following variable is used for caching string comparisons
6469 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6470 int known_errorHandler = -1;
6471
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 if (PyUnicode_READY(unicode) < 0)
6473 return NULL;
6474 size = PyUnicode_GET_LENGTH(unicode);
6475 kind = PyUnicode_KIND(unicode);
6476 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006477 /* allocate enough for a simple encoding without
6478 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006479 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006480 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006481 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006482 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006483 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006484 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006485 ressize = size;
6486
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 while (pos < size) {
6488 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006489
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 /* can we encode this? */
6491 if (c<limit) {
6492 /* no overflow check, because we know that the space is enough */
6493 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006494 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006495 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006496 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 Py_ssize_t requiredsize;
6498 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006499 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 Py_ssize_t collstart = pos;
6502 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 ++collend;
6506 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6507 if (known_errorHandler==-1) {
6508 if ((errors==NULL) || (!strcmp(errors, "strict")))
6509 known_errorHandler = 1;
6510 else if (!strcmp(errors, "replace"))
6511 known_errorHandler = 2;
6512 else if (!strcmp(errors, "ignore"))
6513 known_errorHandler = 3;
6514 else if (!strcmp(errors, "xmlcharrefreplace"))
6515 known_errorHandler = 4;
6516 else
6517 known_errorHandler = 0;
6518 }
6519 switch (known_errorHandler) {
6520 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006521 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 goto onError;
6523 case 2: /* replace */
6524 while (collstart++<collend)
6525 *str++ = '?'; /* fall through */
6526 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006528 break;
6529 case 4: /* xmlcharrefreplace */
6530 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 /* determine replacement size */
6532 for (i = collstart, repsize = 0; i < collend; ++i) {
6533 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6534 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006538 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006540 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006541 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006542#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 else
6544 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006545#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 repsize += 2+6+1;
6550 else
6551 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006552#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006554 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 if (requiredsize > ressize) {
6556 if (requiredsize<2*ressize)
6557 requiredsize = 2*ressize;
6558 if (_PyBytes_Resize(&res, requiredsize))
6559 goto onError;
6560 str = PyBytes_AS_STRING(res) + respos;
6561 ressize = requiredsize;
6562 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006563 /* generate replacement */
6564 for (i = collstart; i < collend; ++i) {
6565 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006567 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006568 break;
6569 default:
6570 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 encoding, reason, unicode, &exc,
6572 collstart, collend, &newpos);
6573 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6574 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006576 if (PyBytes_Check(repunicode)) {
6577 /* Directly copy bytes result to output. */
6578 repsize = PyBytes_Size(repunicode);
6579 if (repsize > 1) {
6580 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006581 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006582 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6583 Py_DECREF(repunicode);
6584 goto onError;
6585 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006586 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006587 ressize += repsize-1;
6588 }
6589 memcpy(str, PyBytes_AsString(repunicode), repsize);
6590 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006591 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006592 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006593 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006594 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 /* need more space? (at least enough for what we
6596 have+the replacement+the rest of the string, so
6597 we won't have to check space for encodable characters) */
6598 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 repsize = PyUnicode_GET_LENGTH(repunicode);
6600 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 if (requiredsize > ressize) {
6602 if (requiredsize<2*ressize)
6603 requiredsize = 2*ressize;
6604 if (_PyBytes_Resize(&res, requiredsize)) {
6605 Py_DECREF(repunicode);
6606 goto onError;
6607 }
6608 str = PyBytes_AS_STRING(res) + respos;
6609 ressize = requiredsize;
6610 }
6611 /* check if there is anything unencodable in the replacement
6612 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613 for (i = 0; repsize-->0; ++i, ++str) {
6614 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006616 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 Py_DECREF(repunicode);
6619 goto onError;
6620 }
6621 *str = (char)c;
6622 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006623 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006624 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006625 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006626 }
6627 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006628 /* Resize if we allocated to much */
6629 size = str - PyBytes_AS_STRING(res);
6630 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006631 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006632 if (_PyBytes_Resize(&res, size) < 0)
6633 goto onError;
6634 }
6635
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 Py_XDECREF(errorHandler);
6637 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006638 return res;
6639
6640 onError:
6641 Py_XDECREF(res);
6642 Py_XDECREF(errorHandler);
6643 Py_XDECREF(exc);
6644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645}
6646
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006648PyObject *
6649PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006650 Py_ssize_t size,
6651 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006653 PyObject *result;
6654 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6655 if (unicode == NULL)
6656 return NULL;
6657 result = unicode_encode_ucs1(unicode, errors, 256);
6658 Py_DECREF(unicode);
6659 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006660}
6661
Alexander Belopolsky40018472011-02-26 01:02:56 +00006662PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006663_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664{
6665 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 PyErr_BadArgument();
6667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006669 if (PyUnicode_READY(unicode) == -1)
6670 return NULL;
6671 /* Fast path: if it is a one-byte string, construct
6672 bytes object directly. */
6673 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6674 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6675 PyUnicode_GET_LENGTH(unicode));
6676 /* Non-Latin-1 characters present. Defer to above function to
6677 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006678 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006679}
6680
6681PyObject*
6682PyUnicode_AsLatin1String(PyObject *unicode)
6683{
6684 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006685}
6686
6687/* --- 7-bit ASCII Codec -------------------------------------------------- */
6688
Alexander Belopolsky40018472011-02-26 01:02:56 +00006689PyObject *
6690PyUnicode_DecodeASCII(const char *s,
6691 Py_ssize_t size,
6692 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006693{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006694 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006695 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006696 int kind;
6697 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006698 Py_ssize_t startinpos;
6699 Py_ssize_t endinpos;
6700 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006702 int has_error;
6703 const unsigned char *p = (const unsigned char *)s;
6704 const unsigned char *end = p + size;
6705 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706 PyObject *errorHandler = NULL;
6707 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006708
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006709 if (size == 0) {
6710 Py_INCREF(unicode_empty);
6711 return unicode_empty;
6712 }
6713
Guido van Rossumd57fd912000-03-10 22:53:23 +00006714 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006715 if (size == 1 && (unsigned char)s[0] < 128)
6716 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006717
Victor Stinner702c7342011-10-05 13:50:52 +02006718 has_error = 0;
6719 while (p < end && !has_error) {
6720 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6721 an explanation. */
6722 if (!((size_t) p & LONG_PTR_MASK)) {
6723 /* Help register allocation */
6724 register const unsigned char *_p = p;
6725 while (_p < aligned_end) {
6726 unsigned long value = *(unsigned long *) _p;
6727 if (value & ASCII_CHAR_MASK) {
6728 has_error = 1;
6729 break;
6730 }
6731 _p += SIZEOF_LONG;
6732 }
6733 if (_p == end)
6734 break;
6735 if (has_error)
6736 break;
6737 p = _p;
6738 }
6739 if (*p & 0x80) {
6740 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006741 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006742 }
6743 else {
6744 ++p;
6745 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006746 }
Victor Stinner702c7342011-10-05 13:50:52 +02006747 if (!has_error)
6748 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006749
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006750 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006751 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006753 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006754 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006755 kind = PyUnicode_KIND(v);
6756 data = PyUnicode_DATA(v);
6757 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006758 e = s + size;
6759 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006760 register unsigned char c = (unsigned char)*s;
6761 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006762 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006763 ++s;
6764 }
6765 else {
6766 startinpos = s-starts;
6767 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 if (unicode_decode_call_errorhandler(
6769 errors, &errorHandler,
6770 "ascii", "ordinal not in range(128)",
6771 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006772 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006773 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006774 kind = PyUnicode_KIND(v);
6775 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006777 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006778 if (PyUnicode_Resize(&v, outpos) < 0)
6779 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006780 Py_XDECREF(errorHandler);
6781 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006782 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006783 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006784
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006786 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006787 Py_XDECREF(errorHandler);
6788 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006789 return NULL;
6790}
6791
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006792/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006793PyObject *
6794PyUnicode_EncodeASCII(const Py_UNICODE *p,
6795 Py_ssize_t size,
6796 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006797{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006798 PyObject *result;
6799 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6800 if (unicode == NULL)
6801 return NULL;
6802 result = unicode_encode_ucs1(unicode, errors, 128);
6803 Py_DECREF(unicode);
6804 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805}
6806
Alexander Belopolsky40018472011-02-26 01:02:56 +00006807PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006808_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006809{
6810 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006811 PyErr_BadArgument();
6812 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006814 if (PyUnicode_READY(unicode) == -1)
6815 return NULL;
6816 /* Fast path: if it is an ASCII-only string, construct bytes object
6817 directly. Else defer to above function to raise the exception. */
6818 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6819 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6820 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006821 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006822}
6823
6824PyObject *
6825PyUnicode_AsASCIIString(PyObject *unicode)
6826{
6827 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006828}
6829
Victor Stinner99b95382011-07-04 14:23:54 +02006830#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006831
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006832/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006833
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006834#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006835#define NEED_RETRY
6836#endif
6837
Victor Stinner3a50e702011-10-18 21:21:00 +02006838#ifndef WC_ERR_INVALID_CHARS
6839# define WC_ERR_INVALID_CHARS 0x0080
6840#endif
6841
6842static char*
6843code_page_name(UINT code_page, PyObject **obj)
6844{
6845 *obj = NULL;
6846 if (code_page == CP_ACP)
6847 return "mbcs";
6848 if (code_page == CP_UTF7)
6849 return "CP_UTF7";
6850 if (code_page == CP_UTF8)
6851 return "CP_UTF8";
6852
6853 *obj = PyBytes_FromFormat("cp%u", code_page);
6854 if (*obj == NULL)
6855 return NULL;
6856 return PyBytes_AS_STRING(*obj);
6857}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006858
Alexander Belopolsky40018472011-02-26 01:02:56 +00006859static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006860is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006861{
6862 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006863 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006864
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 if (!IsDBCSLeadByteEx(code_page, *curr))
6866 return 0;
6867
6868 prev = CharPrevExA(code_page, s, curr, 0);
6869 if (prev == curr)
6870 return 1;
6871 /* FIXME: This code is limited to "true" double-byte encodings,
6872 as it assumes an incomplete character consists of a single
6873 byte. */
6874 if (curr - prev == 2)
6875 return 1;
6876 if (!IsDBCSLeadByteEx(code_page, *prev))
6877 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006878 return 0;
6879}
6880
Victor Stinner3a50e702011-10-18 21:21:00 +02006881static DWORD
6882decode_code_page_flags(UINT code_page)
6883{
6884 if (code_page == CP_UTF7) {
6885 /* The CP_UTF7 decoder only supports flags=0 */
6886 return 0;
6887 }
6888 else
6889 return MB_ERR_INVALID_CHARS;
6890}
6891
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006892/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006893 * Decode a byte string from a Windows code page into unicode object in strict
6894 * mode.
6895 *
6896 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6897 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006898 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006899static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006900decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006901 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 const char *in,
6903 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904{
Victor Stinner3a50e702011-10-18 21:21:00 +02006905 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006906 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006907 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006908
6909 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006910 assert(insize > 0);
6911 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6912 if (outsize <= 0)
6913 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006914
6915 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006917 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006918 if (*v == NULL)
6919 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921 }
6922 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006923 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006924 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006925 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006926 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006927 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006928 }
6929
6930 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006931 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6932 if (outsize <= 0)
6933 goto error;
6934 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006935
Victor Stinner3a50e702011-10-18 21:21:00 +02006936error:
6937 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6938 return -2;
6939 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006940 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006941}
6942
Victor Stinner3a50e702011-10-18 21:21:00 +02006943/*
6944 * Decode a byte string from a code page into unicode object with an error
6945 * handler.
6946 *
6947 * Returns consumed size if succeed, or raise a WindowsError or
6948 * UnicodeDecodeError exception and returns -1 on error.
6949 */
6950static int
6951decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006952 PyObject **v,
6953 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006954 const char *errors)
6955{
6956 const char *startin = in;
6957 const char *endin = in + size;
6958 const DWORD flags = decode_code_page_flags(code_page);
6959 /* Ideally, we should get reason from FormatMessage. This is the Windows
6960 2000 English version of the message. */
6961 const char *reason = "No mapping for the Unicode character exists "
6962 "in the target code page.";
6963 /* each step cannot decode more than 1 character, but a character can be
6964 represented as a surrogate pair */
6965 wchar_t buffer[2], *startout, *out;
6966 int insize, outsize;
6967 PyObject *errorHandler = NULL;
6968 PyObject *exc = NULL;
6969 PyObject *encoding_obj = NULL;
6970 char *encoding;
6971 DWORD err;
6972 int ret = -1;
6973
6974 assert(size > 0);
6975
6976 encoding = code_page_name(code_page, &encoding_obj);
6977 if (encoding == NULL)
6978 return -1;
6979
6980 if (errors == NULL || strcmp(errors, "strict") == 0) {
6981 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6982 UnicodeDecodeError. */
6983 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6984 if (exc != NULL) {
6985 PyCodec_StrictErrors(exc);
6986 Py_CLEAR(exc);
6987 }
6988 goto error;
6989 }
6990
6991 if (*v == NULL) {
6992 /* Create unicode object */
6993 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6994 PyErr_NoMemory();
6995 goto error;
6996 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006997 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006998 if (*v == NULL)
6999 goto error;
7000 startout = PyUnicode_AS_UNICODE(*v);
7001 }
7002 else {
7003 /* Extend unicode object */
7004 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7005 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7006 PyErr_NoMemory();
7007 goto error;
7008 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007009 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007010 goto error;
7011 startout = PyUnicode_AS_UNICODE(*v) + n;
7012 }
7013
7014 /* Decode the byte string character per character */
7015 out = startout;
7016 while (in < endin)
7017 {
7018 /* Decode a character */
7019 insize = 1;
7020 do
7021 {
7022 outsize = MultiByteToWideChar(code_page, flags,
7023 in, insize,
7024 buffer, Py_ARRAY_LENGTH(buffer));
7025 if (outsize > 0)
7026 break;
7027 err = GetLastError();
7028 if (err != ERROR_NO_UNICODE_TRANSLATION
7029 && err != ERROR_INSUFFICIENT_BUFFER)
7030 {
7031 PyErr_SetFromWindowsErr(0);
7032 goto error;
7033 }
7034 insize++;
7035 }
7036 /* 4=maximum length of a UTF-8 sequence */
7037 while (insize <= 4 && (in + insize) <= endin);
7038
7039 if (outsize <= 0) {
7040 Py_ssize_t startinpos, endinpos, outpos;
7041
7042 startinpos = in - startin;
7043 endinpos = startinpos + 1;
7044 outpos = out - PyUnicode_AS_UNICODE(*v);
7045 if (unicode_decode_call_errorhandler(
7046 errors, &errorHandler,
7047 encoding, reason,
7048 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007049 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007050 {
7051 goto error;
7052 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007053 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007054 }
7055 else {
7056 in += insize;
7057 memcpy(out, buffer, outsize * sizeof(wchar_t));
7058 out += outsize;
7059 }
7060 }
7061
7062 /* write a NUL character at the end */
7063 *out = 0;
7064
7065 /* Extend unicode object */
7066 outsize = out - startout;
7067 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007068 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007070 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007071
7072error:
7073 Py_XDECREF(encoding_obj);
7074 Py_XDECREF(errorHandler);
7075 Py_XDECREF(exc);
7076 return ret;
7077}
7078
Victor Stinner3a50e702011-10-18 21:21:00 +02007079static PyObject *
7080decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007081 const char *s, Py_ssize_t size,
7082 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007083{
Victor Stinner76a31a62011-11-04 00:05:13 +01007084 PyObject *v = NULL;
7085 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
Victor Stinner3a50e702011-10-18 21:21:00 +02007087 if (code_page < 0) {
7088 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7089 return NULL;
7090 }
7091
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007093 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007094
Victor Stinner76a31a62011-11-04 00:05:13 +01007095 do
7096 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007098 if (size > INT_MAX) {
7099 chunk_size = INT_MAX;
7100 final = 0;
7101 done = 0;
7102 }
7103 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007105 {
7106 chunk_size = (int)size;
7107 final = (consumed == NULL);
7108 done = 1;
7109 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110
Victor Stinner76a31a62011-11-04 00:05:13 +01007111 /* Skip trailing lead-byte unless 'final' is set */
7112 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7113 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114
Victor Stinner76a31a62011-11-04 00:05:13 +01007115 if (chunk_size == 0 && done) {
7116 if (v != NULL)
7117 break;
7118 Py_INCREF(unicode_empty);
7119 return unicode_empty;
7120 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007121
Victor Stinner76a31a62011-11-04 00:05:13 +01007122
7123 converted = decode_code_page_strict(code_page, &v,
7124 s, chunk_size);
7125 if (converted == -2)
7126 converted = decode_code_page_errors(code_page, &v,
7127 s, chunk_size,
7128 errors);
7129 assert(converted != 0);
7130
7131 if (converted < 0) {
7132 Py_XDECREF(v);
7133 return NULL;
7134 }
7135
7136 if (consumed)
7137 *consumed += converted;
7138
7139 s += converted;
7140 size -= converted;
7141 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007142
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007143 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007144}
7145
Alexander Belopolsky40018472011-02-26 01:02:56 +00007146PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007147PyUnicode_DecodeCodePageStateful(int code_page,
7148 const char *s,
7149 Py_ssize_t size,
7150 const char *errors,
7151 Py_ssize_t *consumed)
7152{
7153 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7154}
7155
7156PyObject *
7157PyUnicode_DecodeMBCSStateful(const char *s,
7158 Py_ssize_t size,
7159 const char *errors,
7160 Py_ssize_t *consumed)
7161{
7162 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7163}
7164
7165PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007166PyUnicode_DecodeMBCS(const char *s,
7167 Py_ssize_t size,
7168 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007169{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7171}
7172
Victor Stinner3a50e702011-10-18 21:21:00 +02007173static DWORD
7174encode_code_page_flags(UINT code_page, const char *errors)
7175{
7176 if (code_page == CP_UTF8) {
7177 if (winver.dwMajorVersion >= 6)
7178 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7179 and later */
7180 return WC_ERR_INVALID_CHARS;
7181 else
7182 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7183 return 0;
7184 }
7185 else if (code_page == CP_UTF7) {
7186 /* CP_UTF7 only supports flags=0 */
7187 return 0;
7188 }
7189 else {
7190 if (errors != NULL && strcmp(errors, "replace") == 0)
7191 return 0;
7192 else
7193 return WC_NO_BEST_FIT_CHARS;
7194 }
7195}
7196
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 * Encode a Unicode string to a Windows code page into a byte string in strict
7199 * mode.
7200 *
7201 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7202 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007203 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007204static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007205encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007206 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007208{
Victor Stinner554f3f02010-06-16 23:33:54 +00007209 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 BOOL *pusedDefaultChar = &usedDefaultChar;
7211 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007212 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007213 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 const DWORD flags = encode_code_page_flags(code_page, NULL);
7216 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 /* Create a substring so that we can get the UTF-16 representation
7218 of just the slice under consideration. */
7219 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007220
Martin v. Löwis3d325192011-11-04 18:23:06 +01007221 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007222
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007224 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007226 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007227
Victor Stinner2fc507f2011-11-04 20:06:39 +01007228 substring = PyUnicode_Substring(unicode, offset, offset+len);
7229 if (substring == NULL)
7230 return -1;
7231 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7232 if (p == NULL) {
7233 Py_DECREF(substring);
7234 return -1;
7235 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007236
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007237 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 outsize = WideCharToMultiByte(code_page, flags,
7239 p, size,
7240 NULL, 0,
7241 NULL, pusedDefaultChar);
7242 if (outsize <= 0)
7243 goto error;
7244 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007245 if (pusedDefaultChar && *pusedDefaultChar) {
7246 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007249
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007251 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 if (*outbytes == NULL) {
7254 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007255 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007256 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007257 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007258 }
7259 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007260 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 const Py_ssize_t n = PyBytes_Size(*outbytes);
7262 if (outsize > PY_SSIZE_T_MAX - n) {
7263 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007264 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007265 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007267 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7268 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007270 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007272 }
7273
7274 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 outsize = WideCharToMultiByte(code_page, flags,
7276 p, size,
7277 out, outsize,
7278 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007279 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007280 if (outsize <= 0)
7281 goto error;
7282 if (pusedDefaultChar && *pusedDefaultChar)
7283 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007284 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007285
Victor Stinner3a50e702011-10-18 21:21:00 +02007286error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007287 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007288 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7289 return -2;
7290 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007291 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007292}
7293
Victor Stinner3a50e702011-10-18 21:21:00 +02007294/*
7295 * Encode a Unicode string to a Windows code page into a byte string using a
7296 * error handler.
7297 *
7298 * Returns consumed characters if succeed, or raise a WindowsError and returns
7299 * -1 on other error.
7300 */
7301static int
7302encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007303 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007304 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007305{
Victor Stinner3a50e702011-10-18 21:21:00 +02007306 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007307 Py_ssize_t pos = unicode_offset;
7308 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 /* Ideally, we should get reason from FormatMessage. This is the Windows
7310 2000 English version of the message. */
7311 const char *reason = "invalid character";
7312 /* 4=maximum length of a UTF-8 sequence */
7313 char buffer[4];
7314 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7315 Py_ssize_t outsize;
7316 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 PyObject *errorHandler = NULL;
7318 PyObject *exc = NULL;
7319 PyObject *encoding_obj = NULL;
7320 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007321 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007322 PyObject *rep;
7323 int ret = -1;
7324
7325 assert(insize > 0);
7326
7327 encoding = code_page_name(code_page, &encoding_obj);
7328 if (encoding == NULL)
7329 return -1;
7330
7331 if (errors == NULL || strcmp(errors, "strict") == 0) {
7332 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7333 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007334 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007335 if (exc != NULL) {
7336 PyCodec_StrictErrors(exc);
7337 Py_DECREF(exc);
7338 }
7339 Py_XDECREF(encoding_obj);
7340 return -1;
7341 }
7342
7343 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7344 pusedDefaultChar = &usedDefaultChar;
7345 else
7346 pusedDefaultChar = NULL;
7347
7348 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7349 PyErr_NoMemory();
7350 goto error;
7351 }
7352 outsize = insize * Py_ARRAY_LENGTH(buffer);
7353
7354 if (*outbytes == NULL) {
7355 /* Create string object */
7356 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7357 if (*outbytes == NULL)
7358 goto error;
7359 out = PyBytes_AS_STRING(*outbytes);
7360 }
7361 else {
7362 /* Extend string object */
7363 Py_ssize_t n = PyBytes_Size(*outbytes);
7364 if (n > PY_SSIZE_T_MAX - outsize) {
7365 PyErr_NoMemory();
7366 goto error;
7367 }
7368 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7369 goto error;
7370 out = PyBytes_AS_STRING(*outbytes) + n;
7371 }
7372
7373 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007374 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007376 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7377 wchar_t chars[2];
7378 int charsize;
7379 if (ch < 0x10000) {
7380 chars[0] = (wchar_t)ch;
7381 charsize = 1;
7382 }
7383 else {
7384 ch -= 0x10000;
7385 chars[0] = 0xd800 + (ch >> 10);
7386 chars[1] = 0xdc00 + (ch & 0x3ff);
7387 charsize = 2;
7388 }
7389
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007391 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 buffer, Py_ARRAY_LENGTH(buffer),
7393 NULL, pusedDefaultChar);
7394 if (outsize > 0) {
7395 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7396 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007397 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 memcpy(out, buffer, outsize);
7399 out += outsize;
7400 continue;
7401 }
7402 }
7403 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7404 PyErr_SetFromWindowsErr(0);
7405 goto error;
7406 }
7407
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 rep = unicode_encode_call_errorhandler(
7409 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007410 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007411 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007412 if (rep == NULL)
7413 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007414 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007415
7416 if (PyBytes_Check(rep)) {
7417 outsize = PyBytes_GET_SIZE(rep);
7418 if (outsize != 1) {
7419 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7420 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7421 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7422 Py_DECREF(rep);
7423 goto error;
7424 }
7425 out = PyBytes_AS_STRING(*outbytes) + offset;
7426 }
7427 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7428 out += outsize;
7429 }
7430 else {
7431 Py_ssize_t i;
7432 enum PyUnicode_Kind kind;
7433 void *data;
7434
7435 if (PyUnicode_READY(rep) < 0) {
7436 Py_DECREF(rep);
7437 goto error;
7438 }
7439
7440 outsize = PyUnicode_GET_LENGTH(rep);
7441 if (outsize != 1) {
7442 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7443 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7444 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7445 Py_DECREF(rep);
7446 goto error;
7447 }
7448 out = PyBytes_AS_STRING(*outbytes) + offset;
7449 }
7450 kind = PyUnicode_KIND(rep);
7451 data = PyUnicode_DATA(rep);
7452 for (i=0; i < outsize; i++) {
7453 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7454 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007455 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007456 encoding, unicode,
7457 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 "unable to encode error handler result to ASCII");
7459 Py_DECREF(rep);
7460 goto error;
7461 }
7462 *out = (unsigned char)ch;
7463 out++;
7464 }
7465 }
7466 Py_DECREF(rep);
7467 }
7468 /* write a NUL byte */
7469 *out = 0;
7470 outsize = out - PyBytes_AS_STRING(*outbytes);
7471 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7472 if (_PyBytes_Resize(outbytes, outsize) < 0)
7473 goto error;
7474 ret = 0;
7475
7476error:
7477 Py_XDECREF(encoding_obj);
7478 Py_XDECREF(errorHandler);
7479 Py_XDECREF(exc);
7480 return ret;
7481}
7482
Victor Stinner3a50e702011-10-18 21:21:00 +02007483static PyObject *
7484encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007485 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 const char *errors)
7487{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007488 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007490 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007491 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007492
Victor Stinner2fc507f2011-11-04 20:06:39 +01007493 if (PyUnicode_READY(unicode) < 0)
7494 return NULL;
7495 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007496
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 if (code_page < 0) {
7498 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7499 return NULL;
7500 }
7501
Martin v. Löwis3d325192011-11-04 18:23:06 +01007502 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007503 return PyBytes_FromStringAndSize(NULL, 0);
7504
Victor Stinner7581cef2011-11-03 22:32:33 +01007505 offset = 0;
7506 do
7507 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007508#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007509 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007510 chunks. */
7511 if (len > INT_MAX/2) {
7512 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007513 done = 0;
7514 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007515 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007516#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007517 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007518 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007519 done = 1;
7520 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007521
Victor Stinner76a31a62011-11-04 00:05:13 +01007522 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007523 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007524 errors);
7525 if (ret == -2)
7526 ret = encode_code_page_errors(code_page, &outbytes,
7527 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007528 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007529 if (ret < 0) {
7530 Py_XDECREF(outbytes);
7531 return NULL;
7532 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007533
Victor Stinner7581cef2011-11-03 22:32:33 +01007534 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007535 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007536 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007537
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 return outbytes;
7539}
7540
7541PyObject *
7542PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7543 Py_ssize_t size,
7544 const char *errors)
7545{
Victor Stinner7581cef2011-11-03 22:32:33 +01007546 PyObject *unicode, *res;
7547 unicode = PyUnicode_FromUnicode(p, size);
7548 if (unicode == NULL)
7549 return NULL;
7550 res = encode_code_page(CP_ACP, unicode, errors);
7551 Py_DECREF(unicode);
7552 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007553}
7554
7555PyObject *
7556PyUnicode_EncodeCodePage(int code_page,
7557 PyObject *unicode,
7558 const char *errors)
7559{
Victor Stinner7581cef2011-11-03 22:32:33 +01007560 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007561}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007562
Alexander Belopolsky40018472011-02-26 01:02:56 +00007563PyObject *
7564PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007565{
7566 if (!PyUnicode_Check(unicode)) {
7567 PyErr_BadArgument();
7568 return NULL;
7569 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007570 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007571}
7572
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007573#undef NEED_RETRY
7574
Victor Stinner99b95382011-07-04 14:23:54 +02007575#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007576
Guido van Rossumd57fd912000-03-10 22:53:23 +00007577/* --- Character Mapping Codec -------------------------------------------- */
7578
Alexander Belopolsky40018472011-02-26 01:02:56 +00007579PyObject *
7580PyUnicode_DecodeCharmap(const char *s,
7581 Py_ssize_t size,
7582 PyObject *mapping,
7583 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007584{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007585 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007586 Py_ssize_t startinpos;
7587 Py_ssize_t endinpos;
7588 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007589 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007590 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007591 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007592 PyObject *errorHandler = NULL;
7593 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007594
Guido van Rossumd57fd912000-03-10 22:53:23 +00007595 /* Default to Latin-1 */
7596 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007597 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007598
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007599 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007600 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007601 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007602 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007603 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007604 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007605 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007606 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007607 Py_ssize_t maplen;
7608 enum PyUnicode_Kind kind;
7609 void *data;
7610 Py_UCS4 x;
7611
7612 if (PyUnicode_READY(mapping) < 0)
7613 return NULL;
7614
7615 maplen = PyUnicode_GET_LENGTH(mapping);
7616 data = PyUnicode_DATA(mapping);
7617 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007618 while (s < e) {
7619 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007620
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007622 x = PyUnicode_READ(kind, data, ch);
7623 else
7624 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007625
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007626 if (x == 0xfffe)
7627 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007628 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007629 startinpos = s-starts;
7630 endinpos = startinpos+1;
7631 if (unicode_decode_call_errorhandler(
7632 errors, &errorHandler,
7633 "charmap", "character maps to <undefined>",
7634 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007635 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 goto onError;
7637 }
7638 continue;
7639 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007640
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007641 if (unicode_putchar(&v, &outpos, x) < 0)
7642 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007643 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007644 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007645 }
7646 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 while (s < e) {
7648 unsigned char ch = *s;
7649 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007650
Benjamin Peterson29060642009-01-31 22:14:21 +00007651 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7652 w = PyLong_FromLong((long)ch);
7653 if (w == NULL)
7654 goto onError;
7655 x = PyObject_GetItem(mapping, w);
7656 Py_DECREF(w);
7657 if (x == NULL) {
7658 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7659 /* No mapping found means: mapping is undefined. */
7660 PyErr_Clear();
7661 x = Py_None;
7662 Py_INCREF(x);
7663 } else
7664 goto onError;
7665 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007666
Benjamin Peterson29060642009-01-31 22:14:21 +00007667 /* Apply mapping */
7668 if (PyLong_Check(x)) {
7669 long value = PyLong_AS_LONG(x);
7670 if (value < 0 || value > 65535) {
7671 PyErr_SetString(PyExc_TypeError,
7672 "character mapping must be in range(65536)");
7673 Py_DECREF(x);
7674 goto onError;
7675 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007676 if (unicode_putchar(&v, &outpos, value) < 0)
7677 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007678 }
7679 else if (x == Py_None) {
7680 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007681 startinpos = s-starts;
7682 endinpos = startinpos+1;
7683 if (unicode_decode_call_errorhandler(
7684 errors, &errorHandler,
7685 "charmap", "character maps to <undefined>",
7686 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007687 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007688 Py_DECREF(x);
7689 goto onError;
7690 }
7691 Py_DECREF(x);
7692 continue;
7693 }
7694 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007695 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007696
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007697 if (PyUnicode_READY(x) < 0)
7698 goto onError;
7699 targetsize = PyUnicode_GET_LENGTH(x);
7700
7701 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007702 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007703 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007704 PyUnicode_READ_CHAR(x, 0)) < 0)
7705 goto onError;
7706 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 else if (targetsize > 1) {
7708 /* 1-n mapping */
7709 if (targetsize > extrachars) {
7710 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007711 Py_ssize_t needed = (targetsize - extrachars) + \
7712 (targetsize << 2);
7713 extrachars += needed;
7714 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007715 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007716 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007717 Py_DECREF(x);
7718 goto onError;
7719 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007721 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7722 goto onError;
7723 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7724 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007725 extrachars -= targetsize;
7726 }
7727 /* 1-0 mapping: skip the character */
7728 }
7729 else {
7730 /* wrong return value */
7731 PyErr_SetString(PyExc_TypeError,
7732 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007733 Py_DECREF(x);
7734 goto onError;
7735 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 Py_DECREF(x);
7737 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007738 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007739 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007740 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007741 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007742 Py_XDECREF(errorHandler);
7743 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007744 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007745
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007747 Py_XDECREF(errorHandler);
7748 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007749 Py_XDECREF(v);
7750 return NULL;
7751}
7752
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007753/* Charmap encoding: the lookup table */
7754
Alexander Belopolsky40018472011-02-26 01:02:56 +00007755struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007756 PyObject_HEAD
7757 unsigned char level1[32];
7758 int count2, count3;
7759 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007760};
7761
7762static PyObject*
7763encoding_map_size(PyObject *obj, PyObject* args)
7764{
7765 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007766 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007767 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768}
7769
7770static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007771 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007772 PyDoc_STR("Return the size (in bytes) of this object") },
7773 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007774};
7775
7776static void
7777encoding_map_dealloc(PyObject* o)
7778{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007779 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780}
7781
7782static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007783 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007784 "EncodingMap", /*tp_name*/
7785 sizeof(struct encoding_map), /*tp_basicsize*/
7786 0, /*tp_itemsize*/
7787 /* methods */
7788 encoding_map_dealloc, /*tp_dealloc*/
7789 0, /*tp_print*/
7790 0, /*tp_getattr*/
7791 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007792 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007793 0, /*tp_repr*/
7794 0, /*tp_as_number*/
7795 0, /*tp_as_sequence*/
7796 0, /*tp_as_mapping*/
7797 0, /*tp_hash*/
7798 0, /*tp_call*/
7799 0, /*tp_str*/
7800 0, /*tp_getattro*/
7801 0, /*tp_setattro*/
7802 0, /*tp_as_buffer*/
7803 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7804 0, /*tp_doc*/
7805 0, /*tp_traverse*/
7806 0, /*tp_clear*/
7807 0, /*tp_richcompare*/
7808 0, /*tp_weaklistoffset*/
7809 0, /*tp_iter*/
7810 0, /*tp_iternext*/
7811 encoding_map_methods, /*tp_methods*/
7812 0, /*tp_members*/
7813 0, /*tp_getset*/
7814 0, /*tp_base*/
7815 0, /*tp_dict*/
7816 0, /*tp_descr_get*/
7817 0, /*tp_descr_set*/
7818 0, /*tp_dictoffset*/
7819 0, /*tp_init*/
7820 0, /*tp_alloc*/
7821 0, /*tp_new*/
7822 0, /*tp_free*/
7823 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007824};
7825
7826PyObject*
7827PyUnicode_BuildEncodingMap(PyObject* string)
7828{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829 PyObject *result;
7830 struct encoding_map *mresult;
7831 int i;
7832 int need_dict = 0;
7833 unsigned char level1[32];
7834 unsigned char level2[512];
7835 unsigned char *mlevel1, *mlevel2, *mlevel3;
7836 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007837 int kind;
7838 void *data;
7839 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007841 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007842 PyErr_BadArgument();
7843 return NULL;
7844 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007845 kind = PyUnicode_KIND(string);
7846 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007847 memset(level1, 0xFF, sizeof level1);
7848 memset(level2, 0xFF, sizeof level2);
7849
7850 /* If there isn't a one-to-one mapping of NULL to \0,
7851 or if there are non-BMP characters, we need to use
7852 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007853 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854 need_dict = 1;
7855 for (i = 1; i < 256; i++) {
7856 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007857 ch = PyUnicode_READ(kind, data, i);
7858 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007859 need_dict = 1;
7860 break;
7861 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007862 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007863 /* unmapped character */
7864 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007865 l1 = ch >> 11;
7866 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007867 if (level1[l1] == 0xFF)
7868 level1[l1] = count2++;
7869 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007870 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871 }
7872
7873 if (count2 >= 0xFF || count3 >= 0xFF)
7874 need_dict = 1;
7875
7876 if (need_dict) {
7877 PyObject *result = PyDict_New();
7878 PyObject *key, *value;
7879 if (!result)
7880 return NULL;
7881 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007882 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007883 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884 if (!key || !value)
7885 goto failed1;
7886 if (PyDict_SetItem(result, key, value) == -1)
7887 goto failed1;
7888 Py_DECREF(key);
7889 Py_DECREF(value);
7890 }
7891 return result;
7892 failed1:
7893 Py_XDECREF(key);
7894 Py_XDECREF(value);
7895 Py_DECREF(result);
7896 return NULL;
7897 }
7898
7899 /* Create a three-level trie */
7900 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7901 16*count2 + 128*count3 - 1);
7902 if (!result)
7903 return PyErr_NoMemory();
7904 PyObject_Init(result, &EncodingMapType);
7905 mresult = (struct encoding_map*)result;
7906 mresult->count2 = count2;
7907 mresult->count3 = count3;
7908 mlevel1 = mresult->level1;
7909 mlevel2 = mresult->level23;
7910 mlevel3 = mresult->level23 + 16*count2;
7911 memcpy(mlevel1, level1, 32);
7912 memset(mlevel2, 0xFF, 16*count2);
7913 memset(mlevel3, 0, 128*count3);
7914 count3 = 0;
7915 for (i = 1; i < 256; i++) {
7916 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007917 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918 /* unmapped character */
7919 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007920 o1 = PyUnicode_READ(kind, data, i)>>11;
7921 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007922 i2 = 16*mlevel1[o1] + o2;
7923 if (mlevel2[i2] == 0xFF)
7924 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007925 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007926 i3 = 128*mlevel2[i2] + o3;
7927 mlevel3[i3] = i;
7928 }
7929 return result;
7930}
7931
7932static int
Victor Stinner22168992011-11-20 17:09:18 +01007933encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934{
7935 struct encoding_map *map = (struct encoding_map*)mapping;
7936 int l1 = c>>11;
7937 int l2 = (c>>7) & 0xF;
7938 int l3 = c & 0x7F;
7939 int i;
7940
Victor Stinner22168992011-11-20 17:09:18 +01007941 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007943 if (c == 0)
7944 return 0;
7945 /* level 1*/
7946 i = map->level1[l1];
7947 if (i == 0xFF) {
7948 return -1;
7949 }
7950 /* level 2*/
7951 i = map->level23[16*i+l2];
7952 if (i == 0xFF) {
7953 return -1;
7954 }
7955 /* level 3 */
7956 i = map->level23[16*map->count2 + 128*i + l3];
7957 if (i == 0) {
7958 return -1;
7959 }
7960 return i;
7961}
7962
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007963/* Lookup the character ch in the mapping. If the character
7964 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007965 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007966static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007967charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007968{
Christian Heimes217cfd12007-12-02 14:31:20 +00007969 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007970 PyObject *x;
7971
7972 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007973 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007974 x = PyObject_GetItem(mapping, w);
7975 Py_DECREF(w);
7976 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7978 /* No mapping found means: mapping is undefined. */
7979 PyErr_Clear();
7980 x = Py_None;
7981 Py_INCREF(x);
7982 return x;
7983 } else
7984 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007986 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007988 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 long value = PyLong_AS_LONG(x);
7990 if (value < 0 || value > 255) {
7991 PyErr_SetString(PyExc_TypeError,
7992 "character mapping must be in range(256)");
7993 Py_DECREF(x);
7994 return NULL;
7995 }
7996 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007998 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008000 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008001 /* wrong return value */
8002 PyErr_Format(PyExc_TypeError,
8003 "character mapping must return integer, bytes or None, not %.400s",
8004 x->ob_type->tp_name);
8005 Py_DECREF(x);
8006 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007 }
8008}
8009
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008011charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008013 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8014 /* exponentially overallocate to minimize reallocations */
8015 if (requiredsize < 2*outsize)
8016 requiredsize = 2*outsize;
8017 if (_PyBytes_Resize(outobj, requiredsize))
8018 return -1;
8019 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020}
8021
Benjamin Peterson14339b62009-01-31 16:36:08 +00008022typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008024} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008025/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008026 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008027 space is available. Return a new reference to the object that
8028 was put in the output buffer, or Py_None, if the mapping was undefined
8029 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008030 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008031static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008032charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008033 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008034{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035 PyObject *rep;
8036 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008037 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008038
Christian Heimes90aa7642007-12-19 02:45:37 +00008039 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042 if (res == -1)
8043 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 if (outsize<requiredsize)
8045 if (charmapencode_resize(outobj, outpos, requiredsize))
8046 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008047 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008048 outstart[(*outpos)++] = (char)res;
8049 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 }
8051
8052 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 Py_DECREF(rep);
8057 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008058 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 if (PyLong_Check(rep)) {
8060 Py_ssize_t requiredsize = *outpos+1;
8061 if (outsize<requiredsize)
8062 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8063 Py_DECREF(rep);
8064 return enc_EXCEPTION;
8065 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008066 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008068 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 else {
8070 const char *repchars = PyBytes_AS_STRING(rep);
8071 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8072 Py_ssize_t requiredsize = *outpos+repsize;
8073 if (outsize<requiredsize)
8074 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8075 Py_DECREF(rep);
8076 return enc_EXCEPTION;
8077 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008078 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008079 memcpy(outstart + *outpos, repchars, repsize);
8080 *outpos += repsize;
8081 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008082 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083 Py_DECREF(rep);
8084 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085}
8086
8087/* handle an error in PyUnicode_EncodeCharmap
8088 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008089static int
8090charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008091 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008093 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008094 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095{
8096 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008097 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008098 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008099 enum PyUnicode_Kind kind;
8100 void *data;
8101 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008102 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008103 Py_ssize_t collstartpos = *inpos;
8104 Py_ssize_t collendpos = *inpos+1;
8105 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008106 char *encoding = "charmap";
8107 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008109 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008110 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008111
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112 if (PyUnicode_READY(unicode) < 0)
8113 return -1;
8114 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008115 /* find all unencodable characters */
8116 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008117 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008118 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008120 val = encoding_map_lookup(ch, mapping);
8121 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 break;
8123 ++collendpos;
8124 continue;
8125 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008126
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008127 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8128 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008129 if (rep==NULL)
8130 return -1;
8131 else if (rep!=Py_None) {
8132 Py_DECREF(rep);
8133 break;
8134 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008135 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008137 }
8138 /* cache callback name lookup
8139 * (if not done yet, i.e. it's the first error) */
8140 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008141 if ((errors==NULL) || (!strcmp(errors, "strict")))
8142 *known_errorHandler = 1;
8143 else if (!strcmp(errors, "replace"))
8144 *known_errorHandler = 2;
8145 else if (!strcmp(errors, "ignore"))
8146 *known_errorHandler = 3;
8147 else if (!strcmp(errors, "xmlcharrefreplace"))
8148 *known_errorHandler = 4;
8149 else
8150 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008151 }
8152 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008153 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008154 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008155 return -1;
8156 case 2: /* replace */
8157 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008158 x = charmapencode_output('?', mapping, res, respos);
8159 if (x==enc_EXCEPTION) {
8160 return -1;
8161 }
8162 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008163 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 return -1;
8165 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008166 }
8167 /* fall through */
8168 case 3: /* ignore */
8169 *inpos = collendpos;
8170 break;
8171 case 4: /* xmlcharrefreplace */
8172 /* generate replacement (temporarily (mis)uses p) */
8173 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 char buffer[2+29+1+1];
8175 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008176 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 for (cp = buffer; *cp; ++cp) {
8178 x = charmapencode_output(*cp, mapping, res, respos);
8179 if (x==enc_EXCEPTION)
8180 return -1;
8181 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008182 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 return -1;
8184 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008185 }
8186 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008187 *inpos = collendpos;
8188 break;
8189 default:
8190 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008191 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008193 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008194 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008195 if (PyBytes_Check(repunicode)) {
8196 /* Directly copy bytes result to output. */
8197 Py_ssize_t outsize = PyBytes_Size(*res);
8198 Py_ssize_t requiredsize;
8199 repsize = PyBytes_Size(repunicode);
8200 requiredsize = *respos + repsize;
8201 if (requiredsize > outsize)
8202 /* Make room for all additional bytes. */
8203 if (charmapencode_resize(res, respos, requiredsize)) {
8204 Py_DECREF(repunicode);
8205 return -1;
8206 }
8207 memcpy(PyBytes_AsString(*res) + *respos,
8208 PyBytes_AsString(repunicode), repsize);
8209 *respos += repsize;
8210 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008211 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008212 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008213 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008214 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008215 if (PyUnicode_READY(repunicode) < 0) {
8216 Py_DECREF(repunicode);
8217 return -1;
8218 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008219 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008220 data = PyUnicode_DATA(repunicode);
8221 kind = PyUnicode_KIND(repunicode);
8222 for (index = 0; index < repsize; index++) {
8223 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8224 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008226 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008227 return -1;
8228 }
8229 else if (x==enc_FAILED) {
8230 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008231 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 return -1;
8233 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008234 }
8235 *inpos = newpos;
8236 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 }
8238 return 0;
8239}
8240
Alexander Belopolsky40018472011-02-26 01:02:56 +00008241PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008242_PyUnicode_EncodeCharmap(PyObject *unicode,
8243 PyObject *mapping,
8244 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008245{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 /* output object */
8247 PyObject *res = NULL;
8248 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008249 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008251 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008252 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253 PyObject *errorHandler = NULL;
8254 PyObject *exc = NULL;
8255 /* the following variable is used for caching string comparisons
8256 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8257 * 3=ignore, 4=xmlcharrefreplace */
8258 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008259
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008260 if (PyUnicode_READY(unicode) < 0)
8261 return NULL;
8262 size = PyUnicode_GET_LENGTH(unicode);
8263
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264 /* Default to Latin-1 */
8265 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008266 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 /* allocate enough for a simple encoding without
8269 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008270 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 if (res == NULL)
8272 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008273 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008275
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008277 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 if (x==enc_EXCEPTION) /* error */
8281 goto onError;
8282 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008283 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 &exc,
8285 &known_errorHandler, &errorHandler, errors,
8286 &res, &respos)) {
8287 goto onError;
8288 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008289 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008290 else
8291 /* done with this character => adjust input position */
8292 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008293 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008296 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008297 if (_PyBytes_Resize(&res, respos) < 0)
8298 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008299
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300 Py_XDECREF(exc);
8301 Py_XDECREF(errorHandler);
8302 return res;
8303
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008305 Py_XDECREF(res);
8306 Py_XDECREF(exc);
8307 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008308 return NULL;
8309}
8310
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008311/* Deprecated */
8312PyObject *
8313PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8314 Py_ssize_t size,
8315 PyObject *mapping,
8316 const char *errors)
8317{
8318 PyObject *result;
8319 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8320 if (unicode == NULL)
8321 return NULL;
8322 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8323 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008324 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008325}
8326
Alexander Belopolsky40018472011-02-26 01:02:56 +00008327PyObject *
8328PyUnicode_AsCharmapString(PyObject *unicode,
8329 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330{
8331 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 PyErr_BadArgument();
8333 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008335 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008336}
8337
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008339static void
8340make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008341 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008342 Py_ssize_t startpos, Py_ssize_t endpos,
8343 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008346 *exceptionObject = _PyUnicodeTranslateError_Create(
8347 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348 }
8349 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8351 goto onError;
8352 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8353 goto onError;
8354 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8355 goto onError;
8356 return;
8357 onError:
8358 Py_DECREF(*exceptionObject);
8359 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008360 }
8361}
8362
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008364static void
8365raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008366 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008367 Py_ssize_t startpos, Py_ssize_t endpos,
8368 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369{
8370 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008371 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374}
8375
8376/* error handling callback helper:
8377 build arguments, call the callback and check the arguments,
8378 put the result into newpos and return the replacement string, which
8379 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008380static PyObject *
8381unicode_translate_call_errorhandler(const char *errors,
8382 PyObject **errorHandler,
8383 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008384 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008385 Py_ssize_t startpos, Py_ssize_t endpos,
8386 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008387{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008388 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008390 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 PyObject *restuple;
8392 PyObject *resunicode;
8393
8394 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008396 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 }
8399
8400 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008401 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404
8405 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008410 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 Py_DECREF(restuple);
8412 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008413 }
8414 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 &resunicode, &i_newpos)) {
8416 Py_DECREF(restuple);
8417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008419 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008420 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008421 else
8422 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008423 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8425 Py_DECREF(restuple);
8426 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008427 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 Py_INCREF(resunicode);
8429 Py_DECREF(restuple);
8430 return resunicode;
8431}
8432
8433/* Lookup the character ch in the mapping and put the result in result,
8434 which must be decrefed by the caller.
8435 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008436static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008437charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438{
Christian Heimes217cfd12007-12-02 14:31:20 +00008439 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 PyObject *x;
8441
8442 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 x = PyObject_GetItem(mapping, w);
8445 Py_DECREF(w);
8446 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8448 /* No mapping found means: use 1:1 mapping. */
8449 PyErr_Clear();
8450 *result = NULL;
8451 return 0;
8452 } else
8453 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454 }
8455 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 *result = x;
8457 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008458 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008459 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 long value = PyLong_AS_LONG(x);
8461 long max = PyUnicode_GetMax();
8462 if (value < 0 || value > max) {
8463 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008464 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 Py_DECREF(x);
8466 return -1;
8467 }
8468 *result = x;
8469 return 0;
8470 }
8471 else if (PyUnicode_Check(x)) {
8472 *result = x;
8473 return 0;
8474 }
8475 else {
8476 /* wrong return value */
8477 PyErr_SetString(PyExc_TypeError,
8478 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008479 Py_DECREF(x);
8480 return -1;
8481 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482}
8483/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 if not reallocate and adjust various state variables.
8485 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008486static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008487charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008491 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 /* exponentially overallocate to minimize reallocations */
8493 if (requiredsize < 2 * oldsize)
8494 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8496 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 }
8500 return 0;
8501}
8502/* lookup the character, put the result in the output string and adjust
8503 various state variables. Return a new reference to the object that
8504 was put in the output buffer in *result, or Py_None, if the mapping was
8505 undefined (in which case no character was written).
8506 The called must decref result.
8507 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008508static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8510 PyObject *mapping, Py_UCS4 **output,
8511 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8515 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 }
8521 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008523 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 }
8527 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 Py_ssize_t repsize;
8529 if (PyUnicode_READY(*res) == -1)
8530 return -1;
8531 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 if (repsize==1) {
8533 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 }
8536 else if (repsize!=0) {
8537 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 Py_ssize_t requiredsize = *opos +
8539 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 Py_ssize_t i;
8542 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 for(i = 0; i < repsize; i++)
8545 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008547 }
8548 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550 return 0;
8551}
8552
Alexander Belopolsky40018472011-02-26 01:02:56 +00008553PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554_PyUnicode_TranslateCharmap(PyObject *input,
8555 PyObject *mapping,
8556 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008557{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008558 /* input object */
8559 char *idata;
8560 Py_ssize_t size, i;
8561 int kind;
8562 /* output buffer */
8563 Py_UCS4 *output = NULL;
8564 Py_ssize_t osize;
8565 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 char *reason = "character maps to <undefined>";
8569 PyObject *errorHandler = NULL;
8570 PyObject *exc = NULL;
8571 /* the following variable is used for caching string comparisons
8572 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8573 * 3=ignore, 4=xmlcharrefreplace */
8574 int known_errorHandler = -1;
8575
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 PyErr_BadArgument();
8578 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 if (PyUnicode_READY(input) == -1)
8582 return NULL;
8583 idata = (char*)PyUnicode_DATA(input);
8584 kind = PyUnicode_KIND(input);
8585 size = PyUnicode_GET_LENGTH(input);
8586 i = 0;
8587
8588 if (size == 0) {
8589 Py_INCREF(input);
8590 return input;
8591 }
8592
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 /* allocate enough for a simple 1:1 translation without
8594 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 osize = size;
8596 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8597 opos = 0;
8598 if (output == NULL) {
8599 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 /* try to encode it */
8605 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 if (charmaptranslate_output(input, i, mapping,
8607 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 Py_XDECREF(x);
8609 goto onError;
8610 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008611 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 else { /* untranslatable character */
8615 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8616 Py_ssize_t repsize;
8617 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 Py_ssize_t collstart = i;
8621 Py_ssize_t collend = i+1;
8622 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008623
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 while (collend < size) {
8626 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 goto onError;
8628 Py_XDECREF(x);
8629 if (x!=Py_None)
8630 break;
8631 ++collend;
8632 }
8633 /* cache callback name lookup
8634 * (if not done yet, i.e. it's the first error) */
8635 if (known_errorHandler==-1) {
8636 if ((errors==NULL) || (!strcmp(errors, "strict")))
8637 known_errorHandler = 1;
8638 else if (!strcmp(errors, "replace"))
8639 known_errorHandler = 2;
8640 else if (!strcmp(errors, "ignore"))
8641 known_errorHandler = 3;
8642 else if (!strcmp(errors, "xmlcharrefreplace"))
8643 known_errorHandler = 4;
8644 else
8645 known_errorHandler = 0;
8646 }
8647 switch (known_errorHandler) {
8648 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649 raise_translate_exception(&exc, input, collstart,
8650 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008651 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 case 2: /* replace */
8653 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 for (coll = collstart; coll<collend; coll++)
8655 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 /* fall through */
8657 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008659 break;
8660 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661 /* generate replacement (temporarily (mis)uses i) */
8662 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 char buffer[2+29+1+1];
8664 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8666 if (charmaptranslate_makespace(&output, &osize,
8667 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 goto onError;
8669 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 break;
8674 default:
8675 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008676 reason, input, &exc,
8677 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008678 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008680 if (PyUnicode_READY(repunicode) < 0) {
8681 Py_DECREF(repunicode);
8682 goto onError;
8683 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008685 repsize = PyUnicode_GET_LENGTH(repunicode);
8686 if (charmaptranslate_makespace(&output, &osize,
8687 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 Py_DECREF(repunicode);
8689 goto onError;
8690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 for (uni2 = 0; repsize-->0; ++uni2)
8692 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8693 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008695 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008696 }
8697 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8699 if (!res)
8700 goto onError;
8701 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008702 Py_XDECREF(exc);
8703 Py_XDECREF(errorHandler);
8704 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008707 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008708 Py_XDECREF(exc);
8709 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008710 return NULL;
8711}
8712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008713/* Deprecated. Use PyUnicode_Translate instead. */
8714PyObject *
8715PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8716 Py_ssize_t size,
8717 PyObject *mapping,
8718 const char *errors)
8719{
8720 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8721 if (!unicode)
8722 return NULL;
8723 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8724}
8725
Alexander Belopolsky40018472011-02-26 01:02:56 +00008726PyObject *
8727PyUnicode_Translate(PyObject *str,
8728 PyObject *mapping,
8729 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008730{
8731 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008732
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733 str = PyUnicode_FromObject(str);
8734 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008736 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008737 Py_DECREF(str);
8738 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008739
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741 Py_XDECREF(str);
8742 return NULL;
8743}
Tim Petersced69f82003-09-16 20:30:58 +00008744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008746fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747{
8748 /* No need to call PyUnicode_READY(self) because this function is only
8749 called as a callback from fixup() which does it already. */
8750 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8751 const int kind = PyUnicode_KIND(self);
8752 void *data = PyUnicode_DATA(self);
8753 Py_UCS4 maxchar = 0, ch, fixed;
8754 Py_ssize_t i;
8755
8756 for (i = 0; i < len; ++i) {
8757 ch = PyUnicode_READ(kind, data, i);
8758 fixed = 0;
8759 if (ch > 127) {
8760 if (Py_UNICODE_ISSPACE(ch))
8761 fixed = ' ';
8762 else {
8763 const int decimal = Py_UNICODE_TODECIMAL(ch);
8764 if (decimal >= 0)
8765 fixed = '0' + decimal;
8766 }
8767 if (fixed != 0) {
8768 if (fixed > maxchar)
8769 maxchar = fixed;
8770 PyUnicode_WRITE(kind, data, i, fixed);
8771 }
8772 else if (ch > maxchar)
8773 maxchar = ch;
8774 }
8775 else if (ch > maxchar)
8776 maxchar = ch;
8777 }
8778
8779 return maxchar;
8780}
8781
8782PyObject *
8783_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8784{
8785 if (!PyUnicode_Check(unicode)) {
8786 PyErr_BadInternalCall();
8787 return NULL;
8788 }
8789 if (PyUnicode_READY(unicode) == -1)
8790 return NULL;
8791 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8792 /* If the string is already ASCII, just return the same string */
8793 Py_INCREF(unicode);
8794 return unicode;
8795 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008796 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008797}
8798
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008799PyObject *
8800PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8801 Py_ssize_t length)
8802{
Victor Stinnerf0124502011-11-21 23:12:56 +01008803 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008804 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008805 Py_UCS4 maxchar;
8806 enum PyUnicode_Kind kind;
8807 void *data;
8808
8809 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008810 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008811 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008812 if (ch > 127) {
8813 int decimal = Py_UNICODE_TODECIMAL(ch);
8814 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008815 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008816 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008817 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008818 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008819
8820 /* Copy to a new string */
8821 decimal = PyUnicode_New(length, maxchar);
8822 if (decimal == NULL)
8823 return decimal;
8824 kind = PyUnicode_KIND(decimal);
8825 data = PyUnicode_DATA(decimal);
8826 /* Iterate over code points */
8827 for (i = 0; i < length; i++) {
8828 Py_UNICODE ch = s[i];
8829 if (ch > 127) {
8830 int decimal = Py_UNICODE_TODECIMAL(ch);
8831 if (decimal >= 0)
8832 ch = '0' + decimal;
8833 }
8834 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008836 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008837}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008838/* --- Decimal Encoder ---------------------------------------------------- */
8839
Alexander Belopolsky40018472011-02-26 01:02:56 +00008840int
8841PyUnicode_EncodeDecimal(Py_UNICODE *s,
8842 Py_ssize_t length,
8843 char *output,
8844 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008845{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008846 PyObject *errorHandler = NULL;
8847 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008848 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008849 const char *encoding = "decimal";
8850 const char *reason = "invalid decimal Unicode string";
8851 /* the following variable is used for caching string comparisons
8852 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8853 int known_errorHandler = -1;
Victor Stinner42bf7752011-11-21 22:52:58 +01008854 Py_ssize_t i, j;
8855 enum PyUnicode_Kind kind;
8856 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008857
8858 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008859 PyErr_BadArgument();
8860 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008861 }
8862
Victor Stinner42bf7752011-11-21 22:52:58 +01008863 unicode = PyUnicode_FromUnicode(s, length);
8864 if (unicode == NULL)
8865 return -1;
8866
8867 if (PyUnicode_READY(unicode) < 0)
8868 goto onError;
8869 kind = PyUnicode_KIND(unicode);
8870 data = PyUnicode_DATA(unicode);
8871
8872 for (i=0; i < length; i++) {
8873 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008874 int decimal;
Victor Stinner42bf7752011-11-21 22:52:58 +01008875 Py_ssize_t startpos, endpos;
Tim Petersced69f82003-09-16 20:30:58 +00008876
Benjamin Peterson29060642009-01-31 22:14:21 +00008877 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008878 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008879 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008880 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008881 decimal = Py_UNICODE_TODECIMAL(ch);
8882 if (decimal >= 0) {
8883 *output++ = '0' + decimal;
Benjamin Peterson29060642009-01-31 22:14:21 +00008884 continue;
8885 }
8886 if (0 < ch && ch < 256) {
8887 *output++ = (char)ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008888 continue;
8889 }
8890 /* All other characters are considered unencodable */
Victor Stinner42bf7752011-11-21 22:52:58 +01008891 startpos = i;
8892 endpos = i+1;
8893 for (; endpos < length; endpos++) {
8894 ch = PyUnicode_READ(kind, data, endpos);
8895 if ((0 < ch && ch < 256) ||
8896 !Py_UNICODE_ISSPACE(ch) ||
8897 Py_UNICODE_TODECIMAL(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00008898 break;
8899 }
8900 /* cache callback name lookup
8901 * (if not done yet, i.e. it's the first error) */
8902 if (known_errorHandler==-1) {
8903 if ((errors==NULL) || (!strcmp(errors, "strict")))
8904 known_errorHandler = 1;
8905 else if (!strcmp(errors, "replace"))
8906 known_errorHandler = 2;
8907 else if (!strcmp(errors, "ignore"))
8908 known_errorHandler = 3;
8909 else if (!strcmp(errors, "xmlcharrefreplace"))
8910 known_errorHandler = 4;
8911 else
8912 known_errorHandler = 0;
8913 }
8914 switch (known_errorHandler) {
8915 case 1: /* strict */
Victor Stinner42bf7752011-11-21 22:52:58 +01008916 raise_encode_exception(&exc, encoding, unicode, startpos, endpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 goto onError;
8918 case 2: /* replace */
Victor Stinner42bf7752011-11-21 22:52:58 +01008919 for (j=startpos; j < endpos; j++)
Benjamin Peterson29060642009-01-31 22:14:21 +00008920 *output++ = '?';
8921 /* fall through */
8922 case 3: /* ignore */
Victor Stinner42bf7752011-11-21 22:52:58 +01008923 i = endpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 break;
8925 case 4: /* xmlcharrefreplace */
Victor Stinner42bf7752011-11-21 22:52:58 +01008926 /* generate replacement */
8927 for (j=startpos; j < endpos; j++) {
8928 ch = PyUnicode_READ(kind, data, i);
8929 output += sprintf(output, "&#%d;", (int)ch);
8930 i++;
8931 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 break;
8933 default:
Victor Stinner42bf7752011-11-21 22:52:58 +01008934 {
8935 PyObject *repunicode;
8936 Py_ssize_t repsize, newpos, k;
8937 enum PyUnicode_Kind repkind;
8938 void *repdata;
8939
Benjamin Peterson29060642009-01-31 22:14:21 +00008940 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008941 encoding, reason, unicode, &exc,
Victor Stinner42bf7752011-11-21 22:52:58 +01008942 startpos, endpos, &newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008943 if (repunicode == NULL)
8944 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008945 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008946 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008947 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8948 Py_DECREF(repunicode);
8949 goto onError;
8950 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008951 if (PyUnicode_READY(repunicode) < 0) {
8952 Py_DECREF(repunicode);
8953 goto onError;
8954 }
8955 repkind = PyUnicode_KIND(repunicode);
8956 repdata = PyUnicode_DATA(repunicode);
8957
Benjamin Peterson29060642009-01-31 22:14:21 +00008958 /* generate replacement */
8959 repsize = PyUnicode_GET_SIZE(repunicode);
Victor Stinner42bf7752011-11-21 22:52:58 +01008960 for (k=0; k<repsize; k++) {
8961 ch = PyUnicode_READ(repkind, repdata, k);
Benjamin Peterson29060642009-01-31 22:14:21 +00008962 if (Py_UNICODE_ISSPACE(ch))
8963 *output++ = ' ';
8964 else {
8965 decimal = Py_UNICODE_TODECIMAL(ch);
8966 if (decimal >= 0)
8967 *output++ = '0' + decimal;
8968 else if (0 < ch && ch < 256)
8969 *output++ = (char)ch;
8970 else {
8971 Py_DECREF(repunicode);
8972 raise_encode_exception(&exc, encoding,
Victor Stinner42bf7752011-11-21 22:52:58 +01008973 unicode, startpos, endpos,
8974 reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 goto onError;
8976 }
8977 }
8978 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008979 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008980 Py_DECREF(repunicode);
8981 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008982 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008983 }
8984 /* 0-terminate the output string */
8985 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008986 Py_XDECREF(exc);
8987 Py_XDECREF(errorHandler);
Victor Stinner42bf7752011-11-21 22:52:58 +01008988 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008989 return 0;
8990
Benjamin Peterson29060642009-01-31 22:14:21 +00008991 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008992 Py_XDECREF(exc);
8993 Py_XDECREF(errorHandler);
Victor Stinner42bf7752011-11-21 22:52:58 +01008994 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008995 return -1;
8996}
8997
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998/* --- Helpers ------------------------------------------------------------ */
8999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009001any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002 Py_ssize_t start,
9003 Py_ssize_t end)
9004{
9005 int kind1, kind2, kind;
9006 void *buf1, *buf2;
9007 Py_ssize_t len1, len2, result;
9008
9009 kind1 = PyUnicode_KIND(s1);
9010 kind2 = PyUnicode_KIND(s2);
9011 kind = kind1 > kind2 ? kind1 : kind2;
9012 buf1 = PyUnicode_DATA(s1);
9013 buf2 = PyUnicode_DATA(s2);
9014 if (kind1 != kind)
9015 buf1 = _PyUnicode_AsKind(s1, kind);
9016 if (!buf1)
9017 return -2;
9018 if (kind2 != kind)
9019 buf2 = _PyUnicode_AsKind(s2, kind);
9020 if (!buf2) {
9021 if (kind1 != kind) PyMem_Free(buf1);
9022 return -2;
9023 }
9024 len1 = PyUnicode_GET_LENGTH(s1);
9025 len2 = PyUnicode_GET_LENGTH(s2);
9026
Victor Stinner794d5672011-10-10 03:21:36 +02009027 if (direction > 0) {
9028 switch(kind) {
9029 case PyUnicode_1BYTE_KIND:
9030 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9031 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9032 else
9033 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9034 break;
9035 case PyUnicode_2BYTE_KIND:
9036 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9037 break;
9038 case PyUnicode_4BYTE_KIND:
9039 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9040 break;
9041 default:
9042 assert(0); result = -2;
9043 }
9044 }
9045 else {
9046 switch(kind) {
9047 case PyUnicode_1BYTE_KIND:
9048 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9049 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9050 else
9051 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9052 break;
9053 case PyUnicode_2BYTE_KIND:
9054 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9055 break;
9056 case PyUnicode_4BYTE_KIND:
9057 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9058 break;
9059 default:
9060 assert(0); result = -2;
9061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062 }
9063
9064 if (kind1 != kind)
9065 PyMem_Free(buf1);
9066 if (kind2 != kind)
9067 PyMem_Free(buf2);
9068
9069 return result;
9070}
9071
9072Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009073_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 Py_ssize_t n_buffer,
9075 void *digits, Py_ssize_t n_digits,
9076 Py_ssize_t min_width,
9077 const char *grouping,
9078 const char *thousands_sep)
9079{
9080 switch(kind) {
9081 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009082 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9083 return _PyUnicode_ascii_InsertThousandsGrouping(
9084 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9085 min_width, grouping, thousands_sep);
9086 else
9087 return _PyUnicode_ucs1_InsertThousandsGrouping(
9088 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9089 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090 case PyUnicode_2BYTE_KIND:
9091 return _PyUnicode_ucs2_InsertThousandsGrouping(
9092 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9093 min_width, grouping, thousands_sep);
9094 case PyUnicode_4BYTE_KIND:
9095 return _PyUnicode_ucs4_InsertThousandsGrouping(
9096 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9097 min_width, grouping, thousands_sep);
9098 }
9099 assert(0);
9100 return -1;
9101}
9102
9103
Thomas Wouters477c8d52006-05-27 19:21:47 +00009104/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009105#define ADJUST_INDICES(start, end, len) \
9106 if (end > len) \
9107 end = len; \
9108 else if (end < 0) { \
9109 end += len; \
9110 if (end < 0) \
9111 end = 0; \
9112 } \
9113 if (start < 0) { \
9114 start += len; \
9115 if (start < 0) \
9116 start = 0; \
9117 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009118
Alexander Belopolsky40018472011-02-26 01:02:56 +00009119Py_ssize_t
9120PyUnicode_Count(PyObject *str,
9121 PyObject *substr,
9122 Py_ssize_t start,
9123 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009124{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009125 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009126 PyObject* str_obj;
9127 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128 int kind1, kind2, kind;
9129 void *buf1 = NULL, *buf2 = NULL;
9130 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009131
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009132 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009134 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009135 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009136 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009137 Py_DECREF(str_obj);
9138 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 }
Tim Petersced69f82003-09-16 20:30:58 +00009140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 kind1 = PyUnicode_KIND(str_obj);
9142 kind2 = PyUnicode_KIND(sub_obj);
9143 kind = kind1 > kind2 ? kind1 : kind2;
9144 buf1 = PyUnicode_DATA(str_obj);
9145 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009146 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009147 if (!buf1)
9148 goto onError;
9149 buf2 = PyUnicode_DATA(sub_obj);
9150 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009151 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 if (!buf2)
9153 goto onError;
9154 len1 = PyUnicode_GET_LENGTH(str_obj);
9155 len2 = PyUnicode_GET_LENGTH(sub_obj);
9156
9157 ADJUST_INDICES(start, end, len1);
9158 switch(kind) {
9159 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009160 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9161 result = asciilib_count(
9162 ((Py_UCS1*)buf1) + start, end - start,
9163 buf2, len2, PY_SSIZE_T_MAX
9164 );
9165 else
9166 result = ucs1lib_count(
9167 ((Py_UCS1*)buf1) + start, end - start,
9168 buf2, len2, PY_SSIZE_T_MAX
9169 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009170 break;
9171 case PyUnicode_2BYTE_KIND:
9172 result = ucs2lib_count(
9173 ((Py_UCS2*)buf1) + start, end - start,
9174 buf2, len2, PY_SSIZE_T_MAX
9175 );
9176 break;
9177 case PyUnicode_4BYTE_KIND:
9178 result = ucs4lib_count(
9179 ((Py_UCS4*)buf1) + start, end - start,
9180 buf2, len2, PY_SSIZE_T_MAX
9181 );
9182 break;
9183 default:
9184 assert(0); result = 0;
9185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009186
9187 Py_DECREF(sub_obj);
9188 Py_DECREF(str_obj);
9189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 if (kind1 != kind)
9191 PyMem_Free(buf1);
9192 if (kind2 != kind)
9193 PyMem_Free(buf2);
9194
Guido van Rossumd57fd912000-03-10 22:53:23 +00009195 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196 onError:
9197 Py_DECREF(sub_obj);
9198 Py_DECREF(str_obj);
9199 if (kind1 != kind && buf1)
9200 PyMem_Free(buf1);
9201 if (kind2 != kind && buf2)
9202 PyMem_Free(buf2);
9203 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204}
9205
Alexander Belopolsky40018472011-02-26 01:02:56 +00009206Py_ssize_t
9207PyUnicode_Find(PyObject *str,
9208 PyObject *sub,
9209 Py_ssize_t start,
9210 Py_ssize_t end,
9211 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009212{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009213 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009214
Guido van Rossumd57fd912000-03-10 22:53:23 +00009215 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009216 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009217 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009218 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009220 Py_DECREF(str);
9221 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222 }
Tim Petersced69f82003-09-16 20:30:58 +00009223
Victor Stinner794d5672011-10-10 03:21:36 +02009224 result = any_find_slice(direction,
9225 str, sub, start, end
9226 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009227
Guido van Rossumd57fd912000-03-10 22:53:23 +00009228 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009229 Py_DECREF(sub);
9230
Guido van Rossumd57fd912000-03-10 22:53:23 +00009231 return result;
9232}
9233
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234Py_ssize_t
9235PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9236 Py_ssize_t start, Py_ssize_t end,
9237 int direction)
9238{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009240 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009241 if (PyUnicode_READY(str) == -1)
9242 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009243 if (start < 0 || end < 0) {
9244 PyErr_SetString(PyExc_IndexError, "string index out of range");
9245 return -2;
9246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247 if (end > PyUnicode_GET_LENGTH(str))
9248 end = PyUnicode_GET_LENGTH(str);
9249 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009250 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9251 kind, end-start, ch, direction);
9252 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009254 else
9255 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256}
9257
Alexander Belopolsky40018472011-02-26 01:02:56 +00009258static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009259tailmatch(PyObject *self,
9260 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009261 Py_ssize_t start,
9262 Py_ssize_t end,
9263 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 int kind_self;
9266 int kind_sub;
9267 void *data_self;
9268 void *data_sub;
9269 Py_ssize_t offset;
9270 Py_ssize_t i;
9271 Py_ssize_t end_sub;
9272
9273 if (PyUnicode_READY(self) == -1 ||
9274 PyUnicode_READY(substring) == -1)
9275 return 0;
9276
9277 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278 return 1;
9279
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9281 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009283 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 kind_self = PyUnicode_KIND(self);
9286 data_self = PyUnicode_DATA(self);
9287 kind_sub = PyUnicode_KIND(substring);
9288 data_sub = PyUnicode_DATA(substring);
9289 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9290
9291 if (direction > 0)
9292 offset = end;
9293 else
9294 offset = start;
9295
9296 if (PyUnicode_READ(kind_self, data_self, offset) ==
9297 PyUnicode_READ(kind_sub, data_sub, 0) &&
9298 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9299 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9300 /* If both are of the same kind, memcmp is sufficient */
9301 if (kind_self == kind_sub) {
9302 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009303 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304 data_sub,
9305 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009306 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009307 }
9308 /* otherwise we have to compare each character by first accesing it */
9309 else {
9310 /* We do not need to compare 0 and len(substring)-1 because
9311 the if statement above ensured already that they are equal
9312 when we end up here. */
9313 // TODO: honor direction and do a forward or backwards search
9314 for (i = 1; i < end_sub; ++i) {
9315 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9316 PyUnicode_READ(kind_sub, data_sub, i))
9317 return 0;
9318 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009319 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009321 }
9322
9323 return 0;
9324}
9325
Alexander Belopolsky40018472011-02-26 01:02:56 +00009326Py_ssize_t
9327PyUnicode_Tailmatch(PyObject *str,
9328 PyObject *substr,
9329 Py_ssize_t start,
9330 Py_ssize_t end,
9331 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009332{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009333 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009334
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 str = PyUnicode_FromObject(str);
9336 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009337 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338 substr = PyUnicode_FromObject(substr);
9339 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009340 Py_DECREF(str);
9341 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342 }
Tim Petersced69f82003-09-16 20:30:58 +00009343
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009344 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009345 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346 Py_DECREF(str);
9347 Py_DECREF(substr);
9348 return result;
9349}
9350
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351/* Apply fixfct filter to the Unicode object self and return a
9352 reference to the modified object */
9353
Alexander Belopolsky40018472011-02-26 01:02:56 +00009354static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009355fixup(PyObject *self,
9356 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358 PyObject *u;
9359 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360
Victor Stinner87af4f22011-11-21 23:03:47 +01009361 u = PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009363 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009364 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366 /* fix functions return the new maximum character in a string,
9367 if the kind of the resulting unicode object does not change,
9368 everything is fine. Otherwise we need to change the string kind
9369 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009370 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371 if (maxchar_new == 0)
9372 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9373 else if (maxchar_new <= 127)
9374 maxchar_new = 127;
9375 else if (maxchar_new <= 255)
9376 maxchar_new = 255;
9377 else if (maxchar_new <= 65535)
9378 maxchar_new = 65535;
9379 else
9380 maxchar_new = 1114111; /* 0x10ffff */
9381
9382 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 /* fixfct should return TRUE if it modified the buffer. If
9384 FALSE, return a reference to the original buffer instead
9385 (to save space, not time) */
9386 Py_INCREF(self);
9387 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009388 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 else if (maxchar_new == maxchar_old) {
9391 return u;
9392 }
9393 else {
9394 /* In case the maximum character changed, we need to
9395 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009396 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 if (v == NULL) {
9398 Py_DECREF(u);
9399 return NULL;
9400 }
9401 if (maxchar_new > maxchar_old) {
9402 /* If the maxchar increased so that the kind changed, not all
9403 characters are representable anymore and we need to fix the
9404 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009405 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009406 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9408 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009409 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009410 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412
9413 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009414 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 return v;
9416 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417}
9418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009420fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 /* No need to call PyUnicode_READY(self) because this function is only
9423 called as a callback from fixup() which does it already. */
9424 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9425 const int kind = PyUnicode_KIND(self);
9426 void *data = PyUnicode_DATA(self);
9427 int touched = 0;
9428 Py_UCS4 maxchar = 0;
9429 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 for (i = 0; i < len; ++i) {
9432 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9433 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9434 if (up != ch) {
9435 if (up > maxchar)
9436 maxchar = up;
9437 PyUnicode_WRITE(kind, data, i, up);
9438 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009440 else if (ch > maxchar)
9441 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442 }
9443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 if (touched)
9445 return maxchar;
9446 else
9447 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448}
9449
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009451fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9454 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9455 const int kind = PyUnicode_KIND(self);
9456 void *data = PyUnicode_DATA(self);
9457 int touched = 0;
9458 Py_UCS4 maxchar = 0;
9459 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 for(i = 0; i < len; ++i) {
9462 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9463 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9464 if (lo != ch) {
9465 if (lo > maxchar)
9466 maxchar = lo;
9467 PyUnicode_WRITE(kind, data, i, lo);
9468 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009469 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 else if (ch > maxchar)
9471 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472 }
9473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 if (touched)
9475 return maxchar;
9476 else
9477 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478}
9479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009481fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9484 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9485 const int kind = PyUnicode_KIND(self);
9486 void *data = PyUnicode_DATA(self);
9487 int touched = 0;
9488 Py_UCS4 maxchar = 0;
9489 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 for(i = 0; i < len; ++i) {
9492 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9493 Py_UCS4 nu = 0;
9494
9495 if (Py_UNICODE_ISUPPER(ch))
9496 nu = Py_UNICODE_TOLOWER(ch);
9497 else if (Py_UNICODE_ISLOWER(ch))
9498 nu = Py_UNICODE_TOUPPER(ch);
9499
9500 if (nu != 0) {
9501 if (nu > maxchar)
9502 maxchar = nu;
9503 PyUnicode_WRITE(kind, data, i, nu);
9504 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 else if (ch > maxchar)
9507 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508 }
9509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 if (touched)
9511 return maxchar;
9512 else
9513 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514}
9515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009517fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9520 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9521 const int kind = PyUnicode_KIND(self);
9522 void *data = PyUnicode_DATA(self);
9523 int touched = 0;
9524 Py_UCS4 maxchar = 0;
9525 Py_ssize_t i = 0;
9526 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009527
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009528 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009529 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530
9531 ch = PyUnicode_READ(kind, data, i);
9532 if (!Py_UNICODE_ISUPPER(ch)) {
9533 maxchar = Py_UNICODE_TOUPPER(ch);
9534 PyUnicode_WRITE(kind, data, i, maxchar);
9535 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009536 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009537 ++i;
9538 for(; i < len; ++i) {
9539 ch = PyUnicode_READ(kind, data, i);
9540 if (!Py_UNICODE_ISLOWER(ch)) {
9541 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9542 if (lo > maxchar)
9543 maxchar = lo;
9544 PyUnicode_WRITE(kind, data, i, lo);
9545 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 else if (ch > maxchar)
9548 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550
9551 if (touched)
9552 return maxchar;
9553 else
9554 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009555}
9556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009558fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9561 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9562 const int kind = PyUnicode_KIND(self);
9563 void *data = PyUnicode_DATA(self);
9564 Py_UCS4 maxchar = 0;
9565 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566 int previous_is_cased;
9567
9568 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 if (len == 1) {
9570 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9571 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9572 if (ti != ch) {
9573 PyUnicode_WRITE(kind, data, i, ti);
9574 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009575 }
9576 else
9577 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 for(; i < len; ++i) {
9581 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9582 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009583
Benjamin Peterson29060642009-01-31 22:14:21 +00009584 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009586 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 nu = Py_UNICODE_TOTITLE(ch);
9588
9589 if (nu > maxchar)
9590 maxchar = nu;
9591 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009592
Benjamin Peterson29060642009-01-31 22:14:21 +00009593 if (Py_UNICODE_ISLOWER(ch) ||
9594 Py_UNICODE_ISUPPER(ch) ||
9595 Py_UNICODE_ISTITLE(ch))
9596 previous_is_cased = 1;
9597 else
9598 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601}
9602
Tim Peters8ce9f162004-08-27 01:49:32 +00009603PyObject *
9604PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009606 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009607 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009609 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009610 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9611 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009612 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009614 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009616 int use_memcpy;
9617 unsigned char *res_data = NULL, *sep_data = NULL;
9618 PyObject *last_obj;
9619 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620
Tim Peters05eba1f2004-08-27 21:32:02 +00009621 fseq = PySequence_Fast(seq, "");
9622 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009623 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009624 }
9625
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009626 /* NOTE: the following code can't call back into Python code,
9627 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009628 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009629
Tim Peters05eba1f2004-08-27 21:32:02 +00009630 seqlen = PySequence_Fast_GET_SIZE(fseq);
9631 /* If empty sequence, return u"". */
9632 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009633 Py_DECREF(fseq);
9634 Py_INCREF(unicode_empty);
9635 res = unicode_empty;
9636 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009637 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009638
Tim Peters05eba1f2004-08-27 21:32:02 +00009639 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009640 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009641 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009642 if (seqlen == 1) {
9643 if (PyUnicode_CheckExact(items[0])) {
9644 res = items[0];
9645 Py_INCREF(res);
9646 Py_DECREF(fseq);
9647 return res;
9648 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009649 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009650 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009651 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009652 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009653 /* Set up sep and seplen */
9654 if (separator == NULL) {
9655 /* fall back to a blank space separator */
9656 sep = PyUnicode_FromOrdinal(' ');
9657 if (!sep)
9658 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009659 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009660 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009661 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009662 else {
9663 if (!PyUnicode_Check(separator)) {
9664 PyErr_Format(PyExc_TypeError,
9665 "separator: expected str instance,"
9666 " %.80s found",
9667 Py_TYPE(separator)->tp_name);
9668 goto onError;
9669 }
9670 if (PyUnicode_READY(separator))
9671 goto onError;
9672 sep = separator;
9673 seplen = PyUnicode_GET_LENGTH(separator);
9674 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9675 /* inc refcount to keep this code path symmetric with the
9676 above case of a blank separator */
9677 Py_INCREF(sep);
9678 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009679 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009680 }
9681
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009682 /* There are at least two things to join, or else we have a subclass
9683 * of str in the sequence.
9684 * Do a pre-pass to figure out the total amount of space we'll
9685 * need (sz), and see whether all argument are strings.
9686 */
9687 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009688#ifdef Py_DEBUG
9689 use_memcpy = 0;
9690#else
9691 use_memcpy = 1;
9692#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 for (i = 0; i < seqlen; i++) {
9694 const Py_ssize_t old_sz = sz;
9695 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009696 if (!PyUnicode_Check(item)) {
9697 PyErr_Format(PyExc_TypeError,
9698 "sequence item %zd: expected str instance,"
9699 " %.80s found",
9700 i, Py_TYPE(item)->tp_name);
9701 goto onError;
9702 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009703 if (PyUnicode_READY(item) == -1)
9704 goto onError;
9705 sz += PyUnicode_GET_LENGTH(item);
9706 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009707 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009708 if (i != 0)
9709 sz += seplen;
9710 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9711 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009712 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009713 goto onError;
9714 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009715 if (use_memcpy && last_obj != NULL) {
9716 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9717 use_memcpy = 0;
9718 }
9719 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009720 }
Tim Petersced69f82003-09-16 20:30:58 +00009721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009722 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009723 if (res == NULL)
9724 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009725
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009726 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009727#ifdef Py_DEBUG
9728 use_memcpy = 0;
9729#else
9730 if (use_memcpy) {
9731 res_data = PyUnicode_1BYTE_DATA(res);
9732 kind = PyUnicode_KIND(res);
9733 if (seplen != 0)
9734 sep_data = PyUnicode_1BYTE_DATA(sep);
9735 }
9736#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009737 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009738 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009739 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009740 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009741 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009742 if (use_memcpy) {
9743 Py_MEMCPY(res_data,
9744 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009745 kind * seplen);
9746 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009747 }
9748 else {
9749 copy_characters(res, res_offset, sep, 0, seplen);
9750 res_offset += seplen;
9751 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009752 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009753 itemlen = PyUnicode_GET_LENGTH(item);
9754 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009755 if (use_memcpy) {
9756 Py_MEMCPY(res_data,
9757 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009758 kind * itemlen);
9759 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009760 }
9761 else {
9762 copy_characters(res, res_offset, item, 0, itemlen);
9763 res_offset += itemlen;
9764 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009765 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009766 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009767 if (use_memcpy)
9768 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009769 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009770 else
9771 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009772
Tim Peters05eba1f2004-08-27 21:32:02 +00009773 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009775 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009776 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009777
Benjamin Peterson29060642009-01-31 22:14:21 +00009778 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009779 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009781 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782 return NULL;
9783}
9784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785#define FILL(kind, data, value, start, length) \
9786 do { \
9787 Py_ssize_t i_ = 0; \
9788 assert(kind != PyUnicode_WCHAR_KIND); \
9789 switch ((kind)) { \
9790 case PyUnicode_1BYTE_KIND: { \
9791 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9792 memset(to_, (unsigned char)value, length); \
9793 break; \
9794 } \
9795 case PyUnicode_2BYTE_KIND: { \
9796 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9797 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9798 break; \
9799 } \
9800 default: { \
9801 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9802 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9803 break; \
9804 } \
9805 } \
9806 } while (0)
9807
Victor Stinner9310abb2011-10-05 00:59:23 +02009808static PyObject *
9809pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009810 Py_ssize_t left,
9811 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 PyObject *u;
9815 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009816 int kind;
9817 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009818
9819 if (left < 0)
9820 left = 0;
9821 if (right < 0)
9822 right = 0;
9823
Tim Peters7a29bd52001-09-12 03:03:31 +00009824 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825 Py_INCREF(self);
9826 return self;
9827 }
9828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9830 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009831 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9832 return NULL;
9833 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009834 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9835 if (fill > maxchar)
9836 maxchar = fill;
9837 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009838 if (!u)
9839 return NULL;
9840
9841 kind = PyUnicode_KIND(u);
9842 data = PyUnicode_DATA(u);
9843 if (left)
9844 FILL(kind, data, fill, 0, left);
9845 if (right)
9846 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009847 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009848 assert(_PyUnicode_CheckConsistency(u, 1));
9849 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009850}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009852
Alexander Belopolsky40018472011-02-26 01:02:56 +00009853PyObject *
9854PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009855{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009856 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857
9858 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009860 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 switch(PyUnicode_KIND(string)) {
9863 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009864 if (PyUnicode_IS_ASCII(string))
9865 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009866 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009867 PyUnicode_GET_LENGTH(string), keepends);
9868 else
9869 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009870 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009871 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 break;
9873 case PyUnicode_2BYTE_KIND:
9874 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009875 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 PyUnicode_GET_LENGTH(string), keepends);
9877 break;
9878 case PyUnicode_4BYTE_KIND:
9879 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009880 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 PyUnicode_GET_LENGTH(string), keepends);
9882 break;
9883 default:
9884 assert(0);
9885 list = 0;
9886 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009887 Py_DECREF(string);
9888 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009889}
9890
Alexander Belopolsky40018472011-02-26 01:02:56 +00009891static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009892split(PyObject *self,
9893 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009894 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009896 int kind1, kind2, kind;
9897 void *buf1, *buf2;
9898 Py_ssize_t len1, len2;
9899 PyObject* out;
9900
Guido van Rossumd57fd912000-03-10 22:53:23 +00009901 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009902 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009904 if (PyUnicode_READY(self) == -1)
9905 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 if (substring == NULL)
9908 switch(PyUnicode_KIND(self)) {
9909 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009910 if (PyUnicode_IS_ASCII(self))
9911 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009912 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009913 PyUnicode_GET_LENGTH(self), maxcount
9914 );
9915 else
9916 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009917 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009918 PyUnicode_GET_LENGTH(self), maxcount
9919 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 case PyUnicode_2BYTE_KIND:
9921 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009922 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 PyUnicode_GET_LENGTH(self), maxcount
9924 );
9925 case PyUnicode_4BYTE_KIND:
9926 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009927 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 PyUnicode_GET_LENGTH(self), maxcount
9929 );
9930 default:
9931 assert(0);
9932 return NULL;
9933 }
9934
9935 if (PyUnicode_READY(substring) == -1)
9936 return NULL;
9937
9938 kind1 = PyUnicode_KIND(self);
9939 kind2 = PyUnicode_KIND(substring);
9940 kind = kind1 > kind2 ? kind1 : kind2;
9941 buf1 = PyUnicode_DATA(self);
9942 buf2 = PyUnicode_DATA(substring);
9943 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009944 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 if (!buf1)
9946 return NULL;
9947 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009948 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 if (!buf2) {
9950 if (kind1 != kind) PyMem_Free(buf1);
9951 return NULL;
9952 }
9953 len1 = PyUnicode_GET_LENGTH(self);
9954 len2 = PyUnicode_GET_LENGTH(substring);
9955
9956 switch(kind) {
9957 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009958 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9959 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009961 else
9962 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009963 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 break;
9965 case PyUnicode_2BYTE_KIND:
9966 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009967 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 break;
9969 case PyUnicode_4BYTE_KIND:
9970 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009971 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 break;
9973 default:
9974 out = NULL;
9975 }
9976 if (kind1 != kind)
9977 PyMem_Free(buf1);
9978 if (kind2 != kind)
9979 PyMem_Free(buf2);
9980 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009981}
9982
Alexander Belopolsky40018472011-02-26 01:02:56 +00009983static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009984rsplit(PyObject *self,
9985 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009986 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009987{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 int kind1, kind2, kind;
9989 void *buf1, *buf2;
9990 Py_ssize_t len1, len2;
9991 PyObject* out;
9992
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009993 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009994 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009996 if (PyUnicode_READY(self) == -1)
9997 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 if (substring == NULL)
10000 switch(PyUnicode_KIND(self)) {
10001 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010002 if (PyUnicode_IS_ASCII(self))
10003 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010004 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010005 PyUnicode_GET_LENGTH(self), maxcount
10006 );
10007 else
10008 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010010 PyUnicode_GET_LENGTH(self), maxcount
10011 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 case PyUnicode_2BYTE_KIND:
10013 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010014 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 PyUnicode_GET_LENGTH(self), maxcount
10016 );
10017 case PyUnicode_4BYTE_KIND:
10018 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010019 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 PyUnicode_GET_LENGTH(self), maxcount
10021 );
10022 default:
10023 assert(0);
10024 return NULL;
10025 }
10026
10027 if (PyUnicode_READY(substring) == -1)
10028 return NULL;
10029
10030 kind1 = PyUnicode_KIND(self);
10031 kind2 = PyUnicode_KIND(substring);
10032 kind = kind1 > kind2 ? kind1 : kind2;
10033 buf1 = PyUnicode_DATA(self);
10034 buf2 = PyUnicode_DATA(substring);
10035 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010036 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 if (!buf1)
10038 return NULL;
10039 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010040 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 if (!buf2) {
10042 if (kind1 != kind) PyMem_Free(buf1);
10043 return NULL;
10044 }
10045 len1 = PyUnicode_GET_LENGTH(self);
10046 len2 = PyUnicode_GET_LENGTH(substring);
10047
10048 switch(kind) {
10049 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010050 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10051 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010053 else
10054 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010055 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 break;
10057 case PyUnicode_2BYTE_KIND:
10058 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010059 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 break;
10061 case PyUnicode_4BYTE_KIND:
10062 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010063 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 break;
10065 default:
10066 out = NULL;
10067 }
10068 if (kind1 != kind)
10069 PyMem_Free(buf1);
10070 if (kind2 != kind)
10071 PyMem_Free(buf2);
10072 return out;
10073}
10074
10075static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010076anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10077 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078{
10079 switch(kind) {
10080 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010081 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10082 return asciilib_find(buf1, len1, buf2, len2, offset);
10083 else
10084 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 case PyUnicode_2BYTE_KIND:
10086 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10087 case PyUnicode_4BYTE_KIND:
10088 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10089 }
10090 assert(0);
10091 return -1;
10092}
10093
10094static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010095anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10096 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097{
10098 switch(kind) {
10099 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10101 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10102 else
10103 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 case PyUnicode_2BYTE_KIND:
10105 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10106 case PyUnicode_4BYTE_KIND:
10107 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10108 }
10109 assert(0);
10110 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010111}
10112
Alexander Belopolsky40018472011-02-26 01:02:56 +000010113static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114replace(PyObject *self, PyObject *str1,
10115 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 PyObject *u;
10118 char *sbuf = PyUnicode_DATA(self);
10119 char *buf1 = PyUnicode_DATA(str1);
10120 char *buf2 = PyUnicode_DATA(str2);
10121 int srelease = 0, release1 = 0, release2 = 0;
10122 int skind = PyUnicode_KIND(self);
10123 int kind1 = PyUnicode_KIND(str1);
10124 int kind2 = PyUnicode_KIND(str2);
10125 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10126 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10127 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010128 int mayshrink;
10129 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130
10131 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010132 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010134 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135
Victor Stinner59de0ee2011-10-07 10:01:28 +020010136 if (str1 == str2)
10137 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 if (skind < kind1)
10139 /* substring too wide to be present */
10140 goto nothing;
10141
Victor Stinner49a0a212011-10-12 23:46:10 +020010142 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10143 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10144 /* Replacing str1 with str2 may cause a maxchar reduction in the
10145 result string. */
10146 mayshrink = (maxchar_str2 < maxchar);
10147 maxchar = Py_MAX(maxchar, maxchar_str2);
10148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010150 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010151 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010153 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010155 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010156 Py_UCS4 u1, u2;
10157 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010159 if (findchar(sbuf, PyUnicode_KIND(self),
10160 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010161 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010164 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010166 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 rkind = PyUnicode_KIND(u);
10168 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10169 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010170 if (--maxcount < 0)
10171 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010173 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010174 }
10175 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 int rkind = skind;
10177 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 if (kind1 < rkind) {
10180 /* widen substring */
10181 buf1 = _PyUnicode_AsKind(str1, rkind);
10182 if (!buf1) goto error;
10183 release1 = 1;
10184 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010185 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010186 if (i < 0)
10187 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 if (rkind > kind2) {
10189 /* widen replacement */
10190 buf2 = _PyUnicode_AsKind(str2, rkind);
10191 if (!buf2) goto error;
10192 release2 = 1;
10193 }
10194 else if (rkind < kind2) {
10195 /* widen self and buf1 */
10196 rkind = kind2;
10197 if (release1) PyMem_Free(buf1);
10198 sbuf = _PyUnicode_AsKind(self, rkind);
10199 if (!sbuf) goto error;
10200 srelease = 1;
10201 buf1 = _PyUnicode_AsKind(str1, rkind);
10202 if (!buf1) goto error;
10203 release1 = 1;
10204 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010205 u = PyUnicode_New(slen, maxchar);
10206 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010208 assert(PyUnicode_KIND(u) == rkind);
10209 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010210
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010211 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010212 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010213 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010215 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010217
10218 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010220 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010222 if (i == -1)
10223 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010224 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010228 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010230 }
10231 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 Py_ssize_t n, i, j, ires;
10233 Py_ssize_t product, new_size;
10234 int rkind = skind;
10235 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010238 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 buf1 = _PyUnicode_AsKind(str1, rkind);
10240 if (!buf1) goto error;
10241 release1 = 1;
10242 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010243 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010244 if (n == 0)
10245 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010247 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 buf2 = _PyUnicode_AsKind(str2, rkind);
10249 if (!buf2) goto error;
10250 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010253 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 rkind = kind2;
10255 sbuf = _PyUnicode_AsKind(self, rkind);
10256 if (!sbuf) goto error;
10257 srelease = 1;
10258 if (release1) PyMem_Free(buf1);
10259 buf1 = _PyUnicode_AsKind(str1, rkind);
10260 if (!buf1) goto error;
10261 release1 = 1;
10262 }
10263 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10264 PyUnicode_GET_LENGTH(str1))); */
10265 product = n * (len2-len1);
10266 if ((product / (len2-len1)) != n) {
10267 PyErr_SetString(PyExc_OverflowError,
10268 "replace string is too long");
10269 goto error;
10270 }
10271 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010272 if (new_size == 0) {
10273 Py_INCREF(unicode_empty);
10274 u = unicode_empty;
10275 goto done;
10276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10278 PyErr_SetString(PyExc_OverflowError,
10279 "replace string is too long");
10280 goto error;
10281 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010282 u = PyUnicode_New(new_size, maxchar);
10283 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010285 assert(PyUnicode_KIND(u) == rkind);
10286 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 ires = i = 0;
10288 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010289 while (n-- > 0) {
10290 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010291 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010292 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010293 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010294 if (j == -1)
10295 break;
10296 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010297 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010298 memcpy(res + rkind * ires,
10299 sbuf + rkind * i,
10300 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010302 }
10303 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010305 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010307 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010311 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010313 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010314 memcpy(res + rkind * ires,
10315 sbuf + rkind * i,
10316 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010317 }
10318 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 /* interleave */
10320 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010321 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010323 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010325 if (--n <= 0)
10326 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010327 memcpy(res + rkind * ires,
10328 sbuf + rkind * i,
10329 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 ires++;
10331 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010332 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010333 memcpy(res + rkind * ires,
10334 sbuf + rkind * i,
10335 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010336 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010337 }
10338
10339 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010340 unicode_adjust_maxchar(&u);
10341 if (u == NULL)
10342 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010343 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010344
10345 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 if (srelease)
10347 PyMem_FREE(sbuf);
10348 if (release1)
10349 PyMem_FREE(buf1);
10350 if (release2)
10351 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010352 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010354
Benjamin Peterson29060642009-01-31 22:14:21 +000010355 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010356 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 if (srelease)
10358 PyMem_FREE(sbuf);
10359 if (release1)
10360 PyMem_FREE(buf1);
10361 if (release2)
10362 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010363 if (PyUnicode_CheckExact(self)) {
10364 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010365 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010366 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010367 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 error:
10369 if (srelease && sbuf)
10370 PyMem_FREE(sbuf);
10371 if (release1 && buf1)
10372 PyMem_FREE(buf1);
10373 if (release2 && buf2)
10374 PyMem_FREE(buf2);
10375 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376}
10377
10378/* --- Unicode Object Methods --------------------------------------------- */
10379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010380PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010381 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382\n\
10383Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010384characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385
10386static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010387unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010388{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389 return fixup(self, fixtitle);
10390}
10391
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010392PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010393 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394\n\
10395Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010396have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397
10398static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010399unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401 return fixup(self, fixcapitalize);
10402}
10403
10404#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010405PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010406 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010407\n\
10408Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010409normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410
10411static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010412unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413{
10414 PyObject *list;
10415 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010416 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418 /* Split into words */
10419 list = split(self, NULL, -1);
10420 if (!list)
10421 return NULL;
10422
10423 /* Capitalize each word */
10424 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010425 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010426 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010427 if (item == NULL)
10428 goto onError;
10429 Py_DECREF(PyList_GET_ITEM(list, i));
10430 PyList_SET_ITEM(list, i, item);
10431 }
10432
10433 /* Join the words to form a new string */
10434 item = PyUnicode_Join(NULL, list);
10435
Benjamin Peterson29060642009-01-31 22:14:21 +000010436 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010437 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010438 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010439}
10440#endif
10441
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010442/* Argument converter. Coerces to a single unicode character */
10443
10444static int
10445convert_uc(PyObject *obj, void *addr)
10446{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010448 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010449
Benjamin Peterson14339b62009-01-31 16:36:08 +000010450 uniobj = PyUnicode_FromObject(obj);
10451 if (uniobj == NULL) {
10452 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010453 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010454 return 0;
10455 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010457 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010458 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010459 Py_DECREF(uniobj);
10460 return 0;
10461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010463 Py_DECREF(uniobj);
10464 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010465}
10466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010467PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010468 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010470Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010471done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472
10473static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010474unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010476 Py_ssize_t marg, left;
10477 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 Py_UCS4 fillchar = ' ';
10479
Victor Stinnere9a29352011-10-01 02:14:59 +020010480 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482
Victor Stinnere9a29352011-10-01 02:14:59 +020010483 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484 return NULL;
10485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010488 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489 }
10490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492 left = marg / 2 + (marg & width & 1);
10493
Victor Stinner9310abb2011-10-05 00:59:23 +020010494 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010495}
10496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497/* This function assumes that str1 and str2 are readied by the caller. */
10498
Marc-André Lemburge5034372000-08-08 08:04:29 +000010499static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010500unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010501{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 int kind1, kind2;
10503 void *data1, *data2;
10504 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 kind1 = PyUnicode_KIND(str1);
10507 kind2 = PyUnicode_KIND(str2);
10508 data1 = PyUnicode_DATA(str1);
10509 data2 = PyUnicode_DATA(str2);
10510 len1 = PyUnicode_GET_LENGTH(str1);
10511 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 for (i = 0; i < len1 && i < len2; ++i) {
10514 Py_UCS4 c1, c2;
10515 c1 = PyUnicode_READ(kind1, data1, i);
10516 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010517
10518 if (c1 != c2)
10519 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010520 }
10521
10522 return (len1 < len2) ? -1 : (len1 != len2);
10523}
10524
Alexander Belopolsky40018472011-02-26 01:02:56 +000010525int
10526PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010527{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10529 if (PyUnicode_READY(left) == -1 ||
10530 PyUnicode_READY(right) == -1)
10531 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010532 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010534 PyErr_Format(PyExc_TypeError,
10535 "Can't compare %.100s and %.100s",
10536 left->ob_type->tp_name,
10537 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010538 return -1;
10539}
10540
Martin v. Löwis5b222132007-06-10 09:51:05 +000010541int
10542PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10543{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 Py_ssize_t i;
10545 int kind;
10546 void *data;
10547 Py_UCS4 chr;
10548
Victor Stinner910337b2011-10-03 03:20:16 +020010549 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 if (PyUnicode_READY(uni) == -1)
10551 return -1;
10552 kind = PyUnicode_KIND(uni);
10553 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010554 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10556 if (chr != str[i])
10557 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010558 /* This check keeps Python strings that end in '\0' from comparing equal
10559 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010562 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010563 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010564 return 0;
10565}
10566
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010567
Benjamin Peterson29060642009-01-31 22:14:21 +000010568#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010570
Alexander Belopolsky40018472011-02-26 01:02:56 +000010571PyObject *
10572PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010573{
10574 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010576 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10577 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 if (PyUnicode_READY(left) == -1 ||
10579 PyUnicode_READY(right) == -1)
10580 return NULL;
10581 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10582 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010583 if (op == Py_EQ) {
10584 Py_INCREF(Py_False);
10585 return Py_False;
10586 }
10587 if (op == Py_NE) {
10588 Py_INCREF(Py_True);
10589 return Py_True;
10590 }
10591 }
10592 if (left == right)
10593 result = 0;
10594 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010595 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010596
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010597 /* Convert the return value to a Boolean */
10598 switch (op) {
10599 case Py_EQ:
10600 v = TEST_COND(result == 0);
10601 break;
10602 case Py_NE:
10603 v = TEST_COND(result != 0);
10604 break;
10605 case Py_LE:
10606 v = TEST_COND(result <= 0);
10607 break;
10608 case Py_GE:
10609 v = TEST_COND(result >= 0);
10610 break;
10611 case Py_LT:
10612 v = TEST_COND(result == -1);
10613 break;
10614 case Py_GT:
10615 v = TEST_COND(result == 1);
10616 break;
10617 default:
10618 PyErr_BadArgument();
10619 return NULL;
10620 }
10621 Py_INCREF(v);
10622 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010624
Brian Curtindfc80e32011-08-10 20:28:54 -050010625 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010626}
10627
Alexander Belopolsky40018472011-02-26 01:02:56 +000010628int
10629PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010630{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010631 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 int kind1, kind2, kind;
10633 void *buf1, *buf2;
10634 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010635 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010636
10637 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010638 sub = PyUnicode_FromObject(element);
10639 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010640 PyErr_Format(PyExc_TypeError,
10641 "'in <string>' requires string as left operand, not %s",
10642 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010643 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010644 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 if (PyUnicode_READY(sub) == -1)
10646 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010647
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010649 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010650 Py_DECREF(sub);
10651 return -1;
10652 }
10653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 kind1 = PyUnicode_KIND(str);
10655 kind2 = PyUnicode_KIND(sub);
10656 kind = kind1 > kind2 ? kind1 : kind2;
10657 buf1 = PyUnicode_DATA(str);
10658 buf2 = PyUnicode_DATA(sub);
10659 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010660 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 if (!buf1) {
10662 Py_DECREF(sub);
10663 return -1;
10664 }
10665 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010666 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 if (!buf2) {
10668 Py_DECREF(sub);
10669 if (kind1 != kind) PyMem_Free(buf1);
10670 return -1;
10671 }
10672 len1 = PyUnicode_GET_LENGTH(str);
10673 len2 = PyUnicode_GET_LENGTH(sub);
10674
10675 switch(kind) {
10676 case PyUnicode_1BYTE_KIND:
10677 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10678 break;
10679 case PyUnicode_2BYTE_KIND:
10680 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10681 break;
10682 case PyUnicode_4BYTE_KIND:
10683 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10684 break;
10685 default:
10686 result = -1;
10687 assert(0);
10688 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010689
10690 Py_DECREF(str);
10691 Py_DECREF(sub);
10692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 if (kind1 != kind)
10694 PyMem_Free(buf1);
10695 if (kind2 != kind)
10696 PyMem_Free(buf2);
10697
Guido van Rossum403d68b2000-03-13 15:55:09 +000010698 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010699}
10700
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701/* Concat to string or Unicode object giving a new Unicode object. */
10702
Alexander Belopolsky40018472011-02-26 01:02:56 +000010703PyObject *
10704PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010705{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010706 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010707 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708
10709 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010712 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010715 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716
10717 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010718 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010719 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010722 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725 }
10726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010728 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10729 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 w = PyUnicode_New(
10733 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10734 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010736 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010737 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10738 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739 Py_DECREF(u);
10740 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010741 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743
Benjamin Peterson29060642009-01-31 22:14:21 +000010744 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745 Py_XDECREF(u);
10746 Py_XDECREF(v);
10747 return NULL;
10748}
10749
Victor Stinnerb0923652011-10-04 01:17:31 +020010750static void
10751unicode_append_inplace(PyObject **p_left, PyObject *right)
10752{
10753 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010754
10755 assert(PyUnicode_IS_READY(*p_left));
10756 assert(PyUnicode_IS_READY(right));
10757
10758 left_len = PyUnicode_GET_LENGTH(*p_left);
10759 right_len = PyUnicode_GET_LENGTH(right);
10760 if (left_len > PY_SSIZE_T_MAX - right_len) {
10761 PyErr_SetString(PyExc_OverflowError,
10762 "strings are too large to concat");
10763 goto error;
10764 }
10765 new_len = left_len + right_len;
10766
10767 /* Now we own the last reference to 'left', so we can resize it
10768 * in-place.
10769 */
10770 if (unicode_resize(p_left, new_len) != 0) {
10771 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10772 * deallocated so it cannot be put back into
10773 * 'variable'. The MemoryError is raised when there
10774 * is no value in 'variable', which might (very
10775 * remotely) be a cause of incompatibilities.
10776 */
10777 goto error;
10778 }
10779 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010780 copy_characters(*p_left, left_len, right, 0, right_len);
10781 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010782 return;
10783
10784error:
10785 Py_DECREF(*p_left);
10786 *p_left = NULL;
10787}
10788
Walter Dörwald1ab83302007-05-18 17:15:44 +000010789void
Victor Stinner23e56682011-10-03 03:54:37 +020010790PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010791{
Victor Stinner23e56682011-10-03 03:54:37 +020010792 PyObject *left, *res;
10793
10794 if (p_left == NULL) {
10795 if (!PyErr_Occurred())
10796 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010797 return;
10798 }
Victor Stinner23e56682011-10-03 03:54:37 +020010799 left = *p_left;
10800 if (right == NULL || !PyUnicode_Check(left)) {
10801 if (!PyErr_Occurred())
10802 PyErr_BadInternalCall();
10803 goto error;
10804 }
10805
Victor Stinnere1335c72011-10-04 20:53:03 +020010806 if (PyUnicode_READY(left))
10807 goto error;
10808 if (PyUnicode_READY(right))
10809 goto error;
10810
Victor Stinner23e56682011-10-03 03:54:37 +020010811 if (PyUnicode_CheckExact(left) && left != unicode_empty
10812 && PyUnicode_CheckExact(right) && right != unicode_empty
10813 && unicode_resizable(left)
10814 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10815 || _PyUnicode_WSTR(left) != NULL))
10816 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010817 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10818 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010819 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010820 not so different than duplicating the string. */
10821 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010822 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010823 unicode_append_inplace(p_left, right);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010824 assert(p_left == NULL || _PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010825 return;
10826 }
10827 }
10828
10829 res = PyUnicode_Concat(left, right);
10830 if (res == NULL)
10831 goto error;
10832 Py_DECREF(left);
10833 *p_left = res;
10834 return;
10835
10836error:
10837 Py_DECREF(*p_left);
10838 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010839}
10840
10841void
10842PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10843{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010844 PyUnicode_Append(pleft, right);
10845 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010846}
10847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010848PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010849 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010851Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010852string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010853interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010854
10855static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010856unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010858 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010859 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010860 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010862 int kind1, kind2, kind;
10863 void *buf1, *buf2;
10864 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010865
Jesus Ceaac451502011-04-20 17:09:23 +020010866 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10867 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010868 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010870 kind1 = PyUnicode_KIND(self);
10871 kind2 = PyUnicode_KIND(substring);
10872 kind = kind1 > kind2 ? kind1 : kind2;
10873 buf1 = PyUnicode_DATA(self);
10874 buf2 = PyUnicode_DATA(substring);
10875 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010876 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010877 if (!buf1) {
10878 Py_DECREF(substring);
10879 return NULL;
10880 }
10881 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010882 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010883 if (!buf2) {
10884 Py_DECREF(substring);
10885 if (kind1 != kind) PyMem_Free(buf1);
10886 return NULL;
10887 }
10888 len1 = PyUnicode_GET_LENGTH(self);
10889 len2 = PyUnicode_GET_LENGTH(substring);
10890
10891 ADJUST_INDICES(start, end, len1);
10892 switch(kind) {
10893 case PyUnicode_1BYTE_KIND:
10894 iresult = ucs1lib_count(
10895 ((Py_UCS1*)buf1) + start, end - start,
10896 buf2, len2, PY_SSIZE_T_MAX
10897 );
10898 break;
10899 case PyUnicode_2BYTE_KIND:
10900 iresult = ucs2lib_count(
10901 ((Py_UCS2*)buf1) + start, end - start,
10902 buf2, len2, PY_SSIZE_T_MAX
10903 );
10904 break;
10905 case PyUnicode_4BYTE_KIND:
10906 iresult = ucs4lib_count(
10907 ((Py_UCS4*)buf1) + start, end - start,
10908 buf2, len2, PY_SSIZE_T_MAX
10909 );
10910 break;
10911 default:
10912 assert(0); iresult = 0;
10913 }
10914
10915 result = PyLong_FromSsize_t(iresult);
10916
10917 if (kind1 != kind)
10918 PyMem_Free(buf1);
10919 if (kind2 != kind)
10920 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921
10922 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010923
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924 return result;
10925}
10926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010927PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010928 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010930Encode S using the codec registered for encoding. Default encoding\n\
10931is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010932handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010933a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10934'xmlcharrefreplace' as well as any other name registered with\n\
10935codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936
10937static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010938unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010940 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941 char *encoding = NULL;
10942 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010943
Benjamin Peterson308d6372009-09-18 21:42:35 +000010944 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10945 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010947 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010948}
10949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010950PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010951 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952\n\
10953Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010954If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955
10956static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010957unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010959 Py_ssize_t i, j, line_pos, src_len, incr;
10960 Py_UCS4 ch;
10961 PyObject *u;
10962 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010963 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010964 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010965 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010966
10967 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010968 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969
Antoine Pitrou22425222011-10-04 19:10:51 +020010970 if (PyUnicode_READY(self) == -1)
10971 return NULL;
10972
Thomas Wouters7e474022000-07-16 12:04:32 +000010973 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010974 src_len = PyUnicode_GET_LENGTH(self);
10975 i = j = line_pos = 0;
10976 kind = PyUnicode_KIND(self);
10977 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010978 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010979 for (; i < src_len; i++) {
10980 ch = PyUnicode_READ(kind, src_data, i);
10981 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010982 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010983 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010984 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010986 goto overflow;
10987 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010988 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010989 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010990 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010993 goto overflow;
10994 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010996 if (ch == '\n' || ch == '\r')
10997 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010999 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011000 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010011001 Py_INCREF(self);
11002 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011003 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011004
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011006 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 if (!u)
11008 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011009 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010
Antoine Pitroue71d5742011-10-04 15:55:09 +020011011 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012
Antoine Pitroue71d5742011-10-04 15:55:09 +020011013 for (; i < src_len; i++) {
11014 ch = PyUnicode_READ(kind, src_data, i);
11015 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011016 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011017 incr = tabsize - (line_pos % tabsize);
11018 line_pos += incr;
11019 while (incr--) {
11020 PyUnicode_WRITE(kind, dest_data, j, ' ');
11021 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011022 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011023 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011024 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011026 line_pos++;
11027 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011028 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011029 if (ch == '\n' || ch == '\r')
11030 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011032 }
11033 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011034 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011035
Antoine Pitroue71d5742011-10-04 15:55:09 +020011036 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011037 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11038 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039}
11040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011041PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043\n\
11044Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011045such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046arguments start and end are interpreted as in slice notation.\n\
11047\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011048Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049
11050static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011051unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011053 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011054 Py_ssize_t start;
11055 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011056 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057
Jesus Ceaac451502011-04-20 17:09:23 +020011058 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11059 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011062 if (PyUnicode_READY(self) == -1)
11063 return NULL;
11064 if (PyUnicode_READY(substring) == -1)
11065 return NULL;
11066
Victor Stinner7931d9a2011-11-04 00:22:48 +010011067 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068
11069 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071 if (result == -2)
11072 return NULL;
11073
Christian Heimes217cfd12007-12-02 14:31:20 +000011074 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075}
11076
11077static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011078unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011080 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11081 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084}
11085
Guido van Rossumc2504932007-09-18 19:42:40 +000011086/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011087 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011088static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011089unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090{
Guido van Rossumc2504932007-09-18 19:42:40 +000011091 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011092 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 if (_PyUnicode_HASH(self) != -1)
11095 return _PyUnicode_HASH(self);
11096 if (PyUnicode_READY(self) == -1)
11097 return -1;
11098 len = PyUnicode_GET_LENGTH(self);
11099
11100 /* The hash function as a macro, gets expanded three times below. */
11101#define HASH(P) \
11102 x = (Py_uhash_t)*P << 7; \
11103 while (--len >= 0) \
11104 x = (1000003*x) ^ (Py_uhash_t)*P++;
11105
11106 switch (PyUnicode_KIND(self)) {
11107 case PyUnicode_1BYTE_KIND: {
11108 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11109 HASH(c);
11110 break;
11111 }
11112 case PyUnicode_2BYTE_KIND: {
11113 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11114 HASH(s);
11115 break;
11116 }
11117 default: {
11118 Py_UCS4 *l;
11119 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11120 "Impossible switch case in unicode_hash");
11121 l = PyUnicode_4BYTE_DATA(self);
11122 HASH(l);
11123 break;
11124 }
11125 }
11126 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11127
Guido van Rossumc2504932007-09-18 19:42:40 +000011128 if (x == -1)
11129 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011130 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011131 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011135PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011136 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011138Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
11140static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011143 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011144 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011145 Py_ssize_t start;
11146 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147
Jesus Ceaac451502011-04-20 17:09:23 +020011148 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11149 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 if (PyUnicode_READY(self) == -1)
11153 return NULL;
11154 if (PyUnicode_READY(substring) == -1)
11155 return NULL;
11156
Victor Stinner7931d9a2011-11-04 00:22:48 +010011157 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158
11159 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011161 if (result == -2)
11162 return NULL;
11163
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164 if (result < 0) {
11165 PyErr_SetString(PyExc_ValueError, "substring not found");
11166 return NULL;
11167 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011168
Christian Heimes217cfd12007-12-02 14:31:20 +000011169 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170}
11171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011172PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011173 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011175Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011176at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177
11178static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011179unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011181 Py_ssize_t i, length;
11182 int kind;
11183 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011184 int cased;
11185
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 if (PyUnicode_READY(self) == -1)
11187 return NULL;
11188 length = PyUnicode_GET_LENGTH(self);
11189 kind = PyUnicode_KIND(self);
11190 data = PyUnicode_DATA(self);
11191
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 if (length == 1)
11194 return PyBool_FromLong(
11195 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011197 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011199 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011200
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 for (i = 0; i < length; i++) {
11203 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011204
Benjamin Peterson29060642009-01-31 22:14:21 +000011205 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11206 return PyBool_FromLong(0);
11207 else if (!cased && Py_UNICODE_ISLOWER(ch))
11208 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011210 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211}
11212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011213PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011214 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011216Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011217at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
11219static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011220unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 Py_ssize_t i, length;
11223 int kind;
11224 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 int cased;
11226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 if (PyUnicode_READY(self) == -1)
11228 return NULL;
11229 length = PyUnicode_GET_LENGTH(self);
11230 kind = PyUnicode_KIND(self);
11231 data = PyUnicode_DATA(self);
11232
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234 if (length == 1)
11235 return PyBool_FromLong(
11236 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011238 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011240 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011241
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011243 for (i = 0; i < length; i++) {
11244 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011245
Benjamin Peterson29060642009-01-31 22:14:21 +000011246 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11247 return PyBool_FromLong(0);
11248 else if (!cased && Py_UNICODE_ISUPPER(ch))
11249 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011251 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252}
11253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011254PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011257Return True if S is a titlecased string and there is at least one\n\
11258character in S, i.e. upper- and titlecase characters may only\n\
11259follow uncased characters and lowercase characters only cased ones.\n\
11260Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261
11262static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011263unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011265 Py_ssize_t i, length;
11266 int kind;
11267 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 int cased, previous_is_cased;
11269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011270 if (PyUnicode_READY(self) == -1)
11271 return NULL;
11272 length = PyUnicode_GET_LENGTH(self);
11273 kind = PyUnicode_KIND(self);
11274 data = PyUnicode_DATA(self);
11275
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 if (length == 1) {
11278 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11279 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11280 (Py_UNICODE_ISUPPER(ch) != 0));
11281 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011283 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011286
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287 cased = 0;
11288 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 for (i = 0; i < length; i++) {
11290 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011291
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11293 if (previous_is_cased)
11294 return PyBool_FromLong(0);
11295 previous_is_cased = 1;
11296 cased = 1;
11297 }
11298 else if (Py_UNICODE_ISLOWER(ch)) {
11299 if (!previous_is_cased)
11300 return PyBool_FromLong(0);
11301 previous_is_cased = 1;
11302 cased = 1;
11303 }
11304 else
11305 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011307 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308}
11309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011310PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011313Return True if all characters in S are whitespace\n\
11314and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315
11316static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011317unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 Py_ssize_t i, length;
11320 int kind;
11321 void *data;
11322
11323 if (PyUnicode_READY(self) == -1)
11324 return NULL;
11325 length = PyUnicode_GET_LENGTH(self);
11326 kind = PyUnicode_KIND(self);
11327 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 if (length == 1)
11331 return PyBool_FromLong(
11332 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011334 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011336 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011337
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 for (i = 0; i < length; i++) {
11339 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011340 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011341 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011343 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344}
11345
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011346PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011347 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011348\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011349Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011350and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011351
11352static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011353unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011354{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011355 Py_ssize_t i, length;
11356 int kind;
11357 void *data;
11358
11359 if (PyUnicode_READY(self) == -1)
11360 return NULL;
11361 length = PyUnicode_GET_LENGTH(self);
11362 kind = PyUnicode_KIND(self);
11363 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011365 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366 if (length == 1)
11367 return PyBool_FromLong(
11368 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011369
11370 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011372 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011373
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 for (i = 0; i < length; i++) {
11375 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011376 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011377 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011378 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011379}
11380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011381PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011382 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011383\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011384Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011385and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011386
11387static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011388unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011389{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 int kind;
11391 void *data;
11392 Py_ssize_t len, i;
11393
11394 if (PyUnicode_READY(self) == -1)
11395 return NULL;
11396
11397 kind = PyUnicode_KIND(self);
11398 data = PyUnicode_DATA(self);
11399 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011400
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011401 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 if (len == 1) {
11403 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11404 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11405 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011406
11407 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011409 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 for (i = 0; i < len; i++) {
11412 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011413 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011415 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011416 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011417}
11418
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011422Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011423False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424
11425static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011426unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 Py_ssize_t i, length;
11429 int kind;
11430 void *data;
11431
11432 if (PyUnicode_READY(self) == -1)
11433 return NULL;
11434 length = PyUnicode_GET_LENGTH(self);
11435 kind = PyUnicode_KIND(self);
11436 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (length == 1)
11440 return PyBool_FromLong(
11441 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011443 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 for (i = 0; i < length; i++) {
11448 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011451 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452}
11453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011454PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011457Return True if all characters in S are digits\n\
11458and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
11460static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011461unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 Py_ssize_t i, length;
11464 int kind;
11465 void *data;
11466
11467 if (PyUnicode_READY(self) == -1)
11468 return NULL;
11469 length = PyUnicode_GET_LENGTH(self);
11470 kind = PyUnicode_KIND(self);
11471 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 if (length == 1) {
11475 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11476 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011479 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011483 for (i = 0; i < length; i++) {
11484 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011487 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488}
11489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011490PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011491 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011493Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011494False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495
11496static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011497unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 Py_ssize_t i, length;
11500 int kind;
11501 void *data;
11502
11503 if (PyUnicode_READY(self) == -1)
11504 return NULL;
11505 length = PyUnicode_GET_LENGTH(self);
11506 kind = PyUnicode_KIND(self);
11507 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 if (length == 1)
11511 return PyBool_FromLong(
11512 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011514 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 for (i = 0; i < length; i++) {
11519 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011520 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011522 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523}
11524
Martin v. Löwis47383402007-08-15 07:32:56 +000011525int
11526PyUnicode_IsIdentifier(PyObject *self)
11527{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011528 int kind;
11529 void *data;
11530 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011531 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 if (PyUnicode_READY(self) == -1) {
11534 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 }
11537
11538 /* Special case for empty strings */
11539 if (PyUnicode_GET_LENGTH(self) == 0)
11540 return 0;
11541 kind = PyUnicode_KIND(self);
11542 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011543
11544 /* PEP 3131 says that the first character must be in
11545 XID_Start and subsequent characters in XID_Continue,
11546 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011547 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011548 letters, digits, underscore). However, given the current
11549 definition of XID_Start and XID_Continue, it is sufficient
11550 to check just for these, except that _ must be allowed
11551 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011553 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011554 return 0;
11555
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011556 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011559 return 1;
11560}
11561
11562PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011564\n\
11565Return True if S is a valid identifier according\n\
11566to the language definition.");
11567
11568static PyObject*
11569unicode_isidentifier(PyObject *self)
11570{
11571 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11572}
11573
Georg Brandl559e5d72008-06-11 18:37:52 +000011574PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011575 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011576\n\
11577Return True if all characters in S are considered\n\
11578printable in repr() or S is empty, False otherwise.");
11579
11580static PyObject*
11581unicode_isprintable(PyObject *self)
11582{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011583 Py_ssize_t i, length;
11584 int kind;
11585 void *data;
11586
11587 if (PyUnicode_READY(self) == -1)
11588 return NULL;
11589 length = PyUnicode_GET_LENGTH(self);
11590 kind = PyUnicode_KIND(self);
11591 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011592
11593 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 if (length == 1)
11595 return PyBool_FromLong(
11596 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011598 for (i = 0; i < length; i++) {
11599 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011600 Py_RETURN_FALSE;
11601 }
11602 }
11603 Py_RETURN_TRUE;
11604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011607 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
11609Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011610iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611
11612static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011613unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011615 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616}
11617
Martin v. Löwis18e16552006-02-15 17:27:45 +000011618static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011619unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 if (PyUnicode_READY(self) == -1)
11622 return -1;
11623 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624}
11625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011626PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011627 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011629Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011630done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631
11632static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011633unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011635 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 Py_UCS4 fillchar = ' ';
11637
11638 if (PyUnicode_READY(self) == -1)
11639 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011640
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011641 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642 return NULL;
11643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011646 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647 }
11648
Victor Stinner7931d9a2011-11-04 00:22:48 +010011649 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650}
11651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011652PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011653 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011655Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656
11657static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011658unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660 return fixup(self, fixlower);
11661}
11662
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011663#define LEFTSTRIP 0
11664#define RIGHTSTRIP 1
11665#define BOTHSTRIP 2
11666
11667/* Arrays indexed by above */
11668static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11669
11670#define STRIPNAME(i) (stripformat[i]+3)
11671
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011672/* externally visible for str.strip(unicode) */
11673PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011674_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011675{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 void *data;
11677 int kind;
11678 Py_ssize_t i, j, len;
11679 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011680
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11682 return NULL;
11683
11684 kind = PyUnicode_KIND(self);
11685 data = PyUnicode_DATA(self);
11686 len = PyUnicode_GET_LENGTH(self);
11687 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11688 PyUnicode_DATA(sepobj),
11689 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011690
Benjamin Peterson14339b62009-01-31 16:36:08 +000011691 i = 0;
11692 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 while (i < len &&
11694 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011695 i++;
11696 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011697 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011698
Benjamin Peterson14339b62009-01-31 16:36:08 +000011699 j = len;
11700 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011701 do {
11702 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011703 } while (j >= i &&
11704 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011705 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011706 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011707
Victor Stinner7931d9a2011-11-04 00:22:48 +010011708 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709}
11710
11711PyObject*
11712PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11713{
11714 unsigned char *data;
11715 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011716 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717
Victor Stinnerde636f32011-10-01 03:55:54 +020011718 if (PyUnicode_READY(self) == -1)
11719 return NULL;
11720
11721 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11722
Victor Stinner12bab6d2011-10-01 01:53:49 +020011723 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011725 if (PyUnicode_CheckExact(self)) {
11726 Py_INCREF(self);
11727 return self;
11728 }
11729 else
11730 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 }
11732
Victor Stinner12bab6d2011-10-01 01:53:49 +020011733 length = end - start;
11734 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011735 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736
Victor Stinnerde636f32011-10-01 03:55:54 +020011737 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011738 PyErr_SetString(PyExc_IndexError, "string index out of range");
11739 return NULL;
11740 }
11741
Victor Stinnerb9275c12011-10-05 14:01:42 +020011742 if (PyUnicode_IS_ASCII(self)) {
11743 kind = PyUnicode_KIND(self);
11744 data = PyUnicode_1BYTE_DATA(self);
11745 return unicode_fromascii(data + start, length);
11746 }
11747 else {
11748 kind = PyUnicode_KIND(self);
11749 data = PyUnicode_1BYTE_DATA(self);
11750 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011751 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011752 length);
11753 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
11756static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011757do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 int kind;
11760 void *data;
11761 Py_ssize_t len, i, j;
11762
11763 if (PyUnicode_READY(self) == -1)
11764 return NULL;
11765
11766 kind = PyUnicode_KIND(self);
11767 data = PyUnicode_DATA(self);
11768 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011769
Benjamin Peterson14339b62009-01-31 16:36:08 +000011770 i = 0;
11771 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011773 i++;
11774 }
11775 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011776
Benjamin Peterson14339b62009-01-31 16:36:08 +000011777 j = len;
11778 if (striptype != LEFTSTRIP) {
11779 do {
11780 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011782 j++;
11783 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
Victor Stinner7931d9a2011-11-04 00:22:48 +010011785 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786}
11787
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
11789static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011790do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011791{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011792 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011793
Benjamin Peterson14339b62009-01-31 16:36:08 +000011794 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11795 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796
Benjamin Peterson14339b62009-01-31 16:36:08 +000011797 if (sep != NULL && sep != Py_None) {
11798 if (PyUnicode_Check(sep))
11799 return _PyUnicode_XStrip(self, striptype, sep);
11800 else {
11801 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011802 "%s arg must be None or str",
11803 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011804 return NULL;
11805 }
11806 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807
Benjamin Peterson14339b62009-01-31 16:36:08 +000011808 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011809}
11810
11811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011812PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011814\n\
11815Return a copy of the string S with leading and trailing\n\
11816whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011817If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818
11819static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011820unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011821{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011822 if (PyTuple_GET_SIZE(args) == 0)
11823 return do_strip(self, BOTHSTRIP); /* Common case */
11824 else
11825 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011826}
11827
11828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011829PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011830 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011831\n\
11832Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011833If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834
11835static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011836unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011837{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011838 if (PyTuple_GET_SIZE(args) == 0)
11839 return do_strip(self, LEFTSTRIP); /* Common case */
11840 else
11841 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011842}
11843
11844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011845PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011846 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011847\n\
11848Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011849If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011850
11851static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011852unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011853{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011854 if (PyTuple_GET_SIZE(args) == 0)
11855 return do_strip(self, RIGHTSTRIP); /* Common case */
11856 else
11857 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011858}
11859
11860
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011862unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011864 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866
Georg Brandl222de0f2009-04-12 12:01:50 +000011867 if (len < 1) {
11868 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011869 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011870 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871
Tim Peters7a29bd52001-09-12 03:03:31 +000011872 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 /* no repeat, return original string */
11874 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011875 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876 }
Tim Peters8f422462000-09-09 06:13:41 +000011877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011878 if (PyUnicode_READY(str) == -1)
11879 return NULL;
11880
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011881 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011882 PyErr_SetString(PyExc_OverflowError,
11883 "repeated string is too long");
11884 return NULL;
11885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011887
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011888 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889 if (!u)
11890 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011891 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 if (PyUnicode_GET_LENGTH(str) == 1) {
11894 const int kind = PyUnicode_KIND(str);
11895 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11896 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011897 if (kind == PyUnicode_1BYTE_KIND)
11898 memset(to, (unsigned char)fill_char, len);
11899 else {
11900 for (n = 0; n < len; ++n)
11901 PyUnicode_WRITE(kind, to, n, fill_char);
11902 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 }
11904 else {
11905 /* number of characters copied this far */
11906 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011907 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 char *to = (char *) PyUnicode_DATA(u);
11909 Py_MEMCPY(to, PyUnicode_DATA(str),
11910 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011911 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 n = (done <= nchars-done) ? done : nchars-done;
11913 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011914 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916 }
11917
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011918 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011919 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920}
11921
Alexander Belopolsky40018472011-02-26 01:02:56 +000011922PyObject *
11923PyUnicode_Replace(PyObject *obj,
11924 PyObject *subobj,
11925 PyObject *replobj,
11926 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927{
11928 PyObject *self;
11929 PyObject *str1;
11930 PyObject *str2;
11931 PyObject *result;
11932
11933 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011934 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011935 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011937 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011938 Py_DECREF(self);
11939 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940 }
11941 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011942 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011943 Py_DECREF(self);
11944 Py_DECREF(str1);
11945 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948 Py_DECREF(self);
11949 Py_DECREF(str1);
11950 Py_DECREF(str2);
11951 return result;
11952}
11953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011954PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011955 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956\n\
11957Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011958old replaced by new. If the optional argument count is\n\
11959given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960
11961static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 PyObject *str1;
11965 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011966 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967 PyObject *result;
11968
Martin v. Löwis18e16552006-02-15 17:27:45 +000011969 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011972 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 str1 = PyUnicode_FromObject(str1);
11974 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11975 return NULL;
11976 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011977 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011978 Py_DECREF(str1);
11979 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011980 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981
11982 result = replace(self, str1, str2, maxcount);
11983
11984 Py_DECREF(str1);
11985 Py_DECREF(str2);
11986 return result;
11987}
11988
Alexander Belopolsky40018472011-02-26 01:02:56 +000011989static PyObject *
11990unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011991{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011992 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011993 Py_ssize_t isize;
11994 Py_ssize_t osize, squote, dquote, i, o;
11995 Py_UCS4 max, quote;
11996 int ikind, okind;
11997 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012000 return NULL;
12001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 isize = PyUnicode_GET_LENGTH(unicode);
12003 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012005 /* Compute length of output, quote characters, and
12006 maximum character */
12007 osize = 2; /* quotes */
12008 max = 127;
12009 squote = dquote = 0;
12010 ikind = PyUnicode_KIND(unicode);
12011 for (i = 0; i < isize; i++) {
12012 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12013 switch (ch) {
12014 case '\'': squote++; osize++; break;
12015 case '"': dquote++; osize++; break;
12016 case '\\': case '\t': case '\r': case '\n':
12017 osize += 2; break;
12018 default:
12019 /* Fast-path ASCII */
12020 if (ch < ' ' || ch == 0x7f)
12021 osize += 4; /* \xHH */
12022 else if (ch < 0x7f)
12023 osize++;
12024 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12025 osize++;
12026 max = ch > max ? ch : max;
12027 }
12028 else if (ch < 0x100)
12029 osize += 4; /* \xHH */
12030 else if (ch < 0x10000)
12031 osize += 6; /* \uHHHH */
12032 else
12033 osize += 10; /* \uHHHHHHHH */
12034 }
12035 }
12036
12037 quote = '\'';
12038 if (squote) {
12039 if (dquote)
12040 /* Both squote and dquote present. Use squote,
12041 and escape them */
12042 osize += squote;
12043 else
12044 quote = '"';
12045 }
12046
12047 repr = PyUnicode_New(osize, max);
12048 if (repr == NULL)
12049 return NULL;
12050 okind = PyUnicode_KIND(repr);
12051 odata = PyUnicode_DATA(repr);
12052
12053 PyUnicode_WRITE(okind, odata, 0, quote);
12054 PyUnicode_WRITE(okind, odata, osize-1, quote);
12055
12056 for (i = 0, o = 1; i < isize; i++) {
12057 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012058
12059 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 if ((ch == quote) || (ch == '\\')) {
12061 PyUnicode_WRITE(okind, odata, o++, '\\');
12062 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012063 continue;
12064 }
12065
Benjamin Peterson29060642009-01-31 22:14:21 +000012066 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012067 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 PyUnicode_WRITE(okind, odata, o++, '\\');
12069 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012070 }
12071 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012072 PyUnicode_WRITE(okind, odata, o++, '\\');
12073 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012074 }
12075 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012076 PyUnicode_WRITE(okind, odata, o++, '\\');
12077 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012078 }
12079
12080 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012081 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 PyUnicode_WRITE(okind, odata, o++, '\\');
12083 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012084 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12085 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012086 }
12087
Georg Brandl559e5d72008-06-11 18:37:52 +000012088 /* Copy ASCII characters as-is */
12089 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012090 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012091 }
12092
Benjamin Peterson29060642009-01-31 22:14:21 +000012093 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012094 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012095 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012096 (categories Z* and C* except ASCII space)
12097 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012098 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012099 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012100 if (ch <= 0xff) {
12101 PyUnicode_WRITE(okind, odata, o++, '\\');
12102 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012103 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12104 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012105 }
12106 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 else if (ch >= 0x10000) {
12108 PyUnicode_WRITE(okind, odata, o++, '\\');
12109 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012110 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12111 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12112 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12114 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12115 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12116 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12117 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012118 }
12119 /* Map 16-bit characters to '\uxxxx' */
12120 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 PyUnicode_WRITE(okind, odata, o++, '\\');
12122 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012123 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12124 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12125 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12126 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012127 }
12128 }
12129 /* Copy characters as-is */
12130 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012132 }
12133 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012134 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012136 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012137 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138}
12139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012140PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012141 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142\n\
12143Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012144such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145arguments start and end are interpreted as in slice notation.\n\
12146\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012147Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148
12149static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012152 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012153 Py_ssize_t start;
12154 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012155 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156
Jesus Ceaac451502011-04-20 17:09:23 +020012157 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12158 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012159 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 if (PyUnicode_READY(self) == -1)
12162 return NULL;
12163 if (PyUnicode_READY(substring) == -1)
12164 return NULL;
12165
Victor Stinner7931d9a2011-11-04 00:22:48 +010012166 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167
12168 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 if (result == -2)
12171 return NULL;
12172
Christian Heimes217cfd12007-12-02 14:31:20 +000012173 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174}
12175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012176PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012177 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012179Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180
12181static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012184 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012185 Py_ssize_t start;
12186 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012187 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
Jesus Ceaac451502011-04-20 17:09:23 +020012189 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12190 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012191 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 if (PyUnicode_READY(self) == -1)
12194 return NULL;
12195 if (PyUnicode_READY(substring) == -1)
12196 return NULL;
12197
Victor Stinner7931d9a2011-11-04 00:22:48 +010012198 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199
12200 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 if (result == -2)
12203 return NULL;
12204
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205 if (result < 0) {
12206 PyErr_SetString(PyExc_ValueError, "substring not found");
12207 return NULL;
12208 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209
Christian Heimes217cfd12007-12-02 14:31:20 +000012210 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211}
12212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012213PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012214 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012216Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012217done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218
12219static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012220unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012222 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 Py_UCS4 fillchar = ' ';
12224
Victor Stinnere9a29352011-10-01 02:14:59 +020012225 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012227
Victor Stinnere9a29352011-10-01 02:14:59 +020012228 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229 return NULL;
12230
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012233 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234 }
12235
Victor Stinner7931d9a2011-11-04 00:22:48 +010012236 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237}
12238
Alexander Belopolsky40018472011-02-26 01:02:56 +000012239PyObject *
12240PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
12242 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012243
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244 s = PyUnicode_FromObject(s);
12245 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012246 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012247 if (sep != NULL) {
12248 sep = PyUnicode_FromObject(sep);
12249 if (sep == NULL) {
12250 Py_DECREF(s);
12251 return NULL;
12252 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253 }
12254
Victor Stinner9310abb2011-10-05 00:59:23 +020012255 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256
12257 Py_DECREF(s);
12258 Py_XDECREF(sep);
12259 return result;
12260}
12261
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012262PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012263 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264\n\
12265Return a list of the words in S, using sep as the\n\
12266delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012267splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012268whitespace string is a separator and empty strings are\n\
12269removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270
12271static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012272unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273{
12274 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012275 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276
Martin v. Löwis18e16552006-02-15 17:27:45 +000012277 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278 return NULL;
12279
12280 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012281 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012283 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012285 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286}
12287
Thomas Wouters477c8d52006-05-27 19:21:47 +000012288PyObject *
12289PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12290{
12291 PyObject* str_obj;
12292 PyObject* sep_obj;
12293 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 int kind1, kind2, kind;
12295 void *buf1 = NULL, *buf2 = NULL;
12296 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012297
12298 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012299 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012300 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012301 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012303 Py_DECREF(str_obj);
12304 return NULL;
12305 }
12306
Victor Stinner14f8f022011-10-05 20:58:25 +020012307 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012309 kind = Py_MAX(kind1, kind2);
12310 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012312 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 if (!buf1)
12314 goto onError;
12315 buf2 = PyUnicode_DATA(sep_obj);
12316 if (kind2 != kind)
12317 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12318 if (!buf2)
12319 goto onError;
12320 len1 = PyUnicode_GET_LENGTH(str_obj);
12321 len2 = PyUnicode_GET_LENGTH(sep_obj);
12322
Victor Stinner14f8f022011-10-05 20:58:25 +020012323 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012325 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12326 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12327 else
12328 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012329 break;
12330 case PyUnicode_2BYTE_KIND:
12331 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12332 break;
12333 case PyUnicode_4BYTE_KIND:
12334 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12335 break;
12336 default:
12337 assert(0);
12338 out = 0;
12339 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012340
12341 Py_DECREF(sep_obj);
12342 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 if (kind1 != kind)
12344 PyMem_Free(buf1);
12345 if (kind2 != kind)
12346 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012347
12348 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 onError:
12350 Py_DECREF(sep_obj);
12351 Py_DECREF(str_obj);
12352 if (kind1 != kind && buf1)
12353 PyMem_Free(buf1);
12354 if (kind2 != kind && buf2)
12355 PyMem_Free(buf2);
12356 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012357}
12358
12359
12360PyObject *
12361PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12362{
12363 PyObject* str_obj;
12364 PyObject* sep_obj;
12365 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 int kind1, kind2, kind;
12367 void *buf1 = NULL, *buf2 = NULL;
12368 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369
12370 str_obj = PyUnicode_FromObject(str_in);
12371 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012372 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373 sep_obj = PyUnicode_FromObject(sep_in);
12374 if (!sep_obj) {
12375 Py_DECREF(str_obj);
12376 return NULL;
12377 }
12378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 kind1 = PyUnicode_KIND(str_in);
12380 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012381 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 buf1 = PyUnicode_DATA(str_in);
12383 if (kind1 != kind)
12384 buf1 = _PyUnicode_AsKind(str_in, kind);
12385 if (!buf1)
12386 goto onError;
12387 buf2 = PyUnicode_DATA(sep_obj);
12388 if (kind2 != kind)
12389 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12390 if (!buf2)
12391 goto onError;
12392 len1 = PyUnicode_GET_LENGTH(str_obj);
12393 len2 = PyUnicode_GET_LENGTH(sep_obj);
12394
12395 switch(PyUnicode_KIND(str_in)) {
12396 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012397 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12398 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12399 else
12400 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 break;
12402 case PyUnicode_2BYTE_KIND:
12403 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12404 break;
12405 case PyUnicode_4BYTE_KIND:
12406 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12407 break;
12408 default:
12409 assert(0);
12410 out = 0;
12411 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012412
12413 Py_DECREF(sep_obj);
12414 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 if (kind1 != kind)
12416 PyMem_Free(buf1);
12417 if (kind2 != kind)
12418 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012419
12420 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012421 onError:
12422 Py_DECREF(sep_obj);
12423 Py_DECREF(str_obj);
12424 if (kind1 != kind && buf1)
12425 PyMem_Free(buf1);
12426 if (kind2 != kind && buf2)
12427 PyMem_Free(buf2);
12428 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012429}
12430
12431PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012432 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012433\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012434Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012435the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012436found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012437
12438static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012439unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012440{
Victor Stinner9310abb2011-10-05 00:59:23 +020012441 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012442}
12443
12444PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012445 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012446\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012447Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012448the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012449separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450
12451static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012452unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012453{
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012455}
12456
Alexander Belopolsky40018472011-02-26 01:02:56 +000012457PyObject *
12458PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012459{
12460 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012461
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012462 s = PyUnicode_FromObject(s);
12463 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012464 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012465 if (sep != NULL) {
12466 sep = PyUnicode_FromObject(sep);
12467 if (sep == NULL) {
12468 Py_DECREF(s);
12469 return NULL;
12470 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012471 }
12472
Victor Stinner9310abb2011-10-05 00:59:23 +020012473 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012474
12475 Py_DECREF(s);
12476 Py_XDECREF(sep);
12477 return result;
12478}
12479
12480PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012481 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012482\n\
12483Return a list of the words in S, using sep as the\n\
12484delimiter string, starting at the end of the string and\n\
12485working to the front. If maxsplit is given, at most maxsplit\n\
12486splits are done. If sep is not specified, any whitespace string\n\
12487is a separator.");
12488
12489static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012490unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012491{
12492 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012493 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012494
Martin v. Löwis18e16552006-02-15 17:27:45 +000012495 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012496 return NULL;
12497
12498 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012499 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012500 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012501 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012502 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012503 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012504}
12505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012506PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012507 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508\n\
12509Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012510Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012511is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512
12513static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012514unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012516 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012517 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012519 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12520 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521 return NULL;
12522
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012523 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524}
12525
12526static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012527PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528{
Walter Dörwald346737f2007-05-31 10:44:43 +000012529 if (PyUnicode_CheckExact(self)) {
12530 Py_INCREF(self);
12531 return self;
12532 } else
12533 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012534 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535}
12536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012537PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012538 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539\n\
12540Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012541and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542
12543static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012544unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546 return fixup(self, fixswapcase);
12547}
12548
Georg Brandlceee0772007-11-27 23:48:05 +000012549PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012550 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012551\n\
12552Return a translation table usable for str.translate().\n\
12553If there is only one argument, it must be a dictionary mapping Unicode\n\
12554ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012555Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012556If there are two arguments, they must be strings of equal length, and\n\
12557in the resulting dictionary, each character in x will be mapped to the\n\
12558character at the same position in y. If there is a third argument, it\n\
12559must be a string, whose characters will be mapped to None in the result.");
12560
12561static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012562unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012563{
12564 PyObject *x, *y = NULL, *z = NULL;
12565 PyObject *new = NULL, *key, *value;
12566 Py_ssize_t i = 0;
12567 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012568
Georg Brandlceee0772007-11-27 23:48:05 +000012569 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12570 return NULL;
12571 new = PyDict_New();
12572 if (!new)
12573 return NULL;
12574 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 int x_kind, y_kind, z_kind;
12576 void *x_data, *y_data, *z_data;
12577
Georg Brandlceee0772007-11-27 23:48:05 +000012578 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012579 if (!PyUnicode_Check(x)) {
12580 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12581 "be a string if there is a second argument");
12582 goto err;
12583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012585 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12586 "arguments must have equal length");
12587 goto err;
12588 }
12589 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 x_kind = PyUnicode_KIND(x);
12591 y_kind = PyUnicode_KIND(y);
12592 x_data = PyUnicode_DATA(x);
12593 y_data = PyUnicode_DATA(y);
12594 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12595 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12596 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012597 if (!key || !value)
12598 goto err;
12599 res = PyDict_SetItem(new, key, value);
12600 Py_DECREF(key);
12601 Py_DECREF(value);
12602 if (res < 0)
12603 goto err;
12604 }
12605 /* create entries for deleting chars in z */
12606 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607 z_kind = PyUnicode_KIND(z);
12608 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012609 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012611 if (!key)
12612 goto err;
12613 res = PyDict_SetItem(new, key, Py_None);
12614 Py_DECREF(key);
12615 if (res < 0)
12616 goto err;
12617 }
12618 }
12619 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 int kind;
12621 void *data;
12622
Georg Brandlceee0772007-11-27 23:48:05 +000012623 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012624 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012625 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12626 "to maketrans it must be a dict");
12627 goto err;
12628 }
12629 /* copy entries into the new dict, converting string keys to int keys */
12630 while (PyDict_Next(x, &i, &key, &value)) {
12631 if (PyUnicode_Check(key)) {
12632 /* convert string keys to integer keys */
12633 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012634 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012635 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12636 "table must be of length 1");
12637 goto err;
12638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 kind = PyUnicode_KIND(key);
12640 data = PyUnicode_DATA(key);
12641 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012642 if (!newkey)
12643 goto err;
12644 res = PyDict_SetItem(new, newkey, value);
12645 Py_DECREF(newkey);
12646 if (res < 0)
12647 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012648 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012649 /* just keep integer keys */
12650 if (PyDict_SetItem(new, key, value) < 0)
12651 goto err;
12652 } else {
12653 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12654 "be strings or integers");
12655 goto err;
12656 }
12657 }
12658 }
12659 return new;
12660 err:
12661 Py_DECREF(new);
12662 return NULL;
12663}
12664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012665PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012666 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667\n\
12668Return a copy of the string S, where all characters have been mapped\n\
12669through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012670Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012671Unmapped characters are left untouched. Characters mapped to None\n\
12672are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673
12674static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678}
12679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012680PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012681 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012683Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684
12685static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012686unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688 return fixup(self, fixupper);
12689}
12690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012691PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012692 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012694Pad a numeric string S with zeros on the left, to fill a field\n\
12695of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696
12697static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012698unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012700 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012701 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012702 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 int kind;
12704 void *data;
12705 Py_UCS4 chr;
12706
12707 if (PyUnicode_READY(self) == -1)
12708 return NULL;
12709
Martin v. Löwis18e16552006-02-15 17:27:45 +000012710 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711 return NULL;
12712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012713 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012714 if (PyUnicode_CheckExact(self)) {
12715 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012716 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012717 }
12718 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012719 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720 }
12721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723
12724 u = pad(self, fill, 0, '0');
12725
Walter Dörwald068325e2002-04-15 13:36:47 +000012726 if (u == NULL)
12727 return NULL;
12728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012729 kind = PyUnicode_KIND(u);
12730 data = PyUnicode_DATA(u);
12731 chr = PyUnicode_READ(kind, data, fill);
12732
12733 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012735 PyUnicode_WRITE(kind, data, 0, chr);
12736 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737 }
12738
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012739 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012740 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742
12743#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012744static PyObject *
12745unicode__decimal2ascii(PyObject *self)
12746{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012748}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749#endif
12750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012751PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012754Return True if S starts with the specified prefix, False otherwise.\n\
12755With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012756With optional end, stop comparing S at that position.\n\
12757prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758
12759static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012760unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012761 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012762{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012763 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012764 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012765 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012766 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012767 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768
Jesus Ceaac451502011-04-20 17:09:23 +020012769 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012770 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012771 if (PyTuple_Check(subobj)) {
12772 Py_ssize_t i;
12773 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012774 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 if (substring == NULL)
12776 return NULL;
12777 result = tailmatch(self, substring, start, end, -1);
12778 Py_DECREF(substring);
12779 if (result) {
12780 Py_RETURN_TRUE;
12781 }
12782 }
12783 /* nothing matched */
12784 Py_RETURN_FALSE;
12785 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012786 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012787 if (substring == NULL) {
12788 if (PyErr_ExceptionMatches(PyExc_TypeError))
12789 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12790 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012791 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012792 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012793 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012795 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796}
12797
12798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012799PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012800 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012802Return True if S ends with the specified suffix, False otherwise.\n\
12803With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012804With optional end, stop comparing S at that position.\n\
12805suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806
12807static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012808unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012811 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012812 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012813 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012814 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012815 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816
Jesus Ceaac451502011-04-20 17:09:23 +020012817 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012818 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012819 if (PyTuple_Check(subobj)) {
12820 Py_ssize_t i;
12821 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012822 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012823 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012824 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012825 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012826 result = tailmatch(self, substring, start, end, +1);
12827 Py_DECREF(substring);
12828 if (result) {
12829 Py_RETURN_TRUE;
12830 }
12831 }
12832 Py_RETURN_FALSE;
12833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012834 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012835 if (substring == NULL) {
12836 if (PyErr_ExceptionMatches(PyExc_TypeError))
12837 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12838 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012839 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012840 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012841 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012842 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012843 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844}
12845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012846#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012847
12848PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012849 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012850\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012851Return a formatted version of S, using substitutions from args and kwargs.\n\
12852The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012853
Eric Smith27bbca62010-11-04 17:06:58 +000012854PyDoc_STRVAR(format_map__doc__,
12855 "S.format_map(mapping) -> str\n\
12856\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012857Return a formatted version of S, using substitutions from mapping.\n\
12858The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012859
Eric Smith4a7d76d2008-05-30 18:10:19 +000012860static PyObject *
12861unicode__format__(PyObject* self, PyObject* args)
12862{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012863 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012864
12865 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12866 return NULL;
12867
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012868 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012869 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012870 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012871}
12872
Eric Smith8c663262007-08-25 02:26:07 +000012873PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012874 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012875\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012876Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012877
12878static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012879unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012880{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 Py_ssize_t size;
12882
12883 /* If it's a compact object, account for base structure +
12884 character data. */
12885 if (PyUnicode_IS_COMPACT_ASCII(v))
12886 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12887 else if (PyUnicode_IS_COMPACT(v))
12888 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012889 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012890 else {
12891 /* If it is a two-block object, account for base object, and
12892 for character block if present. */
12893 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012894 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012896 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012897 }
12898 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012899 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012900 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012901 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012902 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012903 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012904
12905 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012906}
12907
12908PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012909 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012910
12911static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012912unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012913{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012914 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012915 if (!copy)
12916 return NULL;
12917 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012918}
12919
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920static PyMethodDef unicode_methods[] = {
12921
12922 /* Order is according to common usage: often used methods should
12923 appear first, since lookup is done sequentially. */
12924
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012925 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012926 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12927 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012928 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012929 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12930 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12931 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12932 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12933 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12934 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12935 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012936 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012937 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12938 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12939 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012940 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012941 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12942 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12943 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012944 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012945 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012946 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012947 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012948 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12949 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12950 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12951 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12952 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12953 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12954 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12955 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12956 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12957 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12958 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12959 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12960 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12961 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012962 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012963 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012964 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012965 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012966 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012967 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012968 {"maketrans", (PyCFunction) unicode_maketrans,
12969 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012970 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012971#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012972 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012973#endif
12974
12975#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012976 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012977 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012978#endif
12979
Benjamin Peterson14339b62009-01-31 16:36:08 +000012980 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981 {NULL, NULL}
12982};
12983
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012984static PyObject *
12985unicode_mod(PyObject *v, PyObject *w)
12986{
Brian Curtindfc80e32011-08-10 20:28:54 -050012987 if (!PyUnicode_Check(v))
12988 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012989 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012990}
12991
12992static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012993 0, /*nb_add*/
12994 0, /*nb_subtract*/
12995 0, /*nb_multiply*/
12996 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012997};
12998
Guido van Rossumd57fd912000-03-10 22:53:23 +000012999static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013000 (lenfunc) unicode_length, /* sq_length */
13001 PyUnicode_Concat, /* sq_concat */
13002 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13003 (ssizeargfunc) unicode_getitem, /* sq_item */
13004 0, /* sq_slice */
13005 0, /* sq_ass_item */
13006 0, /* sq_ass_slice */
13007 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013008};
13009
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013010static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013011unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013012{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 if (PyUnicode_READY(self) == -1)
13014 return NULL;
13015
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013016 if (PyIndex_Check(item)) {
13017 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013018 if (i == -1 && PyErr_Occurred())
13019 return NULL;
13020 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013022 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013023 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013024 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013025 PyObject *result;
13026 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013027 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013028 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013030 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013031 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013032 return NULL;
13033 }
13034
13035 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 return PyUnicode_New(0, 0);
13037 } else if (start == 0 && step == 1 &&
13038 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013039 PyUnicode_CheckExact(self)) {
13040 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013041 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013042 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013043 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013044 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013045 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013046 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013047 src_kind = PyUnicode_KIND(self);
13048 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013049 if (!PyUnicode_IS_ASCII(self)) {
13050 kind_limit = kind_maxchar_limit(src_kind);
13051 max_char = 0;
13052 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13053 ch = PyUnicode_READ(src_kind, src_data, cur);
13054 if (ch > max_char) {
13055 max_char = ch;
13056 if (max_char >= kind_limit)
13057 break;
13058 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013059 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013060 }
Victor Stinner55c99112011-10-13 01:17:06 +020013061 else
13062 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013063 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013064 if (result == NULL)
13065 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013066 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013067 dest_data = PyUnicode_DATA(result);
13068
13069 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013070 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13071 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013072 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013073 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013074 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013075 } else {
13076 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13077 return NULL;
13078 }
13079}
13080
13081static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013082 (lenfunc)unicode_length, /* mp_length */
13083 (binaryfunc)unicode_subscript, /* mp_subscript */
13084 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013085};
13086
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088/* Helpers for PyUnicode_Format() */
13089
13090static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013091getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013092{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013093 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 (*p_argidx)++;
13096 if (arglen < 0)
13097 return args;
13098 else
13099 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100 }
13101 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013102 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103 return NULL;
13104}
13105
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013106/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013108static PyObject *
13109formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013111 char *p;
13112 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013114
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115 x = PyFloat_AsDouble(v);
13116 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013117 return NULL;
13118
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013120 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013121
Eric Smith0923d1d2009-04-16 20:16:10 +000013122 p = PyOS_double_to_string(x, type, prec,
13123 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013124 if (p == NULL)
13125 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013126 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013127 PyMem_Free(p);
13128 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129}
13130
Tim Peters38fd5b62000-09-21 05:43:11 +000013131static PyObject*
13132formatlong(PyObject *val, int flags, int prec, int type)
13133{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013134 char *buf;
13135 int len;
13136 PyObject *str; /* temporary string object. */
13137 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013138
Benjamin Peterson14339b62009-01-31 16:36:08 +000013139 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13140 if (!str)
13141 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013143 Py_DECREF(str);
13144 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013145}
13146
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013147static Py_UCS4
13148formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013150 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013151 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013153 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013154 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013155 goto onError;
13156 }
13157 else {
13158 /* Integer input truncated to a character */
13159 long x;
13160 x = PyLong_AsLong(v);
13161 if (x == -1 && PyErr_Occurred())
13162 goto onError;
13163
13164 if (x < 0 || x > 0x10ffff) {
13165 PyErr_SetString(PyExc_OverflowError,
13166 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013167 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013168 }
13169
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013170 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013171 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013172
Benjamin Peterson29060642009-01-31 22:14:21 +000013173 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013174 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013176 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177}
13178
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013179static int
13180repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13181{
13182 int r;
13183 assert(count > 0);
13184 assert(PyUnicode_Check(obj));
13185 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013186 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013187 if (repeated == NULL)
13188 return -1;
13189 r = _PyAccu_Accumulate(acc, repeated);
13190 Py_DECREF(repeated);
13191 return r;
13192 }
13193 else {
13194 do {
13195 if (_PyAccu_Accumulate(acc, obj))
13196 return -1;
13197 } while (--count);
13198 return 0;
13199 }
13200}
13201
Alexander Belopolsky40018472011-02-26 01:02:56 +000013202PyObject *
13203PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013205 void *fmt;
13206 int fmtkind;
13207 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013208 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013209 int r;
13210 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013213 PyObject *temp = NULL;
13214 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013215 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013216 _PyAccu acc;
13217 static PyObject *plus, *minus, *blank, *zero, *percent;
13218
13219 if (!plus && !(plus = get_latin1_char('+')))
13220 return NULL;
13221 if (!minus && !(minus = get_latin1_char('-')))
13222 return NULL;
13223 if (!blank && !(blank = get_latin1_char(' ')))
13224 return NULL;
13225 if (!zero && !(zero = get_latin1_char('0')))
13226 return NULL;
13227 if (!percent && !(percent = get_latin1_char('%')))
13228 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013229
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 PyErr_BadInternalCall();
13232 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013234 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013235 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013236 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013237 if (_PyAccu_Init(&acc))
13238 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013239 fmt = PyUnicode_DATA(uformat);
13240 fmtkind = PyUnicode_KIND(uformat);
13241 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13242 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013243
Guido van Rossumd57fd912000-03-10 22:53:23 +000013244 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 arglen = PyTuple_Size(args);
13246 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013247 }
13248 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013249 arglen = -1;
13250 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013252 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013253 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255
13256 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013257 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013258 PyObject *nonfmt;
13259 Py_ssize_t nonfmtpos;
13260 nonfmtpos = fmtpos++;
13261 while (fmtcnt >= 0 &&
13262 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13263 fmtpos++;
13264 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013265 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013266 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 if (nonfmt == NULL)
13268 goto onError;
13269 r = _PyAccu_Accumulate(&acc, nonfmt);
13270 Py_DECREF(nonfmt);
13271 if (r)
13272 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013273 }
13274 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 /* Got a format specifier */
13276 int flags = 0;
13277 Py_ssize_t width = -1;
13278 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013279 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013280 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013281 int isnumok;
13282 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013283 void *pbuf = NULL;
13284 Py_ssize_t pindex, len;
13285 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 fmtpos++;
13288 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13289 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013290 Py_ssize_t keylen;
13291 PyObject *key;
13292 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013293
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 if (dict == NULL) {
13295 PyErr_SetString(PyExc_TypeError,
13296 "format requires a mapping");
13297 goto onError;
13298 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013299 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013300 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013301 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013302 /* Skip over balanced parentheses */
13303 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013304 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013305 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013306 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013307 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013310 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013311 if (fmtcnt < 0 || pcount > 0) {
13312 PyErr_SetString(PyExc_ValueError,
13313 "incomplete format key");
13314 goto onError;
13315 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013316 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013317 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013318 if (key == NULL)
13319 goto onError;
13320 if (args_owned) {
13321 Py_DECREF(args);
13322 args_owned = 0;
13323 }
13324 args = PyObject_GetItem(dict, key);
13325 Py_DECREF(key);
13326 if (args == NULL) {
13327 goto onError;
13328 }
13329 args_owned = 1;
13330 arglen = -1;
13331 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013332 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013333 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013334 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013335 case '-': flags |= F_LJUST; continue;
13336 case '+': flags |= F_SIGN; continue;
13337 case ' ': flags |= F_BLANK; continue;
13338 case '#': flags |= F_ALT; continue;
13339 case '0': flags |= F_ZERO; continue;
13340 }
13341 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013342 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 if (c == '*') {
13344 v = getnextarg(args, arglen, &argidx);
13345 if (v == NULL)
13346 goto onError;
13347 if (!PyLong_Check(v)) {
13348 PyErr_SetString(PyExc_TypeError,
13349 "* wants int");
13350 goto onError;
13351 }
13352 width = PyLong_AsLong(v);
13353 if (width == -1 && PyErr_Occurred())
13354 goto onError;
13355 if (width < 0) {
13356 flags |= F_LJUST;
13357 width = -width;
13358 }
13359 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013361 }
13362 else if (c >= '0' && c <= '9') {
13363 width = c - '0';
13364 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013365 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 if (c < '0' || c > '9')
13367 break;
13368 if ((width*10) / 10 != width) {
13369 PyErr_SetString(PyExc_ValueError,
13370 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013371 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013372 }
13373 width = width*10 + (c - '0');
13374 }
13375 }
13376 if (c == '.') {
13377 prec = 0;
13378 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013379 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 if (c == '*') {
13381 v = getnextarg(args, arglen, &argidx);
13382 if (v == NULL)
13383 goto onError;
13384 if (!PyLong_Check(v)) {
13385 PyErr_SetString(PyExc_TypeError,
13386 "* wants int");
13387 goto onError;
13388 }
13389 prec = PyLong_AsLong(v);
13390 if (prec == -1 && PyErr_Occurred())
13391 goto onError;
13392 if (prec < 0)
13393 prec = 0;
13394 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013395 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 }
13397 else if (c >= '0' && c <= '9') {
13398 prec = c - '0';
13399 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013400 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013401 if (c < '0' || c > '9')
13402 break;
13403 if ((prec*10) / 10 != prec) {
13404 PyErr_SetString(PyExc_ValueError,
13405 "prec too big");
13406 goto onError;
13407 }
13408 prec = prec*10 + (c - '0');
13409 }
13410 }
13411 } /* prec */
13412 if (fmtcnt >= 0) {
13413 if (c == 'h' || c == 'l' || c == 'L') {
13414 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013415 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 }
13417 }
13418 if (fmtcnt < 0) {
13419 PyErr_SetString(PyExc_ValueError,
13420 "incomplete format");
13421 goto onError;
13422 }
13423 if (c != '%') {
13424 v = getnextarg(args, arglen, &argidx);
13425 if (v == NULL)
13426 goto onError;
13427 }
13428 sign = 0;
13429 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013430 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013431 switch (c) {
13432
13433 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013434 _PyAccu_Accumulate(&acc, percent);
13435 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013436
13437 case 's':
13438 case 'r':
13439 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013440 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013441 temp = v;
13442 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013443 }
13444 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 if (c == 's')
13446 temp = PyObject_Str(v);
13447 else if (c == 'r')
13448 temp = PyObject_Repr(v);
13449 else
13450 temp = PyObject_ASCII(v);
13451 if (temp == NULL)
13452 goto onError;
13453 if (PyUnicode_Check(temp))
13454 /* nothing to do */;
13455 else {
13456 Py_DECREF(temp);
13457 PyErr_SetString(PyExc_TypeError,
13458 "%s argument has non-string str()");
13459 goto onError;
13460 }
13461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013462 if (PyUnicode_READY(temp) == -1) {
13463 Py_CLEAR(temp);
13464 goto onError;
13465 }
13466 pbuf = PyUnicode_DATA(temp);
13467 kind = PyUnicode_KIND(temp);
13468 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013469 if (prec >= 0 && len > prec)
13470 len = prec;
13471 break;
13472
13473 case 'i':
13474 case 'd':
13475 case 'u':
13476 case 'o':
13477 case 'x':
13478 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013479 isnumok = 0;
13480 if (PyNumber_Check(v)) {
13481 PyObject *iobj=NULL;
13482
13483 if (PyLong_Check(v)) {
13484 iobj = v;
13485 Py_INCREF(iobj);
13486 }
13487 else {
13488 iobj = PyNumber_Long(v);
13489 }
13490 if (iobj!=NULL) {
13491 if (PyLong_Check(iobj)) {
13492 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013493 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 Py_DECREF(iobj);
13495 if (!temp)
13496 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013497 if (PyUnicode_READY(temp) == -1) {
13498 Py_CLEAR(temp);
13499 goto onError;
13500 }
13501 pbuf = PyUnicode_DATA(temp);
13502 kind = PyUnicode_KIND(temp);
13503 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013504 sign = 1;
13505 }
13506 else {
13507 Py_DECREF(iobj);
13508 }
13509 }
13510 }
13511 if (!isnumok) {
13512 PyErr_Format(PyExc_TypeError,
13513 "%%%c format: a number is required, "
13514 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13515 goto onError;
13516 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013517 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013519 fillobj = zero;
13520 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 break;
13522
13523 case 'e':
13524 case 'E':
13525 case 'f':
13526 case 'F':
13527 case 'g':
13528 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013529 temp = formatfloat(v, flags, prec, c);
13530 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013532 if (PyUnicode_READY(temp) == -1) {
13533 Py_CLEAR(temp);
13534 goto onError;
13535 }
13536 pbuf = PyUnicode_DATA(temp);
13537 kind = PyUnicode_KIND(temp);
13538 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013539 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013540 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013541 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013542 fillobj = zero;
13543 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013544 break;
13545
13546 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013547 {
13548 Py_UCS4 ch = formatchar(v);
13549 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013551 temp = _PyUnicode_FromUCS4(&ch, 1);
13552 if (temp == NULL)
13553 goto onError;
13554 pbuf = PyUnicode_DATA(temp);
13555 kind = PyUnicode_KIND(temp);
13556 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013557 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013558 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013559
13560 default:
13561 PyErr_Format(PyExc_ValueError,
13562 "unsupported format character '%c' (0x%x) "
13563 "at index %zd",
13564 (31<=c && c<=126) ? (char)c : '?',
13565 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013566 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 goto onError;
13568 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013569 /* pbuf is initialized here. */
13570 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013572 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13573 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013574 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013575 pindex++;
13576 }
13577 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13578 signobj = plus;
13579 len--;
13580 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013581 }
13582 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013583 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013584 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013585 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 else
13587 sign = 0;
13588 }
13589 if (width < len)
13590 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013592 if (fill != ' ') {
13593 assert(signobj != NULL);
13594 if (_PyAccu_Accumulate(&acc, signobj))
13595 goto onError;
13596 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 if (width > len)
13598 width--;
13599 }
13600 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013601 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013602 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013603 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013604 second = get_latin1_char(
13605 PyUnicode_READ(kind, pbuf, pindex + 1));
13606 pindex += 2;
13607 if (second == NULL ||
13608 _PyAccu_Accumulate(&acc, zero) ||
13609 _PyAccu_Accumulate(&acc, second))
13610 goto onError;
13611 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013612 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013613 width -= 2;
13614 if (width < 0)
13615 width = 0;
13616 len -= 2;
13617 }
13618 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013619 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013620 if (repeat_accumulate(&acc, fillobj, width - len))
13621 goto onError;
13622 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013623 }
13624 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013625 if (sign) {
13626 assert(signobj != NULL);
13627 if (_PyAccu_Accumulate(&acc, signobj))
13628 goto onError;
13629 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013631 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13632 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013633 second = get_latin1_char(
13634 PyUnicode_READ(kind, pbuf, pindex + 1));
13635 pindex += 2;
13636 if (second == NULL ||
13637 _PyAccu_Accumulate(&acc, zero) ||
13638 _PyAccu_Accumulate(&acc, second))
13639 goto onError;
13640 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013641 }
13642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013643 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013644 if (temp != NULL) {
13645 assert(pbuf == PyUnicode_DATA(temp));
13646 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013647 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013648 else {
13649 const char *p = (const char *) pbuf;
13650 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013651 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013652 v = PyUnicode_FromKindAndData(kind, p, len);
13653 }
13654 if (v == NULL)
13655 goto onError;
13656 r = _PyAccu_Accumulate(&acc, v);
13657 Py_DECREF(v);
13658 if (r)
13659 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013660 if (width > len && repeat_accumulate(&acc, blank, width - len))
13661 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 if (dict && (argidx < arglen) && c != '%') {
13663 PyErr_SetString(PyExc_TypeError,
13664 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 goto onError;
13666 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013667 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013669 } /* until end */
13670 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 PyErr_SetString(PyExc_TypeError,
13672 "not all arguments converted during string formatting");
13673 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013674 }
13675
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013676 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013677 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013679 }
13680 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013681 Py_XDECREF(temp);
13682 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013683 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013684
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013686 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013687 Py_XDECREF(temp);
13688 Py_XDECREF(second);
13689 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013690 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013692 }
13693 return NULL;
13694}
13695
Jeremy Hylton938ace62002-07-17 16:30:39 +000013696static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013697unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13698
Tim Peters6d6c1a32001-08-02 04:15:00 +000013699static PyObject *
13700unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13701{
Benjamin Peterson29060642009-01-31 22:14:21 +000013702 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013703 static char *kwlist[] = {"object", "encoding", "errors", 0};
13704 char *encoding = NULL;
13705 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013706
Benjamin Peterson14339b62009-01-31 16:36:08 +000013707 if (type != &PyUnicode_Type)
13708 return unicode_subtype_new(type, args, kwds);
13709 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013710 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013711 return NULL;
13712 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013713 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013714 if (encoding == NULL && errors == NULL)
13715 return PyObject_Str(x);
13716 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013717 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013718}
13719
Guido van Rossume023fe02001-08-30 03:12:59 +000013720static PyObject *
13721unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13722{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013723 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013724 Py_ssize_t length, char_size;
13725 int share_wstr, share_utf8;
13726 unsigned int kind;
13727 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013728
Benjamin Peterson14339b62009-01-31 16:36:08 +000013729 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013730
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013731 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013732 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013733 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013734 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013735 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013736 return NULL;
13737
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013738 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013739 if (self == NULL) {
13740 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013741 return NULL;
13742 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013743 kind = PyUnicode_KIND(unicode);
13744 length = PyUnicode_GET_LENGTH(unicode);
13745
13746 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013747#ifdef Py_DEBUG
13748 _PyUnicode_HASH(self) = -1;
13749#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013750 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013751#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013752 _PyUnicode_STATE(self).interned = 0;
13753 _PyUnicode_STATE(self).kind = kind;
13754 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013755 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013756 _PyUnicode_STATE(self).ready = 1;
13757 _PyUnicode_WSTR(self) = NULL;
13758 _PyUnicode_UTF8_LENGTH(self) = 0;
13759 _PyUnicode_UTF8(self) = NULL;
13760 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013761 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013762
13763 share_utf8 = 0;
13764 share_wstr = 0;
13765 if (kind == PyUnicode_1BYTE_KIND) {
13766 char_size = 1;
13767 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13768 share_utf8 = 1;
13769 }
13770 else if (kind == PyUnicode_2BYTE_KIND) {
13771 char_size = 2;
13772 if (sizeof(wchar_t) == 2)
13773 share_wstr = 1;
13774 }
13775 else {
13776 assert(kind == PyUnicode_4BYTE_KIND);
13777 char_size = 4;
13778 if (sizeof(wchar_t) == 4)
13779 share_wstr = 1;
13780 }
13781
13782 /* Ensure we won't overflow the length. */
13783 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13784 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013785 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013786 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013787 data = PyObject_MALLOC((length + 1) * char_size);
13788 if (data == NULL) {
13789 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790 goto onError;
13791 }
13792
Victor Stinnerc3c74152011-10-02 20:39:55 +020013793 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013794 if (share_utf8) {
13795 _PyUnicode_UTF8_LENGTH(self) = length;
13796 _PyUnicode_UTF8(self) = data;
13797 }
13798 if (share_wstr) {
13799 _PyUnicode_WSTR_LENGTH(self) = length;
13800 _PyUnicode_WSTR(self) = (wchar_t *)data;
13801 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013802
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013803 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013804 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013805 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013806#ifdef Py_DEBUG
13807 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13808#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013809 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013810 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013811
13812onError:
13813 Py_DECREF(unicode);
13814 Py_DECREF(self);
13815 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013816}
13817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013818PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013819 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013820\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013821Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013822encoding defaults to the current default string encoding.\n\
13823errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013824
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013825static PyObject *unicode_iter(PyObject *seq);
13826
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013828 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013829 "str", /* tp_name */
13830 sizeof(PyUnicodeObject), /* tp_size */
13831 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013832 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013833 (destructor)unicode_dealloc, /* tp_dealloc */
13834 0, /* tp_print */
13835 0, /* tp_getattr */
13836 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013837 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013838 unicode_repr, /* tp_repr */
13839 &unicode_as_number, /* tp_as_number */
13840 &unicode_as_sequence, /* tp_as_sequence */
13841 &unicode_as_mapping, /* tp_as_mapping */
13842 (hashfunc) unicode_hash, /* tp_hash*/
13843 0, /* tp_call*/
13844 (reprfunc) unicode_str, /* tp_str */
13845 PyObject_GenericGetAttr, /* tp_getattro */
13846 0, /* tp_setattro */
13847 0, /* tp_as_buffer */
13848 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013849 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013850 unicode_doc, /* tp_doc */
13851 0, /* tp_traverse */
13852 0, /* tp_clear */
13853 PyUnicode_RichCompare, /* tp_richcompare */
13854 0, /* tp_weaklistoffset */
13855 unicode_iter, /* tp_iter */
13856 0, /* tp_iternext */
13857 unicode_methods, /* tp_methods */
13858 0, /* tp_members */
13859 0, /* tp_getset */
13860 &PyBaseObject_Type, /* tp_base */
13861 0, /* tp_dict */
13862 0, /* tp_descr_get */
13863 0, /* tp_descr_set */
13864 0, /* tp_dictoffset */
13865 0, /* tp_init */
13866 0, /* tp_alloc */
13867 unicode_new, /* tp_new */
13868 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013869};
13870
13871/* Initialize the Unicode implementation */
13872
Victor Stinner3a50e702011-10-18 21:21:00 +020013873int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013874{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013875 int i;
13876
Thomas Wouters477c8d52006-05-27 19:21:47 +000013877 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013878 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013879 0x000A, /* LINE FEED */
13880 0x000D, /* CARRIAGE RETURN */
13881 0x001C, /* FILE SEPARATOR */
13882 0x001D, /* GROUP SEPARATOR */
13883 0x001E, /* RECORD SEPARATOR */
13884 0x0085, /* NEXT LINE */
13885 0x2028, /* LINE SEPARATOR */
13886 0x2029, /* PARAGRAPH SEPARATOR */
13887 };
13888
Fred Drakee4315f52000-05-09 19:53:39 +000013889 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013890 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013891 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013892 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013893 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013894
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013895 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013896 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013897 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013899
13900 /* initialize the linebreak bloom filter */
13901 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013902 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013903 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013904
13905 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013906
13907#ifdef HAVE_MBCS
13908 winver.dwOSVersionInfoSize = sizeof(winver);
13909 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13910 PyErr_SetFromWindowsErr(0);
13911 return -1;
13912 }
13913#endif
13914 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013915}
13916
13917/* Finalize the Unicode implementation */
13918
Christian Heimesa156e092008-02-16 07:38:31 +000013919int
13920PyUnicode_ClearFreeList(void)
13921{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013922 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013923}
13924
Guido van Rossumd57fd912000-03-10 22:53:23 +000013925void
Thomas Wouters78890102000-07-22 19:25:51 +000013926_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013927{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013928 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013929
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013930 Py_XDECREF(unicode_empty);
13931 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013932
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013933 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013934 if (unicode_latin1[i]) {
13935 Py_DECREF(unicode_latin1[i]);
13936 unicode_latin1[i] = NULL;
13937 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013938 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013939 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013940 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013941}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013942
Walter Dörwald16807132007-05-25 13:52:07 +000013943void
13944PyUnicode_InternInPlace(PyObject **p)
13945{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013946 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013947 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013948#ifdef Py_DEBUG
13949 assert(s != NULL);
13950 assert(_PyUnicode_CHECK(s));
13951#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013952 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013953 return;
13954#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013955 /* If it's a subclass, we don't really know what putting
13956 it in the interned dict might do. */
13957 if (!PyUnicode_CheckExact(s))
13958 return;
13959 if (PyUnicode_CHECK_INTERNED(s))
13960 return;
13961 if (interned == NULL) {
13962 interned = PyDict_New();
13963 if (interned == NULL) {
13964 PyErr_Clear(); /* Don't leave an exception */
13965 return;
13966 }
13967 }
13968 /* It might be that the GetItem call fails even
13969 though the key is present in the dictionary,
13970 namely when this happens during a stack overflow. */
13971 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013972 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013973 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013974
Benjamin Peterson29060642009-01-31 22:14:21 +000013975 if (t) {
13976 Py_INCREF(t);
13977 Py_DECREF(*p);
13978 *p = t;
13979 return;
13980 }
Walter Dörwald16807132007-05-25 13:52:07 +000013981
Benjamin Peterson14339b62009-01-31 16:36:08 +000013982 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013983 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013984 PyErr_Clear();
13985 PyThreadState_GET()->recursion_critical = 0;
13986 return;
13987 }
13988 PyThreadState_GET()->recursion_critical = 0;
13989 /* The two references in interned are not counted by refcnt.
13990 The deallocator will take care of this */
13991 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013992 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013993}
13994
13995void
13996PyUnicode_InternImmortal(PyObject **p)
13997{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 PyUnicode_InternInPlace(p);
13999 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014000 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014001 Py_INCREF(*p);
14002 }
Walter Dörwald16807132007-05-25 13:52:07 +000014003}
14004
14005PyObject *
14006PyUnicode_InternFromString(const char *cp)
14007{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014008 PyObject *s = PyUnicode_FromString(cp);
14009 if (s == NULL)
14010 return NULL;
14011 PyUnicode_InternInPlace(&s);
14012 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014013}
14014
Alexander Belopolsky40018472011-02-26 01:02:56 +000014015void
14016_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014017{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014018 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014019 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014020 Py_ssize_t i, n;
14021 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014022
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 if (interned == NULL || !PyDict_Check(interned))
14024 return;
14025 keys = PyDict_Keys(interned);
14026 if (keys == NULL || !PyList_Check(keys)) {
14027 PyErr_Clear();
14028 return;
14029 }
Walter Dörwald16807132007-05-25 13:52:07 +000014030
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14032 detector, interned unicode strings are not forcibly deallocated;
14033 rather, we give them their stolen references back, and then clear
14034 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014035
Benjamin Peterson14339b62009-01-31 16:36:08 +000014036 n = PyList_GET_SIZE(keys);
14037 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014038 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014039 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014040 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014041 if (PyUnicode_READY(s) == -1) {
14042 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014043 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014044 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014045 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014046 case SSTATE_NOT_INTERNED:
14047 /* XXX Shouldn't happen */
14048 break;
14049 case SSTATE_INTERNED_IMMORTAL:
14050 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014051 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014052 break;
14053 case SSTATE_INTERNED_MORTAL:
14054 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014055 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014056 break;
14057 default:
14058 Py_FatalError("Inconsistent interned string state.");
14059 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014060 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014061 }
14062 fprintf(stderr, "total size of all interned strings: "
14063 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14064 "mortal/immortal\n", mortal_size, immortal_size);
14065 Py_DECREF(keys);
14066 PyDict_Clear(interned);
14067 Py_DECREF(interned);
14068 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014069}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014070
14071
14072/********************* Unicode Iterator **************************/
14073
14074typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014075 PyObject_HEAD
14076 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014077 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014078} unicodeiterobject;
14079
14080static void
14081unicodeiter_dealloc(unicodeiterobject *it)
14082{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 _PyObject_GC_UNTRACK(it);
14084 Py_XDECREF(it->it_seq);
14085 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014086}
14087
14088static int
14089unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14090{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 Py_VISIT(it->it_seq);
14092 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014093}
14094
14095static PyObject *
14096unicodeiter_next(unicodeiterobject *it)
14097{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014098 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014099
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 assert(it != NULL);
14101 seq = it->it_seq;
14102 if (seq == NULL)
14103 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014104 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014106 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14107 int kind = PyUnicode_KIND(seq);
14108 void *data = PyUnicode_DATA(seq);
14109 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14110 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014111 if (item != NULL)
14112 ++it->it_index;
14113 return item;
14114 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014115
Benjamin Peterson14339b62009-01-31 16:36:08 +000014116 Py_DECREF(seq);
14117 it->it_seq = NULL;
14118 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014119}
14120
14121static PyObject *
14122unicodeiter_len(unicodeiterobject *it)
14123{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014124 Py_ssize_t len = 0;
14125 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014126 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014128}
14129
14130PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14131
14132static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014133 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014136};
14137
14138PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014139 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14140 "str_iterator", /* tp_name */
14141 sizeof(unicodeiterobject), /* tp_basicsize */
14142 0, /* tp_itemsize */
14143 /* methods */
14144 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14145 0, /* tp_print */
14146 0, /* tp_getattr */
14147 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014148 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014149 0, /* tp_repr */
14150 0, /* tp_as_number */
14151 0, /* tp_as_sequence */
14152 0, /* tp_as_mapping */
14153 0, /* tp_hash */
14154 0, /* tp_call */
14155 0, /* tp_str */
14156 PyObject_GenericGetAttr, /* tp_getattro */
14157 0, /* tp_setattro */
14158 0, /* tp_as_buffer */
14159 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14160 0, /* tp_doc */
14161 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14162 0, /* tp_clear */
14163 0, /* tp_richcompare */
14164 0, /* tp_weaklistoffset */
14165 PyObject_SelfIter, /* tp_iter */
14166 (iternextfunc)unicodeiter_next, /* tp_iternext */
14167 unicodeiter_methods, /* tp_methods */
14168 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014169};
14170
14171static PyObject *
14172unicode_iter(PyObject *seq)
14173{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014174 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014175
Benjamin Peterson14339b62009-01-31 16:36:08 +000014176 if (!PyUnicode_Check(seq)) {
14177 PyErr_BadInternalCall();
14178 return NULL;
14179 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014180 if (PyUnicode_READY(seq) == -1)
14181 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014182 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14183 if (it == NULL)
14184 return NULL;
14185 it->it_index = 0;
14186 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014187 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 _PyObject_GC_TRACK(it);
14189 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014190}
14191
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014192
14193size_t
14194Py_UNICODE_strlen(const Py_UNICODE *u)
14195{
14196 int res = 0;
14197 while(*u++)
14198 res++;
14199 return res;
14200}
14201
14202Py_UNICODE*
14203Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14204{
14205 Py_UNICODE *u = s1;
14206 while ((*u++ = *s2++));
14207 return s1;
14208}
14209
14210Py_UNICODE*
14211Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14212{
14213 Py_UNICODE *u = s1;
14214 while ((*u++ = *s2++))
14215 if (n-- == 0)
14216 break;
14217 return s1;
14218}
14219
14220Py_UNICODE*
14221Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14222{
14223 Py_UNICODE *u1 = s1;
14224 u1 += Py_UNICODE_strlen(u1);
14225 Py_UNICODE_strcpy(u1, s2);
14226 return s1;
14227}
14228
14229int
14230Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14231{
14232 while (*s1 && *s2 && *s1 == *s2)
14233 s1++, s2++;
14234 if (*s1 && *s2)
14235 return (*s1 < *s2) ? -1 : +1;
14236 if (*s1)
14237 return 1;
14238 if (*s2)
14239 return -1;
14240 return 0;
14241}
14242
14243int
14244Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14245{
14246 register Py_UNICODE u1, u2;
14247 for (; n != 0; n--) {
14248 u1 = *s1;
14249 u2 = *s2;
14250 if (u1 != u2)
14251 return (u1 < u2) ? -1 : +1;
14252 if (u1 == '\0')
14253 return 0;
14254 s1++;
14255 s2++;
14256 }
14257 return 0;
14258}
14259
14260Py_UNICODE*
14261Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14262{
14263 const Py_UNICODE *p;
14264 for (p = s; *p; p++)
14265 if (*p == c)
14266 return (Py_UNICODE*)p;
14267 return NULL;
14268}
14269
14270Py_UNICODE*
14271Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14272{
14273 const Py_UNICODE *p;
14274 p = s + Py_UNICODE_strlen(s);
14275 while (p != s) {
14276 p--;
14277 if (*p == c)
14278 return (Py_UNICODE*)p;
14279 }
14280 return NULL;
14281}
Victor Stinner331ea922010-08-10 16:37:20 +000014282
Victor Stinner71133ff2010-09-01 23:43:53 +000014283Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014284PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014285{
Victor Stinner577db2c2011-10-11 22:12:48 +020014286 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014287 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014289 if (!PyUnicode_Check(unicode)) {
14290 PyErr_BadArgument();
14291 return NULL;
14292 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014293 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014294 if (u == NULL)
14295 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014296 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014297 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014298 PyErr_NoMemory();
14299 return NULL;
14300 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014301 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014302 size *= sizeof(Py_UNICODE);
14303 copy = PyMem_Malloc(size);
14304 if (copy == NULL) {
14305 PyErr_NoMemory();
14306 return NULL;
14307 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014308 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014309 return copy;
14310}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014311
Georg Brandl66c221e2010-10-14 07:04:07 +000014312/* A _string module, to export formatter_parser and formatter_field_name_split
14313 to the string.Formatter class implemented in Python. */
14314
14315static PyMethodDef _string_methods[] = {
14316 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14317 METH_O, PyDoc_STR("split the argument as a field name")},
14318 {"formatter_parser", (PyCFunction) formatter_parser,
14319 METH_O, PyDoc_STR("parse the argument as a format string")},
14320 {NULL, NULL}
14321};
14322
14323static struct PyModuleDef _string_module = {
14324 PyModuleDef_HEAD_INIT,
14325 "_string",
14326 PyDoc_STR("string helper module"),
14327 0,
14328 _string_methods,
14329 NULL,
14330 NULL,
14331 NULL,
14332 NULL
14333};
14334
14335PyMODINIT_FUNC
14336PyInit__string(void)
14337{
14338 return PyModule_Create(&_string_module);
14339}
14340
14341
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014342#ifdef __cplusplus
14343}
14344#endif