blob: ab59e215491267c7827391bbc3a2c440383098f4 [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 }
382 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100383 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200384 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100385 assert(maxchar <= 255);
386 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 else
388 assert(maxchar < 128);
389 }
Victor Stinner77faf692011-11-20 18:56:05 +0100390 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200391 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100392 assert(maxchar <= 0xFFFF);
393 }
394 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 assert(maxchar >= 0x10000);
Victor Stinner0d3721d2011-11-22 03:27:53 +0100396 /* FIXME: Issue #13441: on Solaris, localeconv() and strxfrm()
397 return characters outside the range U+0000-U+10FFFF. */
398 /* assert(maxchar <= 0x10FFFF); */
Victor Stinner77faf692011-11-20 18:56:05 +0100399 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400401 return 1;
402}
Victor Stinner910337b2011-10-03 03:20:16 +0200403#endif
404
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100405static PyObject*
406unicode_result_wchar(PyObject *unicode)
407{
408#ifndef Py_DEBUG
409 Py_ssize_t len;
410
411 assert(Py_REFCNT(unicode) == 1);
412
413 len = _PyUnicode_WSTR_LENGTH(unicode);
414 if (len == 0) {
415 Py_INCREF(unicode_empty);
416 Py_DECREF(unicode);
417 return unicode_empty;
418 }
419
420 if (len == 1) {
421 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
422 if (ch < 256) {
423 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
424 Py_DECREF(unicode);
425 return latin1_char;
426 }
427 }
428
429 if (_PyUnicode_Ready(unicode) < 0) {
430 Py_XDECREF(unicode);
431 return NULL;
432 }
433#else
434 /* don't make the result ready in debug mode to ensure that the caller
435 makes the string ready before using it */
436 assert(_PyUnicode_CheckConsistency(unicode, 1));
437#endif
438 return unicode;
439}
440
441static PyObject*
442unicode_result_ready(PyObject *unicode)
443{
444 Py_ssize_t length;
445
446 length = PyUnicode_GET_LENGTH(unicode);
447 if (length == 0) {
448 if (unicode != unicode_empty) {
449 Py_INCREF(unicode_empty);
450 Py_DECREF(unicode);
451 }
452 return unicode_empty;
453 }
454
455 if (length == 1) {
456 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
457 if (ch < 256) {
458 PyObject *latin1_char = unicode_latin1[ch];
459 if (latin1_char != NULL) {
460 if (unicode != latin1_char) {
461 Py_INCREF(latin1_char);
462 Py_DECREF(unicode);
463 }
464 return latin1_char;
465 }
466 else {
467 assert(_PyUnicode_CheckConsistency(unicode, 1));
468 Py_INCREF(unicode);
469 unicode_latin1[ch] = unicode;
470 return unicode;
471 }
472 }
473 }
474
475 assert(_PyUnicode_CheckConsistency(unicode, 1));
476 return unicode;
477}
478
479static PyObject*
480unicode_result(PyObject *unicode)
481{
482 assert(_PyUnicode_CHECK(unicode));
483 if (PyUnicode_IS_READY(unicode))
484 return unicode_result_ready(unicode);
485 else
486 return unicode_result_wchar(unicode);
487}
488
Victor Stinner3a50e702011-10-18 21:21:00 +0200489#ifdef HAVE_MBCS
490static OSVERSIONINFOEX winver;
491#endif
492
Thomas Wouters477c8d52006-05-27 19:21:47 +0000493/* --- Bloom Filters ----------------------------------------------------- */
494
495/* stuff to implement simple "bloom filters" for Unicode characters.
496 to keep things simple, we use a single bitmask, using the least 5
497 bits from each unicode characters as the bit index. */
498
499/* the linebreak mask is set up by Unicode_Init below */
500
Antoine Pitrouf068f942010-01-13 14:19:12 +0000501#if LONG_BIT >= 128
502#define BLOOM_WIDTH 128
503#elif LONG_BIT >= 64
504#define BLOOM_WIDTH 64
505#elif LONG_BIT >= 32
506#define BLOOM_WIDTH 32
507#else
508#error "LONG_BIT is smaller than 32"
509#endif
510
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511#define BLOOM_MASK unsigned long
512
513static BLOOM_MASK bloom_linebreak;
514
Antoine Pitrouf068f942010-01-13 14:19:12 +0000515#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
516#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517
Benjamin Peterson29060642009-01-31 22:14:21 +0000518#define BLOOM_LINEBREAK(ch) \
519 ((ch) < 128U ? ascii_linebreak[(ch)] : \
520 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000521
Alexander Belopolsky40018472011-02-26 01:02:56 +0000522Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200523make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000524{
525 /* calculate simple bloom-style bitmask for a given unicode string */
526
Antoine Pitrouf068f942010-01-13 14:19:12 +0000527 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000528 Py_ssize_t i;
529
530 mask = 0;
531 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200532 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000533
534 return mask;
535}
536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200537#define BLOOM_MEMBER(mask, chr, str) \
538 (BLOOM(mask, chr) \
539 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200541/* Compilation of templated routines */
542
543#include "stringlib/asciilib.h"
544#include "stringlib/fastsearch.h"
545#include "stringlib/partition.h"
546#include "stringlib/split.h"
547#include "stringlib/count.h"
548#include "stringlib/find.h"
549#include "stringlib/find_max_char.h"
550#include "stringlib/localeutil.h"
551#include "stringlib/undef.h"
552
553#include "stringlib/ucs1lib.h"
554#include "stringlib/fastsearch.h"
555#include "stringlib/partition.h"
556#include "stringlib/split.h"
557#include "stringlib/count.h"
558#include "stringlib/find.h"
559#include "stringlib/find_max_char.h"
560#include "stringlib/localeutil.h"
561#include "stringlib/undef.h"
562
563#include "stringlib/ucs2lib.h"
564#include "stringlib/fastsearch.h"
565#include "stringlib/partition.h"
566#include "stringlib/split.h"
567#include "stringlib/count.h"
568#include "stringlib/find.h"
569#include "stringlib/find_max_char.h"
570#include "stringlib/localeutil.h"
571#include "stringlib/undef.h"
572
573#include "stringlib/ucs4lib.h"
574#include "stringlib/fastsearch.h"
575#include "stringlib/partition.h"
576#include "stringlib/split.h"
577#include "stringlib/count.h"
578#include "stringlib/find.h"
579#include "stringlib/find_max_char.h"
580#include "stringlib/localeutil.h"
581#include "stringlib/undef.h"
582
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200583#include "stringlib/unicodedefs.h"
584#include "stringlib/fastsearch.h"
585#include "stringlib/count.h"
586#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100587#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200588
Guido van Rossumd57fd912000-03-10 22:53:23 +0000589/* --- Unicode Object ----------------------------------------------------- */
590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200591static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200592fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200594Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
595 Py_ssize_t size, Py_UCS4 ch,
596 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200597{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200598 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
599
600 switch (kind) {
601 case PyUnicode_1BYTE_KIND:
602 {
603 Py_UCS1 ch1 = (Py_UCS1) ch;
604 if (ch1 == ch)
605 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
606 else
607 return -1;
608 }
609 case PyUnicode_2BYTE_KIND:
610 {
611 Py_UCS2 ch2 = (Py_UCS2) ch;
612 if (ch2 == ch)
613 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
614 else
615 return -1;
616 }
617 case PyUnicode_4BYTE_KIND:
618 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
619 default:
620 assert(0);
621 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200622 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200623}
624
Victor Stinnerfe226c02011-10-03 03:52:20 +0200625static PyObject*
626resize_compact(PyObject *unicode, Py_ssize_t length)
627{
628 Py_ssize_t char_size;
629 Py_ssize_t struct_size;
630 Py_ssize_t new_size;
631 int share_wstr;
632
633 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200634 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200635 if (PyUnicode_IS_COMPACT_ASCII(unicode))
636 struct_size = sizeof(PyASCIIObject);
637 else
638 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200639 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640
641 _Py_DEC_REFTOTAL;
642 _Py_ForgetReference(unicode);
643
644 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
645 PyErr_NoMemory();
646 return NULL;
647 }
648 new_size = (struct_size + (length + 1) * char_size);
649
650 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
651 if (unicode == NULL) {
652 PyObject_Del(unicode);
653 PyErr_NoMemory();
654 return NULL;
655 }
656 _Py_NewReference(unicode);
657 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200658 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200659 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200660 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
661 _PyUnicode_WSTR_LENGTH(unicode) = length;
662 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
664 length, 0);
665 return unicode;
666}
667
Alexander Belopolsky40018472011-02-26 01:02:56 +0000668static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200669resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000670{
Victor Stinner95663112011-10-04 01:03:50 +0200671 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200673 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000674
Victor Stinner95663112011-10-04 01:03:50 +0200675 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676
677 if (PyUnicode_IS_READY(unicode)) {
678 Py_ssize_t char_size;
679 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200680 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 void *data;
682
683 data = _PyUnicode_DATA_ANY(unicode);
684 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200685 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200686 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
687 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200688 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
689 {
690 PyObject_DEL(_PyUnicode_UTF8(unicode));
691 _PyUnicode_UTF8(unicode) = NULL;
692 _PyUnicode_UTF8_LENGTH(unicode) = 0;
693 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694
695 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
696 PyErr_NoMemory();
697 return -1;
698 }
699 new_size = (length + 1) * char_size;
700
701 data = (PyObject *)PyObject_REALLOC(data, new_size);
702 if (data == NULL) {
703 PyErr_NoMemory();
704 return -1;
705 }
706 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200707 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200708 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200709 _PyUnicode_WSTR_LENGTH(unicode) = length;
710 }
711 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200712 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200713 _PyUnicode_UTF8_LENGTH(unicode) = length;
714 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715 _PyUnicode_LENGTH(unicode) = length;
716 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200717 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200718 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200719 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 }
Victor Stinner95663112011-10-04 01:03:50 +0200722 assert(_PyUnicode_WSTR(unicode) != NULL);
723
724 /* check for integer overflow */
725 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
726 PyErr_NoMemory();
727 return -1;
728 }
729 wstr = _PyUnicode_WSTR(unicode);
730 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
731 if (!wstr) {
732 PyErr_NoMemory();
733 return -1;
734 }
735 _PyUnicode_WSTR(unicode) = wstr;
736 _PyUnicode_WSTR(unicode)[length] = 0;
737 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200738 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000739 return 0;
740}
741
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742static PyObject*
743resize_copy(PyObject *unicode, Py_ssize_t length)
744{
745 Py_ssize_t copy_length;
746 if (PyUnicode_IS_COMPACT(unicode)) {
747 PyObject *copy;
748 assert(PyUnicode_IS_READY(unicode));
749
750 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
751 if (copy == NULL)
752 return NULL;
753
754 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200755 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200756 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200757 }
758 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200759 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 assert(_PyUnicode_WSTR(unicode) != NULL);
761 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200762 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200763 if (w == NULL)
764 return NULL;
765 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
766 copy_length = Py_MIN(copy_length, length);
767 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
768 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200769 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200770 }
771}
772
Guido van Rossumd57fd912000-03-10 22:53:23 +0000773/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000774 Ux0000 terminated; some code (e.g. new_identifier)
775 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000776
777 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000778 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000779
780*/
781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200782#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200783static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200784#endif
785
Alexander Belopolsky40018472011-02-26 01:02:56 +0000786static PyUnicodeObject *
787_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000788{
789 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200790 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000791
Thomas Wouters477c8d52006-05-27 19:21:47 +0000792 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000793 if (length == 0 && unicode_empty != NULL) {
794 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200795 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000796 }
797
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000798 /* Ensure we won't overflow the size. */
799 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
800 return (PyUnicodeObject *)PyErr_NoMemory();
801 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200802 if (length < 0) {
803 PyErr_SetString(PyExc_SystemError,
804 "Negative size passed to _PyUnicode_New");
805 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000806 }
807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200808#ifdef Py_DEBUG
809 ++unicode_old_new_calls;
810#endif
811
812 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
813 if (unicode == NULL)
814 return NULL;
815 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
816 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
817 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000818 PyErr_NoMemory();
819 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821
Jeremy Hyltond8082792003-09-16 19:41:39 +0000822 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000823 * the caller fails before initializing str -- unicode_resize()
824 * reads str[0], and the Keep-Alive optimization can keep memory
825 * allocated for str alive across a call to unicode_dealloc(unicode).
826 * We don't want unicode_resize to read uninitialized memory in
827 * that case.
828 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200829 _PyUnicode_WSTR(unicode)[0] = 0;
830 _PyUnicode_WSTR(unicode)[length] = 0;
831 _PyUnicode_WSTR_LENGTH(unicode) = length;
832 _PyUnicode_HASH(unicode) = -1;
833 _PyUnicode_STATE(unicode).interned = 0;
834 _PyUnicode_STATE(unicode).kind = 0;
835 _PyUnicode_STATE(unicode).compact = 0;
836 _PyUnicode_STATE(unicode).ready = 0;
837 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200838 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200839 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200840 _PyUnicode_UTF8(unicode) = NULL;
841 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100842 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000843 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000844
Benjamin Peterson29060642009-01-31 22:14:21 +0000845 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000846 /* XXX UNREF/NEWREF interface should be more symmetrical */
847 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000848 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000849 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000850 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000851}
852
Victor Stinnerf42dc442011-10-02 23:33:16 +0200853static const char*
854unicode_kind_name(PyObject *unicode)
855{
Victor Stinner42dfd712011-10-03 14:41:45 +0200856 /* don't check consistency: unicode_kind_name() is called from
857 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200858 if (!PyUnicode_IS_COMPACT(unicode))
859 {
860 if (!PyUnicode_IS_READY(unicode))
861 return "wstr";
862 switch(PyUnicode_KIND(unicode))
863 {
864 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200865 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200866 return "legacy ascii";
867 else
868 return "legacy latin1";
869 case PyUnicode_2BYTE_KIND:
870 return "legacy UCS2";
871 case PyUnicode_4BYTE_KIND:
872 return "legacy UCS4";
873 default:
874 return "<legacy invalid kind>";
875 }
876 }
877 assert(PyUnicode_IS_READY(unicode));
878 switch(PyUnicode_KIND(unicode))
879 {
880 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200881 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200882 return "ascii";
883 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200884 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200885 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200886 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200887 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200888 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200889 default:
890 return "<invalid compact kind>";
891 }
892}
893
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200895static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896
897/* Functions wrapping macros for use in debugger */
898char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200899 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900}
901
902void *_PyUnicode_compact_data(void *unicode) {
903 return _PyUnicode_COMPACT_DATA(unicode);
904}
905void *_PyUnicode_data(void *unicode){
906 printf("obj %p\n", unicode);
907 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
908 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
909 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
910 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
911 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
912 return PyUnicode_DATA(unicode);
913}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200914
915void
916_PyUnicode_Dump(PyObject *op)
917{
918 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200919 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
920 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
921 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200922
Victor Stinnera849a4b2011-10-03 12:12:11 +0200923 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200924 {
925 if (ascii->state.ascii)
926 data = (ascii + 1);
927 else
928 data = (compact + 1);
929 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200930 else
931 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200932 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
933
Victor Stinnera849a4b2011-10-03 12:12:11 +0200934 if (ascii->wstr == data)
935 printf("shared ");
936 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200937
Victor Stinnera3b334d2011-10-03 13:53:37 +0200938 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200939 printf(" (%zu), ", compact->wstr_length);
940 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
941 printf("shared ");
942 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200943 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200944 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200945}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200946#endif
947
948PyObject *
949PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
950{
951 PyObject *obj;
952 PyCompactUnicodeObject *unicode;
953 void *data;
954 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200955 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 Py_ssize_t char_size;
957 Py_ssize_t struct_size;
958
959 /* Optimization for empty strings */
960 if (size == 0 && unicode_empty != NULL) {
961 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200962 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200963 }
964
965#ifdef Py_DEBUG
966 ++unicode_new_new_calls;
967#endif
968
Victor Stinner9e9d6892011-10-04 01:02:02 +0200969 is_ascii = 0;
970 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200971 struct_size = sizeof(PyCompactUnicodeObject);
972 if (maxchar < 128) {
973 kind_state = PyUnicode_1BYTE_KIND;
974 char_size = 1;
975 is_ascii = 1;
976 struct_size = sizeof(PyASCIIObject);
977 }
978 else if (maxchar < 256) {
979 kind_state = PyUnicode_1BYTE_KIND;
980 char_size = 1;
981 }
982 else if (maxchar < 65536) {
983 kind_state = PyUnicode_2BYTE_KIND;
984 char_size = 2;
985 if (sizeof(wchar_t) == 2)
986 is_sharing = 1;
987 }
988 else {
989 kind_state = PyUnicode_4BYTE_KIND;
990 char_size = 4;
991 if (sizeof(wchar_t) == 4)
992 is_sharing = 1;
993 }
994
995 /* Ensure we won't overflow the size. */
996 if (size < 0) {
997 PyErr_SetString(PyExc_SystemError,
998 "Negative size passed to PyUnicode_New");
999 return NULL;
1000 }
1001 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1002 return PyErr_NoMemory();
1003
1004 /* Duplicated allocation code from _PyObject_New() instead of a call to
1005 * PyObject_New() so we are able to allocate space for the object and
1006 * it's data buffer.
1007 */
1008 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1009 if (obj == NULL)
1010 return PyErr_NoMemory();
1011 obj = PyObject_INIT(obj, &PyUnicode_Type);
1012 if (obj == NULL)
1013 return NULL;
1014
1015 unicode = (PyCompactUnicodeObject *)obj;
1016 if (is_ascii)
1017 data = ((PyASCIIObject*)obj) + 1;
1018 else
1019 data = unicode + 1;
1020 _PyUnicode_LENGTH(unicode) = size;
1021 _PyUnicode_HASH(unicode) = -1;
1022 _PyUnicode_STATE(unicode).interned = 0;
1023 _PyUnicode_STATE(unicode).kind = kind_state;
1024 _PyUnicode_STATE(unicode).compact = 1;
1025 _PyUnicode_STATE(unicode).ready = 1;
1026 _PyUnicode_STATE(unicode).ascii = is_ascii;
1027 if (is_ascii) {
1028 ((char*)data)[size] = 0;
1029 _PyUnicode_WSTR(unicode) = NULL;
1030 }
1031 else if (kind_state == PyUnicode_1BYTE_KIND) {
1032 ((char*)data)[size] = 0;
1033 _PyUnicode_WSTR(unicode) = NULL;
1034 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001036 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001037 }
1038 else {
1039 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001040 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001041 if (kind_state == PyUnicode_2BYTE_KIND)
1042 ((Py_UCS2*)data)[size] = 0;
1043 else /* kind_state == PyUnicode_4BYTE_KIND */
1044 ((Py_UCS4*)data)[size] = 0;
1045 if (is_sharing) {
1046 _PyUnicode_WSTR_LENGTH(unicode) = size;
1047 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1048 }
1049 else {
1050 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1051 _PyUnicode_WSTR(unicode) = NULL;
1052 }
1053 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001054 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001055 return obj;
1056}
1057
1058#if SIZEOF_WCHAR_T == 2
1059/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1060 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001061 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062
1063 This function assumes that unicode can hold one more code point than wstr
1064 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001065static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001066unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001067 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068{
1069 const wchar_t *iter;
1070 Py_UCS4 *ucs4_out;
1071
Victor Stinner910337b2011-10-03 03:20:16 +02001072 assert(unicode != NULL);
1073 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1075 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1076
1077 for (iter = begin; iter < end; ) {
1078 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1079 _PyUnicode_GET_LENGTH(unicode)));
1080 if (*iter >= 0xD800 && *iter <= 0xDBFF
1081 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1082 {
1083 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1084 iter += 2;
1085 }
1086 else {
1087 *ucs4_out++ = *iter;
1088 iter++;
1089 }
1090 }
1091 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1092 _PyUnicode_GET_LENGTH(unicode)));
1093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094}
1095#endif
1096
Victor Stinnercd9950f2011-10-02 00:34:53 +02001097static int
1098_PyUnicode_Dirty(PyObject *unicode)
1099{
Victor Stinner910337b2011-10-03 03:20:16 +02001100 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001101 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001102 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001103 "Cannot modify a string having more than 1 reference");
1104 return -1;
1105 }
1106 _PyUnicode_DIRTY(unicode);
1107 return 0;
1108}
1109
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001110static int
1111_copy_characters(PyObject *to, Py_ssize_t to_start,
1112 PyObject *from, Py_ssize_t from_start,
1113 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001114{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001115 unsigned int from_kind, to_kind;
1116 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001117 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001119 assert(PyUnicode_Check(from));
1120 assert(PyUnicode_Check(to));
1121 assert(PyUnicode_IS_READY(from));
1122 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001124 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1125 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1126 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001127
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001128 if (how_many == 0)
1129 return 0;
1130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001132 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001133 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001134 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001135
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136#ifdef Py_DEBUG
1137 if (!check_maxchar
1138 && (from_kind > to_kind
1139 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001140 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001141 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1142 Py_UCS4 ch;
1143 Py_ssize_t i;
1144 for (i=0; i < how_many; i++) {
1145 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1146 assert(ch <= to_maxchar);
1147 }
1148 }
1149#endif
1150 fast = (from_kind == to_kind);
1151 if (check_maxchar
1152 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1153 {
1154 /* deny latin1 => ascii */
1155 fast = 0;
1156 }
1157
1158 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001159 Py_MEMCPY((char*)to_data + to_kind * to_start,
1160 (char*)from_data + from_kind * from_start,
1161 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001162 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001163 else if (from_kind == PyUnicode_1BYTE_KIND
1164 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001165 {
1166 _PyUnicode_CONVERT_BYTES(
1167 Py_UCS1, Py_UCS2,
1168 PyUnicode_1BYTE_DATA(from) + from_start,
1169 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1170 PyUnicode_2BYTE_DATA(to) + to_start
1171 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001172 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001173 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001174 && to_kind == PyUnicode_4BYTE_KIND)
1175 {
1176 _PyUnicode_CONVERT_BYTES(
1177 Py_UCS1, Py_UCS4,
1178 PyUnicode_1BYTE_DATA(from) + from_start,
1179 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1180 PyUnicode_4BYTE_DATA(to) + to_start
1181 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001182 }
1183 else if (from_kind == PyUnicode_2BYTE_KIND
1184 && to_kind == PyUnicode_4BYTE_KIND)
1185 {
1186 _PyUnicode_CONVERT_BYTES(
1187 Py_UCS2, Py_UCS4,
1188 PyUnicode_2BYTE_DATA(from) + from_start,
1189 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1190 PyUnicode_4BYTE_DATA(to) + to_start
1191 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001192 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001193 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001194 /* check if max_char(from substring) <= max_char(to) */
1195 if (from_kind > to_kind
1196 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001197 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001198 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001199 /* slow path to check for character overflow */
1200 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001201 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001202 Py_ssize_t i;
1203
Victor Stinner56c161a2011-10-06 02:47:11 +02001204#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 for (i=0; i < how_many; i++) {
1206 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001207 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001208 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1209 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001210#else
1211 if (!check_maxchar) {
1212 for (i=0; i < how_many; i++) {
1213 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1214 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1215 }
1216 }
1217 else {
1218 for (i=0; i < how_many; i++) {
1219 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1220 if (ch > to_maxchar)
1221 return 1;
1222 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1223 }
1224 }
1225#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001226 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001227 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001228 assert(0 && "inconsistent state");
1229 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001230 }
1231 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001232 return 0;
1233}
1234
1235static void
1236copy_characters(PyObject *to, Py_ssize_t to_start,
1237 PyObject *from, Py_ssize_t from_start,
1238 Py_ssize_t how_many)
1239{
1240 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1241}
1242
1243Py_ssize_t
1244PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1245 PyObject *from, Py_ssize_t from_start,
1246 Py_ssize_t how_many)
1247{
1248 int err;
1249
1250 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1251 PyErr_BadInternalCall();
1252 return -1;
1253 }
1254
1255 if (PyUnicode_READY(from))
1256 return -1;
1257 if (PyUnicode_READY(to))
1258 return -1;
1259
1260 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1261 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1262 PyErr_Format(PyExc_SystemError,
1263 "Cannot write %zi characters at %zi "
1264 "in a string of %zi characters",
1265 how_many, to_start, PyUnicode_GET_LENGTH(to));
1266 return -1;
1267 }
1268
1269 if (how_many == 0)
1270 return 0;
1271
1272 if (_PyUnicode_Dirty(to))
1273 return -1;
1274
1275 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1276 if (err) {
1277 PyErr_Format(PyExc_SystemError,
1278 "Cannot copy %s characters "
1279 "into a string of %s characters",
1280 unicode_kind_name(from),
1281 unicode_kind_name(to));
1282 return -1;
1283 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001284 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285}
1286
Victor Stinner17222162011-09-28 22:15:37 +02001287/* Find the maximum code point and count the number of surrogate pairs so a
1288 correct string length can be computed before converting a string to UCS4.
1289 This function counts single surrogates as a character and not as a pair.
1290
1291 Return 0 on success, or -1 on error. */
1292static int
1293find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1294 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001295{
1296 const wchar_t *iter;
1297
Victor Stinnerc53be962011-10-02 21:33:54 +02001298 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001299 *num_surrogates = 0;
1300 *maxchar = 0;
1301
1302 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001303 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001305#if SIZEOF_WCHAR_T != 2
1306 if (*maxchar >= 0x10000)
1307 return 0;
1308#endif
1309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001311 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1312 && (iter+1) < end
1313 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 {
1315 Py_UCS4 surrogate_val;
Victor Stinnerca4f2072011-11-22 03:38:40 +01001316 surrogate_val = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ++(*num_surrogates);
1318 if (surrogate_val > *maxchar)
1319 *maxchar = surrogate_val;
1320 iter += 2;
1321 }
1322 else
1323 iter++;
1324#else
1325 iter++;
1326#endif
1327 }
1328 return 0;
1329}
1330
1331#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001332static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333#endif
1334
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001335int
1336_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337{
1338 wchar_t *end;
1339 Py_UCS4 maxchar = 0;
1340 Py_ssize_t num_surrogates;
1341#if SIZEOF_WCHAR_T == 2
1342 Py_ssize_t length_wo_surrogates;
1343#endif
1344
Georg Brandl7597add2011-10-05 16:36:47 +02001345 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001346 strings were created using _PyObject_New() and where no canonical
1347 representation (the str field) has been set yet aka strings
1348 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001349 assert(_PyUnicode_CHECK(unicode));
1350 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001352 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001353 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001354 /* Actually, it should neither be interned nor be anything else: */
1355 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356
1357#ifdef Py_DEBUG
1358 ++unicode_ready_calls;
1359#endif
1360
1361 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001362 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001363 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001365
1366 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001367 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1368 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369 PyErr_NoMemory();
1370 return -1;
1371 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001372 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 _PyUnicode_WSTR(unicode), end,
1374 PyUnicode_1BYTE_DATA(unicode));
1375 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1376 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1377 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1378 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001379 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001380 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001381 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382 }
1383 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001384 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001385 _PyUnicode_UTF8(unicode) = NULL;
1386 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 }
1388 PyObject_FREE(_PyUnicode_WSTR(unicode));
1389 _PyUnicode_WSTR(unicode) = NULL;
1390 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1391 }
1392 /* In this case we might have to convert down from 4-byte native
1393 wchar_t to 2-byte unicode. */
1394 else if (maxchar < 65536) {
1395 assert(num_surrogates == 0 &&
1396 "FindMaxCharAndNumSurrogatePairs() messed up");
1397
Victor Stinner506f5922011-09-28 22:34:18 +02001398#if SIZEOF_WCHAR_T == 2
1399 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001400 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001401 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1402 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1403 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001406#else
1407 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001408 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001409 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001410 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001411 PyErr_NoMemory();
1412 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001413 }
Victor Stinner506f5922011-09-28 22:34:18 +02001414 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1415 _PyUnicode_WSTR(unicode), end,
1416 PyUnicode_2BYTE_DATA(unicode));
1417 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1418 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1419 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001420 _PyUnicode_UTF8(unicode) = NULL;
1421 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001422 PyObject_FREE(_PyUnicode_WSTR(unicode));
1423 _PyUnicode_WSTR(unicode) = NULL;
1424 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1425#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426 }
1427 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1428 else {
1429#if SIZEOF_WCHAR_T == 2
1430 /* in case the native representation is 2-bytes, we need to allocate a
1431 new normalized 4-byte version. */
1432 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001433 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1434 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001435 PyErr_NoMemory();
1436 return -1;
1437 }
1438 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1439 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001440 _PyUnicode_UTF8(unicode) = NULL;
1441 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001442 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1443 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001444 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445 PyObject_FREE(_PyUnicode_WSTR(unicode));
1446 _PyUnicode_WSTR(unicode) = NULL;
1447 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1448#else
1449 assert(num_surrogates == 0);
1450
Victor Stinnerc3c74152011-10-02 20:39:55 +02001451 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001453 _PyUnicode_UTF8(unicode) = NULL;
1454 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001455 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1456#endif
1457 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1458 }
1459 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001460 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001461 return 0;
1462}
1463
Alexander Belopolsky40018472011-02-26 01:02:56 +00001464static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001465unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001466{
Walter Dörwald16807132007-05-25 13:52:07 +00001467 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001468 case SSTATE_NOT_INTERNED:
1469 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001470
Benjamin Peterson29060642009-01-31 22:14:21 +00001471 case SSTATE_INTERNED_MORTAL:
1472 /* revive dead object temporarily for DelItem */
1473 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001474 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001475 Py_FatalError(
1476 "deletion of interned string failed");
1477 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001478
Benjamin Peterson29060642009-01-31 22:14:21 +00001479 case SSTATE_INTERNED_IMMORTAL:
1480 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001481
Benjamin Peterson29060642009-01-31 22:14:21 +00001482 default:
1483 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001484 }
1485
Victor Stinner03490912011-10-03 23:45:12 +02001486 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001488 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001489 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490
1491 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001492 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001493 }
1494 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001495 if (_PyUnicode_DATA_ANY(unicode))
1496 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001497 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001498 }
1499}
1500
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001501#ifdef Py_DEBUG
1502static int
1503unicode_is_singleton(PyObject *unicode)
1504{
1505 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1506 if (unicode == unicode_empty)
1507 return 1;
1508 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1509 {
1510 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1511 if (ch < 256 && unicode_latin1[ch] == unicode)
1512 return 1;
1513 }
1514 return 0;
1515}
1516#endif
1517
Alexander Belopolsky40018472011-02-26 01:02:56 +00001518static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001519unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001520{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001521 if (Py_REFCNT(unicode) != 1)
1522 return 0;
1523 if (PyUnicode_CHECK_INTERNED(unicode))
1524 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001525#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001526 /* singleton refcount is greater than 1 */
1527 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001528#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001529 return 1;
1530}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001531
Victor Stinnerfe226c02011-10-03 03:52:20 +02001532static int
1533unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1534{
1535 PyObject *unicode;
1536 Py_ssize_t old_length;
1537
1538 assert(p_unicode != NULL);
1539 unicode = *p_unicode;
1540
1541 assert(unicode != NULL);
1542 assert(PyUnicode_Check(unicode));
1543 assert(0 <= length);
1544
Victor Stinner910337b2011-10-03 03:20:16 +02001545 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001546 old_length = PyUnicode_WSTR_LENGTH(unicode);
1547 else
1548 old_length = PyUnicode_GET_LENGTH(unicode);
1549 if (old_length == length)
1550 return 0;
1551
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001552 if (length == 0) {
1553 Py_DECREF(*p_unicode);
1554 *p_unicode = unicode_empty;
1555 Py_INCREF(*p_unicode);
1556 return 0;
1557 }
1558
Victor Stinnerfe226c02011-10-03 03:52:20 +02001559 if (!unicode_resizable(unicode)) {
1560 PyObject *copy = resize_copy(unicode, length);
1561 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001562 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001563 Py_DECREF(*p_unicode);
1564 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001565 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001566 }
1567
Victor Stinnerfe226c02011-10-03 03:52:20 +02001568 if (PyUnicode_IS_COMPACT(unicode)) {
1569 *p_unicode = resize_compact(unicode, length);
1570 if (*p_unicode == NULL)
1571 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001572 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001573 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001574 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001575 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001576}
1577
Alexander Belopolsky40018472011-02-26 01:02:56 +00001578int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001579PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001580{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 PyObject *unicode;
1582 if (p_unicode == NULL) {
1583 PyErr_BadInternalCall();
1584 return -1;
1585 }
1586 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001587 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001588 {
1589 PyErr_BadInternalCall();
1590 return -1;
1591 }
1592 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001593}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001594
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001595static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001596unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001597{
1598 PyObject *result;
1599 assert(PyUnicode_IS_READY(*p_unicode));
1600 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1601 return 0;
1602 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1603 maxchar);
1604 if (result == NULL)
1605 return -1;
1606 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1607 PyUnicode_GET_LENGTH(*p_unicode));
1608 Py_DECREF(*p_unicode);
1609 *p_unicode = result;
1610 return 0;
1611}
1612
1613static int
1614unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1615 Py_UCS4 ch)
1616{
1617 if (unicode_widen(p_unicode, ch) < 0)
1618 return -1;
1619 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1620 PyUnicode_DATA(*p_unicode),
1621 (*pos)++, ch);
1622 return 0;
1623}
1624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001625static PyObject*
1626get_latin1_char(unsigned char ch)
1627{
Victor Stinnera464fc12011-10-02 20:39:30 +02001628 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001630 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631 if (!unicode)
1632 return NULL;
1633 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001634 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 unicode_latin1[ch] = unicode;
1636 }
1637 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001638 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639}
1640
Alexander Belopolsky40018472011-02-26 01:02:56 +00001641PyObject *
1642PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001643{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001644 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001645 Py_UCS4 maxchar = 0;
1646 Py_ssize_t num_surrogates;
1647
1648 if (u == NULL)
1649 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001650
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001651 /* If the Unicode data is known at construction time, we can apply
1652 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001654 /* Optimization for empty strings */
1655 if (size == 0 && unicode_empty != NULL) {
1656 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001657 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001658 }
Tim Petersced69f82003-09-16 20:30:58 +00001659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 /* Single character Unicode objects in the Latin-1 range are
1661 shared when using this constructor */
1662 if (size == 1 && *u < 256)
1663 return get_latin1_char((unsigned char)*u);
1664
1665 /* If not empty and not single character, copy the Unicode data
1666 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001667 if (find_maxchar_surrogates(u, u + size,
1668 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 return NULL;
1670
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001671 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001673 if (!unicode)
1674 return NULL;
1675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001676 switch (PyUnicode_KIND(unicode)) {
1677 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001678 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001679 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1680 break;
1681 case PyUnicode_2BYTE_KIND:
1682#if Py_UNICODE_SIZE == 2
1683 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1684#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001685 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1687#endif
1688 break;
1689 case PyUnicode_4BYTE_KIND:
1690#if SIZEOF_WCHAR_T == 2
1691 /* This is the only case which has to process surrogates, thus
1692 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001693 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001694#else
1695 assert(num_surrogates == 0);
1696 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1697#endif
1698 break;
1699 default:
1700 assert(0 && "Impossible state");
1701 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001702
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001703 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001704}
1705
Alexander Belopolsky40018472011-02-26 01:02:56 +00001706PyObject *
1707PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001708{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001709 if (size < 0) {
1710 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001711 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001712 return NULL;
1713 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001714
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001715 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001716 some optimizations which share commonly used objects.
1717 Also, this means the input must be UTF-8, so fall back to the
1718 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001719 if (u != NULL) {
1720
Benjamin Peterson29060642009-01-31 22:14:21 +00001721 /* Optimization for empty strings */
1722 if (size == 0 && unicode_empty != NULL) {
1723 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001724 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001725 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001726
1727 /* Single characters are shared when using this constructor.
1728 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001729 if (size == 1 && (unsigned char)*u < 128)
1730 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001731
1732 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001733 }
1734
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001735 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001736}
1737
Alexander Belopolsky40018472011-02-26 01:02:56 +00001738PyObject *
1739PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001740{
1741 size_t size = strlen(u);
1742 if (size > PY_SSIZE_T_MAX) {
1743 PyErr_SetString(PyExc_OverflowError, "input too long");
1744 return NULL;
1745 }
1746
1747 return PyUnicode_FromStringAndSize(u, size);
1748}
1749
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001750PyObject *
1751_PyUnicode_FromId(_Py_Identifier *id)
1752{
1753 if (!id->object) {
1754 id->object = PyUnicode_FromString(id->string);
1755 if (!id->object)
1756 return NULL;
1757 PyUnicode_InternInPlace(&id->object);
1758 assert(!id->next);
1759 id->next = static_strings;
1760 static_strings = id;
1761 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001762 return id->object;
1763}
1764
1765void
1766_PyUnicode_ClearStaticStrings()
1767{
1768 _Py_Identifier *i;
1769 for (i = static_strings; i; i = i->next) {
1770 Py_DECREF(i->object);
1771 i->object = NULL;
1772 i->next = NULL;
1773 }
1774}
1775
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001776/* Internal function, don't check maximum character */
1777
Victor Stinnere57b1c02011-09-28 22:20:48 +02001778static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001779unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001780{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001781 PyObject *res;
1782#ifdef Py_DEBUG
1783 const unsigned char *p;
1784 const unsigned char *end = s + size;
1785 for (p=s; p < end; p++) {
1786 assert(*p < 128);
1787 }
1788#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001789 if (size == 1)
1790 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001791 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001792 if (!res)
1793 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001794 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001795 return res;
1796}
1797
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001798static Py_UCS4
1799kind_maxchar_limit(unsigned int kind)
1800{
1801 switch(kind) {
1802 case PyUnicode_1BYTE_KIND:
1803 return 0x80;
1804 case PyUnicode_2BYTE_KIND:
1805 return 0x100;
1806 case PyUnicode_4BYTE_KIND:
1807 return 0x10000;
1808 default:
1809 assert(0 && "invalid kind");
1810 return 0x10ffff;
1811 }
1812}
1813
Victor Stinner702c7342011-10-05 13:50:52 +02001814static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001815_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001816{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001817 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001818 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001819
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001820 if (size == 0) {
1821 Py_INCREF(unicode_empty);
1822 return unicode_empty;
1823 }
1824 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001825 if (size == 1)
1826 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001827
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001828 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001829 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 if (!res)
1831 return NULL;
1832 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001833 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001834 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001835}
1836
Victor Stinnere57b1c02011-09-28 22:20:48 +02001837static PyObject*
1838_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001839{
1840 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001841 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001842
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001843 if (size == 0) {
1844 Py_INCREF(unicode_empty);
1845 return unicode_empty;
1846 }
1847 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001848 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001849 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001850
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001851 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001852 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001853 if (!res)
1854 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001855 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001857 else {
1858 _PyUnicode_CONVERT_BYTES(
1859 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1860 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001861 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001862 return res;
1863}
1864
Victor Stinnere57b1c02011-09-28 22:20:48 +02001865static PyObject*
1866_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867{
1868 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001869 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001870
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001871 if (size == 0) {
1872 Py_INCREF(unicode_empty);
1873 return unicode_empty;
1874 }
1875 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001876 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001877 return get_latin1_char((unsigned char)u[0]);
1878
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001879 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001880 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001881 if (!res)
1882 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001883 if (max_char < 256)
1884 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1885 PyUnicode_1BYTE_DATA(res));
1886 else if (max_char < 0x10000)
1887 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1888 PyUnicode_2BYTE_DATA(res));
1889 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001890 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001891 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001892 return res;
1893}
1894
1895PyObject*
1896PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1897{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001898 if (size < 0) {
1899 PyErr_SetString(PyExc_ValueError, "size must be positive");
1900 return NULL;
1901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001902 switch(kind) {
1903 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001904 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001905 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001906 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001908 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001909 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001910 PyErr_SetString(PyExc_SystemError, "invalid kind");
1911 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001913}
1914
Victor Stinner25a4b292011-10-06 12:31:55 +02001915/* Ensure that a string uses the most efficient storage, if it is not the
1916 case: create a new string with of the right kind. Write NULL into *p_unicode
1917 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001918static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001919unicode_adjust_maxchar(PyObject **p_unicode)
1920{
1921 PyObject *unicode, *copy;
1922 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001923 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001924 unsigned int kind;
1925
1926 assert(p_unicode != NULL);
1927 unicode = *p_unicode;
1928 assert(PyUnicode_IS_READY(unicode));
1929 if (PyUnicode_IS_ASCII(unicode))
1930 return;
1931
1932 len = PyUnicode_GET_LENGTH(unicode);
1933 kind = PyUnicode_KIND(unicode);
1934 if (kind == PyUnicode_1BYTE_KIND) {
1935 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001936 max_char = ucs1lib_find_max_char(u, u + len);
1937 if (max_char >= 128)
1938 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001939 }
1940 else if (kind == PyUnicode_2BYTE_KIND) {
1941 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001942 max_char = ucs2lib_find_max_char(u, u + len);
1943 if (max_char >= 256)
1944 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001945 }
1946 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001947 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001948 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001949 max_char = ucs4lib_find_max_char(u, u + len);
1950 if (max_char >= 0x10000)
1951 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001952 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001953 copy = PyUnicode_New(len, max_char);
1954 copy_characters(copy, 0, unicode, 0, len);
1955 Py_DECREF(unicode);
1956 *p_unicode = copy;
1957}
1958
Victor Stinner034f6cf2011-09-30 02:26:44 +02001959PyObject*
1960PyUnicode_Copy(PyObject *unicode)
1961{
Victor Stinner87af4f22011-11-21 23:03:47 +01001962 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001963 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001964
Victor Stinner034f6cf2011-09-30 02:26:44 +02001965 if (!PyUnicode_Check(unicode)) {
1966 PyErr_BadInternalCall();
1967 return NULL;
1968 }
1969 if (PyUnicode_READY(unicode))
1970 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001971
Victor Stinner87af4f22011-11-21 23:03:47 +01001972 length = PyUnicode_GET_LENGTH(unicode);
1973 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001974 if (!copy)
1975 return NULL;
1976 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1977
Victor Stinner87af4f22011-11-21 23:03:47 +01001978 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1979 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001980 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001981 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001982}
1983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984
Victor Stinnerbc603d12011-10-02 01:00:40 +02001985/* Widen Unicode objects to larger buffers. Don't write terminating null
1986 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987
1988void*
1989_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1990{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001991 Py_ssize_t len;
1992 void *result;
1993 unsigned int skind;
1994
1995 if (PyUnicode_READY(s))
1996 return NULL;
1997
1998 len = PyUnicode_GET_LENGTH(s);
1999 skind = PyUnicode_KIND(s);
2000 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002001 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 return NULL;
2003 }
2004 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002005 case PyUnicode_2BYTE_KIND:
2006 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2007 if (!result)
2008 return PyErr_NoMemory();
2009 assert(skind == PyUnicode_1BYTE_KIND);
2010 _PyUnicode_CONVERT_BYTES(
2011 Py_UCS1, Py_UCS2,
2012 PyUnicode_1BYTE_DATA(s),
2013 PyUnicode_1BYTE_DATA(s) + len,
2014 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002015 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002016 case PyUnicode_4BYTE_KIND:
2017 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2018 if (!result)
2019 return PyErr_NoMemory();
2020 if (skind == PyUnicode_2BYTE_KIND) {
2021 _PyUnicode_CONVERT_BYTES(
2022 Py_UCS2, Py_UCS4,
2023 PyUnicode_2BYTE_DATA(s),
2024 PyUnicode_2BYTE_DATA(s) + len,
2025 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002027 else {
2028 assert(skind == PyUnicode_1BYTE_KIND);
2029 _PyUnicode_CONVERT_BYTES(
2030 Py_UCS1, Py_UCS4,
2031 PyUnicode_1BYTE_DATA(s),
2032 PyUnicode_1BYTE_DATA(s) + len,
2033 result);
2034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002036 default:
2037 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 }
Victor Stinner01698042011-10-04 00:04:26 +02002039 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 return NULL;
2041}
2042
2043static Py_UCS4*
2044as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2045 int copy_null)
2046{
2047 int kind;
2048 void *data;
2049 Py_ssize_t len, targetlen;
2050 if (PyUnicode_READY(string) == -1)
2051 return NULL;
2052 kind = PyUnicode_KIND(string);
2053 data = PyUnicode_DATA(string);
2054 len = PyUnicode_GET_LENGTH(string);
2055 targetlen = len;
2056 if (copy_null)
2057 targetlen++;
2058 if (!target) {
2059 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2060 PyErr_NoMemory();
2061 return NULL;
2062 }
2063 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2064 if (!target) {
2065 PyErr_NoMemory();
2066 return NULL;
2067 }
2068 }
2069 else {
2070 if (targetsize < targetlen) {
2071 PyErr_Format(PyExc_SystemError,
2072 "string is longer than the buffer");
2073 if (copy_null && 0 < targetsize)
2074 target[0] = 0;
2075 return NULL;
2076 }
2077 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002078 if (kind == PyUnicode_1BYTE_KIND) {
2079 Py_UCS1 *start = (Py_UCS1 *) data;
2080 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002082 else if (kind == PyUnicode_2BYTE_KIND) {
2083 Py_UCS2 *start = (Py_UCS2 *) data;
2084 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2085 }
2086 else {
2087 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002088 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090 if (copy_null)
2091 target[len] = 0;
2092 return target;
2093}
2094
2095Py_UCS4*
2096PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2097 int copy_null)
2098{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002099 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002100 PyErr_BadInternalCall();
2101 return NULL;
2102 }
2103 return as_ucs4(string, target, targetsize, copy_null);
2104}
2105
2106Py_UCS4*
2107PyUnicode_AsUCS4Copy(PyObject *string)
2108{
2109 return as_ucs4(string, NULL, 0, 1);
2110}
2111
2112#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002113
Alexander Belopolsky40018472011-02-26 01:02:56 +00002114PyObject *
2115PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002116{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002117 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002118 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002119 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002120 PyErr_BadInternalCall();
2121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002122 }
2123
Martin v. Löwis790465f2008-04-05 20:41:37 +00002124 if (size == -1) {
2125 size = wcslen(w);
2126 }
2127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002128 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002129}
2130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002132
Walter Dörwald346737f2007-05-31 10:44:43 +00002133static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002134makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2135 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002136{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002137 *fmt++ = '%';
2138 if (width) {
2139 if (zeropad)
2140 *fmt++ = '0';
2141 fmt += sprintf(fmt, "%d", width);
2142 }
2143 if (precision)
2144 fmt += sprintf(fmt, ".%d", precision);
2145 if (longflag)
2146 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002147 else if (longlongflag) {
2148 /* longlongflag should only ever be nonzero on machines with
2149 HAVE_LONG_LONG defined */
2150#ifdef HAVE_LONG_LONG
2151 char *f = PY_FORMAT_LONG_LONG;
2152 while (*f)
2153 *fmt++ = *f++;
2154#else
2155 /* we shouldn't ever get here */
2156 assert(0);
2157 *fmt++ = 'l';
2158#endif
2159 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002160 else if (size_tflag) {
2161 char *f = PY_FORMAT_SIZE_T;
2162 while (*f)
2163 *fmt++ = *f++;
2164 }
2165 *fmt++ = c;
2166 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002167}
2168
Victor Stinner96865452011-03-01 23:44:09 +00002169/* helper for PyUnicode_FromFormatV() */
2170
2171static const char*
2172parse_format_flags(const char *f,
2173 int *p_width, int *p_precision,
2174 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2175{
2176 int width, precision, longflag, longlongflag, size_tflag;
2177
2178 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2179 f++;
2180 width = 0;
2181 while (Py_ISDIGIT((unsigned)*f))
2182 width = (width*10) + *f++ - '0';
2183 precision = 0;
2184 if (*f == '.') {
2185 f++;
2186 while (Py_ISDIGIT((unsigned)*f))
2187 precision = (precision*10) + *f++ - '0';
2188 if (*f == '%') {
2189 /* "%.3%s" => f points to "3" */
2190 f--;
2191 }
2192 }
2193 if (*f == '\0') {
2194 /* bogus format "%.1" => go backward, f points to "1" */
2195 f--;
2196 }
2197 if (p_width != NULL)
2198 *p_width = width;
2199 if (p_precision != NULL)
2200 *p_precision = precision;
2201
2202 /* Handle %ld, %lu, %lld and %llu. */
2203 longflag = 0;
2204 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002205 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002206
2207 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002208 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002209 longflag = 1;
2210 ++f;
2211 }
2212#ifdef HAVE_LONG_LONG
2213 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002214 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002215 longlongflag = 1;
2216 f += 2;
2217 }
2218#endif
2219 }
2220 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002221 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002222 size_tflag = 1;
2223 ++f;
2224 }
2225 if (p_longflag != NULL)
2226 *p_longflag = longflag;
2227 if (p_longlongflag != NULL)
2228 *p_longlongflag = longlongflag;
2229 if (p_size_tflag != NULL)
2230 *p_size_tflag = size_tflag;
2231 return f;
2232}
2233
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002234/* maximum number of characters required for output of %ld. 21 characters
2235 allows for 64-bit integers (in decimal) and an optional sign. */
2236#define MAX_LONG_CHARS 21
2237/* maximum number of characters required for output of %lld.
2238 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2239 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2240#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2241
Walter Dörwaldd2034312007-05-18 16:29:38 +00002242PyObject *
2243PyUnicode_FromFormatV(const char *format, va_list vargs)
2244{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002245 va_list count;
2246 Py_ssize_t callcount = 0;
2247 PyObject **callresults = NULL;
2248 PyObject **callresult = NULL;
2249 Py_ssize_t n = 0;
2250 int width = 0;
2251 int precision = 0;
2252 int zeropad;
2253 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002254 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002255 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002256 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2258 Py_UCS4 argmaxchar;
2259 Py_ssize_t numbersize = 0;
2260 char *numberresults = NULL;
2261 char *numberresult = NULL;
2262 Py_ssize_t i;
2263 int kind;
2264 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002265
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002266 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002267 /* step 1: count the number of %S/%R/%A/%s format specifications
2268 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2269 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002270 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002271 * also estimate a upper bound for all the number formats in the string,
2272 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002274 for (f = format; *f; f++) {
2275 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002276 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2278 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2279 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2280 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002282 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002283#ifdef HAVE_LONG_LONG
2284 if (longlongflag) {
2285 if (width < MAX_LONG_LONG_CHARS)
2286 width = MAX_LONG_LONG_CHARS;
2287 }
2288 else
2289#endif
2290 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2291 including sign. Decimal takes the most space. This
2292 isn't enough for octal. If a width is specified we
2293 need more (which we allocate later). */
2294 if (width < MAX_LONG_CHARS)
2295 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002296
2297 /* account for the size + '\0' to separate numbers
2298 inside of the numberresults buffer */
2299 numbersize += (width + 1);
2300 }
2301 }
2302 else if ((unsigned char)*f > 127) {
2303 PyErr_Format(PyExc_ValueError,
2304 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2305 "string, got a non-ASCII byte: 0x%02x",
2306 (unsigned char)*f);
2307 return NULL;
2308 }
2309 }
2310 /* step 2: allocate memory for the results of
2311 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2312 if (callcount) {
2313 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2314 if (!callresults) {
2315 PyErr_NoMemory();
2316 return NULL;
2317 }
2318 callresult = callresults;
2319 }
2320 /* step 2.5: allocate memory for the results of formating numbers */
2321 if (numbersize) {
2322 numberresults = PyObject_Malloc(numbersize);
2323 if (!numberresults) {
2324 PyErr_NoMemory();
2325 goto fail;
2326 }
2327 numberresult = numberresults;
2328 }
2329
2330 /* step 3: format numbers and figure out how large a buffer we need */
2331 for (f = format; *f; f++) {
2332 if (*f == '%') {
2333 const char* p;
2334 int longflag;
2335 int longlongflag;
2336 int size_tflag;
2337 int numprinted;
2338
2339 p = f;
2340 zeropad = (f[1] == '0');
2341 f = parse_format_flags(f, &width, &precision,
2342 &longflag, &longlongflag, &size_tflag);
2343 switch (*f) {
2344 case 'c':
2345 {
2346 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002347 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002348 n++;
2349 break;
2350 }
2351 case '%':
2352 n++;
2353 break;
2354 case 'i':
2355 case 'd':
2356 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2357 width, precision, *f);
2358 if (longflag)
2359 numprinted = sprintf(numberresult, fmt,
2360 va_arg(count, long));
2361#ifdef HAVE_LONG_LONG
2362 else if (longlongflag)
2363 numprinted = sprintf(numberresult, fmt,
2364 va_arg(count, PY_LONG_LONG));
2365#endif
2366 else if (size_tflag)
2367 numprinted = sprintf(numberresult, fmt,
2368 va_arg(count, Py_ssize_t));
2369 else
2370 numprinted = sprintf(numberresult, fmt,
2371 va_arg(count, int));
2372 n += numprinted;
2373 /* advance by +1 to skip over the '\0' */
2374 numberresult += (numprinted + 1);
2375 assert(*(numberresult - 1) == '\0');
2376 assert(*(numberresult - 2) != '\0');
2377 assert(numprinted >= 0);
2378 assert(numberresult <= numberresults + numbersize);
2379 break;
2380 case 'u':
2381 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2382 width, precision, 'u');
2383 if (longflag)
2384 numprinted = sprintf(numberresult, fmt,
2385 va_arg(count, unsigned long));
2386#ifdef HAVE_LONG_LONG
2387 else if (longlongflag)
2388 numprinted = sprintf(numberresult, fmt,
2389 va_arg(count, unsigned PY_LONG_LONG));
2390#endif
2391 else if (size_tflag)
2392 numprinted = sprintf(numberresult, fmt,
2393 va_arg(count, size_t));
2394 else
2395 numprinted = sprintf(numberresult, fmt,
2396 va_arg(count, unsigned int));
2397 n += numprinted;
2398 numberresult += (numprinted + 1);
2399 assert(*(numberresult - 1) == '\0');
2400 assert(*(numberresult - 2) != '\0');
2401 assert(numprinted >= 0);
2402 assert(numberresult <= numberresults + numbersize);
2403 break;
2404 case 'x':
2405 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2406 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2407 n += numprinted;
2408 numberresult += (numprinted + 1);
2409 assert(*(numberresult - 1) == '\0');
2410 assert(*(numberresult - 2) != '\0');
2411 assert(numprinted >= 0);
2412 assert(numberresult <= numberresults + numbersize);
2413 break;
2414 case 'p':
2415 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2416 /* %p is ill-defined: ensure leading 0x. */
2417 if (numberresult[1] == 'X')
2418 numberresult[1] = 'x';
2419 else if (numberresult[1] != 'x') {
2420 memmove(numberresult + 2, numberresult,
2421 strlen(numberresult) + 1);
2422 numberresult[0] = '0';
2423 numberresult[1] = 'x';
2424 numprinted += 2;
2425 }
2426 n += numprinted;
2427 numberresult += (numprinted + 1);
2428 assert(*(numberresult - 1) == '\0');
2429 assert(*(numberresult - 2) != '\0');
2430 assert(numprinted >= 0);
2431 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002432 break;
2433 case 's':
2434 {
2435 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002436 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002437 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2438 if (!str)
2439 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002440 /* since PyUnicode_DecodeUTF8 returns already flexible
2441 unicode objects, there is no need to call ready on them */
2442 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002443 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002445 /* Remember the str and switch to the next slot */
2446 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 break;
2448 }
2449 case 'U':
2450 {
2451 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002452 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 if (PyUnicode_READY(obj) == -1)
2454 goto fail;
2455 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002456 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002458 break;
2459 }
2460 case 'V':
2461 {
2462 PyObject *obj = va_arg(count, PyObject *);
2463 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002464 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002465 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002466 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002467 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 if (PyUnicode_READY(obj) == -1)
2469 goto fail;
2470 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002471 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002473 *callresult++ = NULL;
2474 }
2475 else {
2476 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2477 if (!str_obj)
2478 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002479 if (PyUnicode_READY(str_obj)) {
2480 Py_DECREF(str_obj);
2481 goto fail;
2482 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002484 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002486 *callresult++ = str_obj;
2487 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002488 break;
2489 }
2490 case 'S':
2491 {
2492 PyObject *obj = va_arg(count, PyObject *);
2493 PyObject *str;
2494 assert(obj);
2495 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002497 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002499 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002501 /* Remember the str and switch to the next slot */
2502 *callresult++ = str;
2503 break;
2504 }
2505 case 'R':
2506 {
2507 PyObject *obj = va_arg(count, PyObject *);
2508 PyObject *repr;
2509 assert(obj);
2510 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002512 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002513 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002514 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002516 /* Remember the repr and switch to the next slot */
2517 *callresult++ = repr;
2518 break;
2519 }
2520 case 'A':
2521 {
2522 PyObject *obj = va_arg(count, PyObject *);
2523 PyObject *ascii;
2524 assert(obj);
2525 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002527 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002529 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 /* Remember the repr and switch to the next slot */
2532 *callresult++ = ascii;
2533 break;
2534 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 default:
2536 /* if we stumble upon an unknown
2537 formatting code, copy the rest of
2538 the format string to the output
2539 string. (we cannot just skip the
2540 code, since there's no way to know
2541 what's in the argument list) */
2542 n += strlen(p);
2543 goto expand;
2544 }
2545 } else
2546 n++;
2547 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002548 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002550 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002551 we don't have to resize the string.
2552 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002553 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002554 if (!string)
2555 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002556 kind = PyUnicode_KIND(string);
2557 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002558 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002562 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002563 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002564
2565 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2567 /* checking for == because the last argument could be a empty
2568 string, which causes i to point to end, the assert at the end of
2569 the loop */
2570 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002571
Benjamin Peterson14339b62009-01-31 16:36:08 +00002572 switch (*f) {
2573 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002574 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002575 const int ordinal = va_arg(vargs, int);
2576 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002577 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002578 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002579 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002581 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002582 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 case 'p':
2584 /* unused, since we already have the result */
2585 if (*f == 'p')
2586 (void) va_arg(vargs, void *);
2587 else
2588 (void) va_arg(vargs, int);
2589 /* extract the result from numberresults and append. */
2590 for (; *numberresult; ++i, ++numberresult)
2591 PyUnicode_WRITE(kind, data, i, *numberresult);
2592 /* skip over the separating '\0' */
2593 assert(*numberresult == '\0');
2594 numberresult++;
2595 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002596 break;
2597 case 's':
2598 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002599 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002601 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002602 size = PyUnicode_GET_LENGTH(*callresult);
2603 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002604 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002606 /* We're done with the unicode()/repr() => forget it */
2607 Py_DECREF(*callresult);
2608 /* switch to next unicode()/repr() result */
2609 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002610 break;
2611 }
2612 case 'U':
2613 {
2614 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002615 Py_ssize_t size;
2616 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2617 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002618 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 break;
2621 }
2622 case 'V':
2623 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002624 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002626 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 size = PyUnicode_GET_LENGTH(obj);
2629 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002630 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002631 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 size = PyUnicode_GET_LENGTH(*callresult);
2634 assert(PyUnicode_KIND(*callresult) <=
2635 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002636 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002638 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002639 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002640 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 break;
2642 }
2643 case 'S':
2644 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002645 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002646 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002647 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 /* unused, since we already have the result */
2649 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002650 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002651 copy_characters(string, i, *callresult, 0, size);
2652 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 /* We're done with the unicode()/repr() => forget it */
2654 Py_DECREF(*callresult);
2655 /* switch to next unicode()/repr() result */
2656 ++callresult;
2657 break;
2658 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002659 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002660 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002661 break;
2662 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 for (; *p; ++p, ++i)
2664 PyUnicode_WRITE(kind, data, i, *p);
2665 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002666 goto end;
2667 }
Victor Stinner1205f272010-09-11 00:54:47 +00002668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002669 else {
2670 assert(i < PyUnicode_GET_LENGTH(string));
2671 PyUnicode_WRITE(kind, data, i++, *f);
2672 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002673 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002675
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002677 if (callresults)
2678 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002679 if (numberresults)
2680 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002681 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002682 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002683 if (callresults) {
2684 PyObject **callresult2 = callresults;
2685 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002686 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002687 ++callresult2;
2688 }
2689 PyObject_Free(callresults);
2690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002691 if (numberresults)
2692 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002693 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002694}
2695
Walter Dörwaldd2034312007-05-18 16:29:38 +00002696PyObject *
2697PyUnicode_FromFormat(const char *format, ...)
2698{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 PyObject* ret;
2700 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002701
2702#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002703 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002704#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002705 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002706#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 ret = PyUnicode_FromFormatV(format, vargs);
2708 va_end(vargs);
2709 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002710}
2711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002712#ifdef HAVE_WCHAR_H
2713
Victor Stinner5593d8a2010-10-02 11:11:27 +00002714/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2715 convert a Unicode object to a wide character string.
2716
Victor Stinnerd88d9832011-09-06 02:00:05 +02002717 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002718 character) required to convert the unicode object. Ignore size argument.
2719
Victor Stinnerd88d9832011-09-06 02:00:05 +02002720 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002721 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002722 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002723static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002724unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002725 wchar_t *w,
2726 Py_ssize_t size)
2727{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002728 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002729 const wchar_t *wstr;
2730
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002731 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (wstr == NULL)
2733 return -1;
2734
Victor Stinner5593d8a2010-10-02 11:11:27 +00002735 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002736 if (size > res)
2737 size = res + 1;
2738 else
2739 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002741 return res;
2742 }
2743 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002745}
2746
2747Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002748PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002749 wchar_t *w,
2750 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002751{
2752 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002753 PyErr_BadInternalCall();
2754 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002755 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002756 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002757}
2758
Victor Stinner137c34c2010-09-29 10:25:54 +00002759wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002760PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002761 Py_ssize_t *size)
2762{
2763 wchar_t* buffer;
2764 Py_ssize_t buflen;
2765
2766 if (unicode == NULL) {
2767 PyErr_BadInternalCall();
2768 return NULL;
2769 }
2770
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002771 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 if (buflen == -1)
2773 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002774 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002775 PyErr_NoMemory();
2776 return NULL;
2777 }
2778
Victor Stinner137c34c2010-09-29 10:25:54 +00002779 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2780 if (buffer == NULL) {
2781 PyErr_NoMemory();
2782 return NULL;
2783 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002784 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002785 if (buflen == -1)
2786 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002787 if (size != NULL)
2788 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002789 return buffer;
2790}
2791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002793
Alexander Belopolsky40018472011-02-26 01:02:56 +00002794PyObject *
2795PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002797 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002798 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002799 PyErr_SetString(PyExc_ValueError,
2800 "chr() arg not in range(0x110000)");
2801 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002802 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002804 if (ordinal < 256)
2805 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002807 v = PyUnicode_New(1, ordinal);
2808 if (v == NULL)
2809 return NULL;
2810 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002811 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002813}
2814
Alexander Belopolsky40018472011-02-26 01:02:56 +00002815PyObject *
2816PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002817{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002818 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002819 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002820 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002821 if (PyUnicode_READY(obj))
2822 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002823 Py_INCREF(obj);
2824 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002825 }
2826 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002827 /* For a Unicode subtype that's not a Unicode object,
2828 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002829 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002830 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002831 PyErr_Format(PyExc_TypeError,
2832 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002833 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002834 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002835}
2836
Alexander Belopolsky40018472011-02-26 01:02:56 +00002837PyObject *
2838PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002839 const char *encoding,
2840 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002841{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002842 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002843 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002844
Guido van Rossumd57fd912000-03-10 22:53:23 +00002845 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002846 PyErr_BadInternalCall();
2847 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002848 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002849
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002850 /* Decoding bytes objects is the most common case and should be fast */
2851 if (PyBytes_Check(obj)) {
2852 if (PyBytes_GET_SIZE(obj) == 0) {
2853 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002854 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002855 }
2856 else {
2857 v = PyUnicode_Decode(
2858 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2859 encoding, errors);
2860 }
2861 return v;
2862 }
2863
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002864 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002865 PyErr_SetString(PyExc_TypeError,
2866 "decoding str is not supported");
2867 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002868 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002869
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002870 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2871 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2872 PyErr_Format(PyExc_TypeError,
2873 "coercing to str: need bytes, bytearray "
2874 "or buffer-like object, %.80s found",
2875 Py_TYPE(obj)->tp_name);
2876 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002877 }
Tim Petersced69f82003-09-16 20:30:58 +00002878
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002879 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002880 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002881 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002882 }
Tim Petersced69f82003-09-16 20:30:58 +00002883 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002884 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002885
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002886 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002887 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002888}
2889
Victor Stinner600d3be2010-06-10 12:00:55 +00002890/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002891 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2892 1 on success. */
2893static int
2894normalize_encoding(const char *encoding,
2895 char *lower,
2896 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002897{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002898 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002899 char *l;
2900 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002901
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002902 if (encoding == NULL) {
2903 strcpy(lower, "utf-8");
2904 return 1;
2905 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002906 e = encoding;
2907 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002908 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002909 while (*e) {
2910 if (l == l_end)
2911 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002912 if (Py_ISUPPER(*e)) {
2913 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002914 }
2915 else if (*e == '_') {
2916 *l++ = '-';
2917 e++;
2918 }
2919 else {
2920 *l++ = *e++;
2921 }
2922 }
2923 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002924 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002925}
2926
Alexander Belopolsky40018472011-02-26 01:02:56 +00002927PyObject *
2928PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002929 Py_ssize_t size,
2930 const char *encoding,
2931 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002932{
2933 PyObject *buffer = NULL, *unicode;
2934 Py_buffer info;
2935 char lower[11]; /* Enough for any encoding shortcut */
2936
Fred Drakee4315f52000-05-09 19:53:39 +00002937 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002938 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002939 if ((strcmp(lower, "utf-8") == 0) ||
2940 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002941 return PyUnicode_DecodeUTF8(s, size, errors);
2942 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002943 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002944 (strcmp(lower, "iso-8859-1") == 0))
2945 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002946#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002947 else if (strcmp(lower, "mbcs") == 0)
2948 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002949#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002950 else if (strcmp(lower, "ascii") == 0)
2951 return PyUnicode_DecodeASCII(s, size, errors);
2952 else if (strcmp(lower, "utf-16") == 0)
2953 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2954 else if (strcmp(lower, "utf-32") == 0)
2955 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2956 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957
2958 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002959 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002960 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002961 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002962 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963 if (buffer == NULL)
2964 goto onError;
2965 unicode = PyCodec_Decode(buffer, encoding, errors);
2966 if (unicode == NULL)
2967 goto onError;
2968 if (!PyUnicode_Check(unicode)) {
2969 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002970 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002971 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002972 Py_DECREF(unicode);
2973 goto onError;
2974 }
2975 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002976 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002977
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002979 Py_XDECREF(buffer);
2980 return NULL;
2981}
2982
Alexander Belopolsky40018472011-02-26 01:02:56 +00002983PyObject *
2984PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002985 const char *encoding,
2986 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002987{
2988 PyObject *v;
2989
2990 if (!PyUnicode_Check(unicode)) {
2991 PyErr_BadArgument();
2992 goto onError;
2993 }
2994
2995 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002996 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002997
2998 /* Decode via the codec registry */
2999 v = PyCodec_Decode(unicode, encoding, errors);
3000 if (v == NULL)
3001 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003002 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003003
Benjamin Peterson29060642009-01-31 22:14:21 +00003004 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003005 return NULL;
3006}
3007
Alexander Belopolsky40018472011-02-26 01:02:56 +00003008PyObject *
3009PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003010 const char *encoding,
3011 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003012{
3013 PyObject *v;
3014
3015 if (!PyUnicode_Check(unicode)) {
3016 PyErr_BadArgument();
3017 goto onError;
3018 }
3019
3020 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003021 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003022
3023 /* Decode via the codec registry */
3024 v = PyCodec_Decode(unicode, encoding, errors);
3025 if (v == NULL)
3026 goto onError;
3027 if (!PyUnicode_Check(v)) {
3028 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003029 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003030 Py_TYPE(v)->tp_name);
3031 Py_DECREF(v);
3032 goto onError;
3033 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003034 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003035
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003037 return NULL;
3038}
3039
Alexander Belopolsky40018472011-02-26 01:02:56 +00003040PyObject *
3041PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003042 Py_ssize_t size,
3043 const char *encoding,
3044 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003045{
3046 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003047
Guido van Rossumd57fd912000-03-10 22:53:23 +00003048 unicode = PyUnicode_FromUnicode(s, size);
3049 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003050 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003051 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3052 Py_DECREF(unicode);
3053 return v;
3054}
3055
Alexander Belopolsky40018472011-02-26 01:02:56 +00003056PyObject *
3057PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003058 const char *encoding,
3059 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003060{
3061 PyObject *v;
3062
3063 if (!PyUnicode_Check(unicode)) {
3064 PyErr_BadArgument();
3065 goto onError;
3066 }
3067
3068 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003069 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003070
3071 /* Encode via the codec registry */
3072 v = PyCodec_Encode(unicode, encoding, errors);
3073 if (v == NULL)
3074 goto onError;
3075 return v;
3076
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003078 return NULL;
3079}
3080
Victor Stinnerad158722010-10-27 00:25:46 +00003081PyObject *
3082PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003083{
Victor Stinner99b95382011-07-04 14:23:54 +02003084#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003085 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003086#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003087 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003088#else
Victor Stinner793b5312011-04-27 00:24:21 +02003089 PyInterpreterState *interp = PyThreadState_GET()->interp;
3090 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3091 cannot use it to encode and decode filenames before it is loaded. Load
3092 the Python codec requires to encode at least its own filename. Use the C
3093 version of the locale codec until the codec registry is initialized and
3094 the Python codec is loaded.
3095
3096 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3097 cannot only rely on it: check also interp->fscodec_initialized for
3098 subinterpreters. */
3099 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003100 return PyUnicode_AsEncodedString(unicode,
3101 Py_FileSystemDefaultEncoding,
3102 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003103 }
3104 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003105 /* locale encoding with surrogateescape */
3106 wchar_t *wchar;
3107 char *bytes;
3108 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003109 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003110
3111 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3112 if (wchar == NULL)
3113 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003114 bytes = _Py_wchar2char(wchar, &error_pos);
3115 if (bytes == NULL) {
3116 if (error_pos != (size_t)-1) {
3117 char *errmsg = strerror(errno);
3118 PyObject *exc = NULL;
3119 if (errmsg == NULL)
3120 errmsg = "Py_wchar2char() failed";
3121 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003122 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003123 error_pos, error_pos+1,
3124 errmsg);
3125 Py_XDECREF(exc);
3126 }
3127 else
3128 PyErr_NoMemory();
3129 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003130 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003131 }
3132 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003133
3134 bytes_obj = PyBytes_FromString(bytes);
3135 PyMem_Free(bytes);
3136 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003137 }
Victor Stinnerad158722010-10-27 00:25:46 +00003138#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003139}
3140
Alexander Belopolsky40018472011-02-26 01:02:56 +00003141PyObject *
3142PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003143 const char *encoding,
3144 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003145{
3146 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003147 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003148
Guido van Rossumd57fd912000-03-10 22:53:23 +00003149 if (!PyUnicode_Check(unicode)) {
3150 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003151 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003152 }
Fred Drakee4315f52000-05-09 19:53:39 +00003153
Fred Drakee4315f52000-05-09 19:53:39 +00003154 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003155 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003156 if ((strcmp(lower, "utf-8") == 0) ||
3157 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003158 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003159 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003160 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003161 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003162 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003163 }
Victor Stinner37296e82010-06-10 13:36:23 +00003164 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003165 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003166 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003167 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003168#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003169 else if (strcmp(lower, "mbcs") == 0)
3170 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003171#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003172 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003174 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003175
3176 /* Encode via the codec registry */
3177 v = PyCodec_Encode(unicode, encoding, errors);
3178 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003179 return NULL;
3180
3181 /* The normal path */
3182 if (PyBytes_Check(v))
3183 return v;
3184
3185 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003186 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003187 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003188 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003189
3190 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3191 "encoder %s returned bytearray instead of bytes",
3192 encoding);
3193 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003194 Py_DECREF(v);
3195 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003196 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003197
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003198 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3199 Py_DECREF(v);
3200 return b;
3201 }
3202
3203 PyErr_Format(PyExc_TypeError,
3204 "encoder did not return a bytes object (type=%.400s)",
3205 Py_TYPE(v)->tp_name);
3206 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003207 return NULL;
3208}
3209
Alexander Belopolsky40018472011-02-26 01:02:56 +00003210PyObject *
3211PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003212 const char *encoding,
3213 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003214{
3215 PyObject *v;
3216
3217 if (!PyUnicode_Check(unicode)) {
3218 PyErr_BadArgument();
3219 goto onError;
3220 }
3221
3222 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003224
3225 /* Encode via the codec registry */
3226 v = PyCodec_Encode(unicode, encoding, errors);
3227 if (v == NULL)
3228 goto onError;
3229 if (!PyUnicode_Check(v)) {
3230 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003231 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003232 Py_TYPE(v)->tp_name);
3233 Py_DECREF(v);
3234 goto onError;
3235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003236 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003237
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003239 return NULL;
3240}
3241
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003242PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003243PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003244 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003245 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3246}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003247
Christian Heimes5894ba72007-11-04 11:43:14 +00003248PyObject*
3249PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3250{
Victor Stinner99b95382011-07-04 14:23:54 +02003251#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003252 return PyUnicode_DecodeMBCS(s, size, NULL);
3253#elif defined(__APPLE__)
3254 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3255#else
Victor Stinner793b5312011-04-27 00:24:21 +02003256 PyInterpreterState *interp = PyThreadState_GET()->interp;
3257 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3258 cannot use it to encode and decode filenames before it is loaded. Load
3259 the Python codec requires to encode at least its own filename. Use the C
3260 version of the locale codec until the codec registry is initialized and
3261 the Python codec is loaded.
3262
3263 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3264 cannot only rely on it: check also interp->fscodec_initialized for
3265 subinterpreters. */
3266 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003267 return PyUnicode_Decode(s, size,
3268 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003269 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003270 }
3271 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003272 /* locale encoding with surrogateescape */
3273 wchar_t *wchar;
3274 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003275 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003276
3277 if (s[size] != '\0' || size != strlen(s)) {
3278 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3279 return NULL;
3280 }
3281
Victor Stinner168e1172010-10-16 23:16:16 +00003282 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003283 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003284 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003285
Victor Stinner168e1172010-10-16 23:16:16 +00003286 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003287 PyMem_Free(wchar);
3288 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003289 }
Victor Stinnerad158722010-10-27 00:25:46 +00003290#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003291}
3292
Martin v. Löwis011e8422009-05-05 04:43:17 +00003293
3294int
3295PyUnicode_FSConverter(PyObject* arg, void* addr)
3296{
3297 PyObject *output = NULL;
3298 Py_ssize_t size;
3299 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003300 if (arg == NULL) {
3301 Py_DECREF(*(PyObject**)addr);
3302 return 1;
3303 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003304 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003305 output = arg;
3306 Py_INCREF(output);
3307 }
3308 else {
3309 arg = PyUnicode_FromObject(arg);
3310 if (!arg)
3311 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003312 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003313 Py_DECREF(arg);
3314 if (!output)
3315 return 0;
3316 if (!PyBytes_Check(output)) {
3317 Py_DECREF(output);
3318 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3319 return 0;
3320 }
3321 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003322 size = PyBytes_GET_SIZE(output);
3323 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003324 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003325 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003326 Py_DECREF(output);
3327 return 0;
3328 }
3329 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003330 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003331}
3332
3333
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003334int
3335PyUnicode_FSDecoder(PyObject* arg, void* addr)
3336{
3337 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003338 if (arg == NULL) {
3339 Py_DECREF(*(PyObject**)addr);
3340 return 1;
3341 }
3342 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003343 if (PyUnicode_READY(arg))
3344 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003345 output = arg;
3346 Py_INCREF(output);
3347 }
3348 else {
3349 arg = PyBytes_FromObject(arg);
3350 if (!arg)
3351 return 0;
3352 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3353 PyBytes_GET_SIZE(arg));
3354 Py_DECREF(arg);
3355 if (!output)
3356 return 0;
3357 if (!PyUnicode_Check(output)) {
3358 Py_DECREF(output);
3359 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3360 return 0;
3361 }
3362 }
Victor Stinner065836e2011-10-27 01:56:33 +02003363 if (PyUnicode_READY(output) < 0) {
3364 Py_DECREF(output);
3365 return 0;
3366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003367 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003368 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003369 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3370 Py_DECREF(output);
3371 return 0;
3372 }
3373 *(PyObject**)addr = output;
3374 return Py_CLEANUP_SUPPORTED;
3375}
3376
3377
Martin v. Löwis5b222132007-06-10 09:51:05 +00003378char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003380{
Christian Heimesf3863112007-11-22 07:46:41 +00003381 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003382
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003383 if (!PyUnicode_Check(unicode)) {
3384 PyErr_BadArgument();
3385 return NULL;
3386 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003387 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003388 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003389
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003390 if (PyUnicode_UTF8(unicode) == NULL) {
3391 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003392 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3393 if (bytes == NULL)
3394 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003395 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3396 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003397 Py_DECREF(bytes);
3398 return NULL;
3399 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003400 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3401 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3402 PyBytes_AS_STRING(bytes),
3403 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003404 Py_DECREF(bytes);
3405 }
3406
3407 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003408 *psize = PyUnicode_UTF8_LENGTH(unicode);
3409 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003410}
3411
3412char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003413PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003414{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003415 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3416}
3417
3418#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003419static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003420#endif
3421
3422
3423Py_UNICODE *
3424PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3425{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003426 const unsigned char *one_byte;
3427#if SIZEOF_WCHAR_T == 4
3428 const Py_UCS2 *two_bytes;
3429#else
3430 const Py_UCS4 *four_bytes;
3431 const Py_UCS4 *ucs4_end;
3432 Py_ssize_t num_surrogates;
3433#endif
3434 wchar_t *w;
3435 wchar_t *wchar_end;
3436
3437 if (!PyUnicode_Check(unicode)) {
3438 PyErr_BadArgument();
3439 return NULL;
3440 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003441 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003442 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003443 assert(_PyUnicode_KIND(unicode) != 0);
3444 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003445
3446#ifdef Py_DEBUG
3447 ++unicode_as_unicode_calls;
3448#endif
3449
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003450 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003451#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003452 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3453 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003454 num_surrogates = 0;
3455
3456 for (; four_bytes < ucs4_end; ++four_bytes) {
3457 if (*four_bytes > 0xFFFF)
3458 ++num_surrogates;
3459 }
3460
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003461 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3462 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3463 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003464 PyErr_NoMemory();
3465 return NULL;
3466 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003467 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003468
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003469 w = _PyUnicode_WSTR(unicode);
3470 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3471 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003472 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3473 if (*four_bytes > 0xFFFF) {
Victor Stinner0d3721d2011-11-22 03:27:53 +01003474 assert(*four_bytes <= 0x10FFFF);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003475 /* encode surrogate pair in this case */
3476 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3477 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3478 }
3479 else
3480 *w = *four_bytes;
3481
3482 if (w > wchar_end) {
3483 assert(0 && "Miscalculated string end");
3484 }
3485 }
3486 *w = 0;
3487#else
3488 /* sizeof(wchar_t) == 4 */
3489 Py_FatalError("Impossible unicode object state, wstr and str "
3490 "should share memory already.");
3491 return NULL;
3492#endif
3493 }
3494 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003495 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3496 (_PyUnicode_LENGTH(unicode) + 1));
3497 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003498 PyErr_NoMemory();
3499 return NULL;
3500 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003501 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3502 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3503 w = _PyUnicode_WSTR(unicode);
3504 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003505
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003506 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3507 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003508 for (; w < wchar_end; ++one_byte, ++w)
3509 *w = *one_byte;
3510 /* null-terminate the wstr */
3511 *w = 0;
3512 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003513 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003514#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003515 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003516 for (; w < wchar_end; ++two_bytes, ++w)
3517 *w = *two_bytes;
3518 /* null-terminate the wstr */
3519 *w = 0;
3520#else
3521 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003522 PyObject_FREE(_PyUnicode_WSTR(unicode));
3523 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003524 Py_FatalError("Impossible unicode object state, wstr "
3525 "and str should share memory already.");
3526 return NULL;
3527#endif
3528 }
3529 else {
3530 assert(0 && "This should never happen.");
3531 }
3532 }
3533 }
3534 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003535 *size = PyUnicode_WSTR_LENGTH(unicode);
3536 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003537}
3538
Alexander Belopolsky40018472011-02-26 01:02:56 +00003539Py_UNICODE *
3540PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003541{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003542 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543}
3544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003545
Alexander Belopolsky40018472011-02-26 01:02:56 +00003546Py_ssize_t
3547PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003548{
3549 if (!PyUnicode_Check(unicode)) {
3550 PyErr_BadArgument();
3551 goto onError;
3552 }
3553 return PyUnicode_GET_SIZE(unicode);
3554
Benjamin Peterson29060642009-01-31 22:14:21 +00003555 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003556 return -1;
3557}
3558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003559Py_ssize_t
3560PyUnicode_GetLength(PyObject *unicode)
3561{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003562 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003563 PyErr_BadArgument();
3564 return -1;
3565 }
3566
3567 return PyUnicode_GET_LENGTH(unicode);
3568}
3569
3570Py_UCS4
3571PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3572{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003573 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3574 PyErr_BadArgument();
3575 return (Py_UCS4)-1;
3576 }
3577 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3578 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003579 return (Py_UCS4)-1;
3580 }
3581 return PyUnicode_READ_CHAR(unicode, index);
3582}
3583
3584int
3585PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3586{
3587 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003588 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003589 return -1;
3590 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003591 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3592 PyErr_SetString(PyExc_IndexError, "string index out of range");
3593 return -1;
3594 }
3595 if (_PyUnicode_Dirty(unicode))
3596 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003597 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3598 index, ch);
3599 return 0;
3600}
3601
Alexander Belopolsky40018472011-02-26 01:02:56 +00003602const char *
3603PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003604{
Victor Stinner42cb4622010-09-01 19:39:01 +00003605 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003606}
3607
Victor Stinner554f3f02010-06-16 23:33:54 +00003608/* create or adjust a UnicodeDecodeError */
3609static void
3610make_decode_exception(PyObject **exceptionObject,
3611 const char *encoding,
3612 const char *input, Py_ssize_t length,
3613 Py_ssize_t startpos, Py_ssize_t endpos,
3614 const char *reason)
3615{
3616 if (*exceptionObject == NULL) {
3617 *exceptionObject = PyUnicodeDecodeError_Create(
3618 encoding, input, length, startpos, endpos, reason);
3619 }
3620 else {
3621 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3622 goto onError;
3623 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3624 goto onError;
3625 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3626 goto onError;
3627 }
3628 return;
3629
3630onError:
3631 Py_DECREF(*exceptionObject);
3632 *exceptionObject = NULL;
3633}
3634
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003635/* error handling callback helper:
3636 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003637 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003638 and adjust various state variables.
3639 return 0 on success, -1 on error
3640*/
3641
Alexander Belopolsky40018472011-02-26 01:02:56 +00003642static int
3643unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003644 const char *encoding, const char *reason,
3645 const char **input, const char **inend, Py_ssize_t *startinpos,
3646 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003647 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003648{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003649 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650
3651 PyObject *restuple = NULL;
3652 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003653 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003654 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003655 Py_ssize_t requiredsize;
3656 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003657 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003658 int res = -1;
3659
Victor Stinner596a6c42011-11-09 00:02:18 +01003660 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3661 outsize = PyUnicode_GET_LENGTH(*output);
3662 else
3663 outsize = _PyUnicode_WSTR_LENGTH(*output);
3664
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003665 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003666 *errorHandler = PyCodec_LookupError(errors);
3667 if (*errorHandler == NULL)
3668 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003669 }
3670
Victor Stinner554f3f02010-06-16 23:33:54 +00003671 make_decode_exception(exceptionObject,
3672 encoding,
3673 *input, *inend - *input,
3674 *startinpos, *endinpos,
3675 reason);
3676 if (*exceptionObject == NULL)
3677 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003678
3679 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3680 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003681 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003682 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003683 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003684 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003685 }
3686 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003687 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003688 if (PyUnicode_READY(repunicode) < 0)
3689 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003690
3691 /* Copy back the bytes variables, which might have been modified by the
3692 callback */
3693 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3694 if (!inputobj)
3695 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003696 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003697 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003698 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003699 *input = PyBytes_AS_STRING(inputobj);
3700 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003701 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003702 /* we can DECREF safely, as the exception has another reference,
3703 so the object won't go away. */
3704 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003705
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003706 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003707 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003708 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003709 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3710 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003711 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003712
Victor Stinner596a6c42011-11-09 00:02:18 +01003713 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3714 /* need more space? (at least enough for what we
3715 have+the replacement+the rest of the string (starting
3716 at the new input position), so we won't have to check space
3717 when there are no errors in the rest of the string) */
3718 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3719 requiredsize = *outpos + replen + insize-newpos;
3720 if (requiredsize > outsize) {
3721 if (requiredsize<2*outsize)
3722 requiredsize = 2*outsize;
3723 if (unicode_resize(output, requiredsize) < 0)
3724 goto onError;
3725 }
3726 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003727 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003728 copy_characters(*output, *outpos, repunicode, 0, replen);
3729 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003730 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003731 else {
3732 wchar_t *repwstr;
3733 Py_ssize_t repwlen;
3734 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3735 if (repwstr == NULL)
3736 goto onError;
3737 /* need more space? (at least enough for what we
3738 have+the replacement+the rest of the string (starting
3739 at the new input position), so we won't have to check space
3740 when there are no errors in the rest of the string) */
3741 requiredsize = *outpos + repwlen + insize-newpos;
3742 if (requiredsize > outsize) {
3743 if (requiredsize < 2*outsize)
3744 requiredsize = 2*outsize;
3745 if (unicode_resize(output, requiredsize) < 0)
3746 goto onError;
3747 }
3748 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3749 *outpos += repwlen;
3750 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003751 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003752 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003753
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003754 /* we made it! */
3755 res = 0;
3756
Benjamin Peterson29060642009-01-31 22:14:21 +00003757 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003758 Py_XDECREF(restuple);
3759 return res;
3760}
3761
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003762/* --- UTF-7 Codec -------------------------------------------------------- */
3763
Antoine Pitrou244651a2009-05-04 18:56:13 +00003764/* See RFC2152 for details. We encode conservatively and decode liberally. */
3765
3766/* Three simple macros defining base-64. */
3767
3768/* Is c a base-64 character? */
3769
3770#define IS_BASE64(c) \
3771 (((c) >= 'A' && (c) <= 'Z') || \
3772 ((c) >= 'a' && (c) <= 'z') || \
3773 ((c) >= '0' && (c) <= '9') || \
3774 (c) == '+' || (c) == '/')
3775
3776/* given that c is a base-64 character, what is its base-64 value? */
3777
3778#define FROM_BASE64(c) \
3779 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3780 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3781 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3782 (c) == '+' ? 62 : 63)
3783
3784/* What is the base-64 character of the bottom 6 bits of n? */
3785
3786#define TO_BASE64(n) \
3787 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3788
3789/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3790 * decoded as itself. We are permissive on decoding; the only ASCII
3791 * byte not decoding to itself is the + which begins a base64
3792 * string. */
3793
3794#define DECODE_DIRECT(c) \
3795 ((c) <= 127 && (c) != '+')
3796
3797/* The UTF-7 encoder treats ASCII characters differently according to
3798 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3799 * the above). See RFC2152. This array identifies these different
3800 * sets:
3801 * 0 : "Set D"
3802 * alphanumeric and '(),-./:?
3803 * 1 : "Set O"
3804 * !"#$%&*;<=>@[]^_`{|}
3805 * 2 : "whitespace"
3806 * ht nl cr sp
3807 * 3 : special (must be base64 encoded)
3808 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3809 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003810
Tim Petersced69f82003-09-16 20:30:58 +00003811static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003812char utf7_category[128] = {
3813/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3814 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3815/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3816 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3817/* sp ! " # $ % & ' ( ) * + , - . / */
3818 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3819/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3820 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3821/* @ A B C D E F G H I J K L M N O */
3822 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3823/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3824 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3825/* ` a b c d e f g h i j k l m n o */
3826 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3827/* p q r s t u v w x y z { | } ~ del */
3828 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003829};
3830
Antoine Pitrou244651a2009-05-04 18:56:13 +00003831/* ENCODE_DIRECT: this character should be encoded as itself. The
3832 * answer depends on whether we are encoding set O as itself, and also
3833 * on whether we are encoding whitespace as itself. RFC2152 makes it
3834 * clear that the answers to these questions vary between
3835 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003836
Antoine Pitrou244651a2009-05-04 18:56:13 +00003837#define ENCODE_DIRECT(c, directO, directWS) \
3838 ((c) < 128 && (c) > 0 && \
3839 ((utf7_category[(c)] == 0) || \
3840 (directWS && (utf7_category[(c)] == 2)) || \
3841 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003842
Alexander Belopolsky40018472011-02-26 01:02:56 +00003843PyObject *
3844PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003845 Py_ssize_t size,
3846 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003847{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003848 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3849}
3850
Antoine Pitrou244651a2009-05-04 18:56:13 +00003851/* The decoder. The only state we preserve is our read position,
3852 * i.e. how many characters we have consumed. So if we end in the
3853 * middle of a shift sequence we have to back off the read position
3854 * and the output to the beginning of the sequence, otherwise we lose
3855 * all the shift state (seen bits, number of bits seen, high
3856 * surrogate). */
3857
Alexander Belopolsky40018472011-02-26 01:02:56 +00003858PyObject *
3859PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003860 Py_ssize_t size,
3861 const char *errors,
3862 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003863{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003864 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003865 Py_ssize_t startinpos;
3866 Py_ssize_t endinpos;
3867 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003869 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003870 const char *errmsg = "";
3871 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003872 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003873 unsigned int base64bits = 0;
3874 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003875 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003876 PyObject *errorHandler = NULL;
3877 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003878
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003879 /* Start off assuming it's all ASCII. Widen later as necessary. */
3880 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003881 if (!unicode)
3882 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003883 if (size == 0) {
3884 if (consumed)
3885 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003886 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003887 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003888
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003889 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003890 e = s + size;
3891
3892 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003893 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003894 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003895 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003896
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 if (inShift) { /* in a base-64 section */
3898 if (IS_BASE64(ch)) { /* consume a base-64 character */
3899 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3900 base64bits += 6;
3901 s++;
3902 if (base64bits >= 16) {
3903 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003904 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003905 base64bits -= 16;
3906 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3907 if (surrogate) {
3908 /* expecting a second surrogate */
3909 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003910 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3911 | (outCh & 0x3FF)) + 0x10000;
3912 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3913 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003914 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003915 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003916 }
3917 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003918 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3919 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003920 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003921 }
3922 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003923 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003924 /* first surrogate */
3925 surrogate = outCh;
3926 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003927 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003928 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3929 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003930 }
3931 }
3932 }
3933 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003934 inShift = 0;
3935 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003936 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003937 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3938 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003939 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003940 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003941 if (base64bits > 0) { /* left-over bits */
3942 if (base64bits >= 6) {
3943 /* We've seen at least one base-64 character */
3944 errmsg = "partial character in shift sequence";
3945 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003946 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003947 else {
3948 /* Some bits remain; they should be zero */
3949 if (base64buffer != 0) {
3950 errmsg = "non-zero padding bits in shift sequence";
3951 goto utf7Error;
3952 }
3953 }
3954 }
3955 if (ch != '-') {
3956 /* '-' is absorbed; other terminating
3957 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003958 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3959 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003960 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003961 }
3962 }
3963 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003964 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003965 s++; /* consume '+' */
3966 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003967 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003968 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3969 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003970 }
3971 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003972 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003973 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003974 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003975 }
3976 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003977 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003978 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3979 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003980 s++;
3981 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003982 else {
3983 startinpos = s-starts;
3984 s++;
3985 errmsg = "unexpected special character";
3986 goto utf7Error;
3987 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003988 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003989utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003990 endinpos = s-starts;
3991 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003992 errors, &errorHandler,
3993 "utf7", errmsg,
3994 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003995 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003996 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003997 }
3998
Antoine Pitrou244651a2009-05-04 18:56:13 +00003999 /* end of string */
4000
4001 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4002 /* if we're in an inconsistent state, that's an error */
4003 if (surrogate ||
4004 (base64bits >= 6) ||
4005 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004006 endinpos = size;
4007 if (unicode_decode_call_errorhandler(
4008 errors, &errorHandler,
4009 "utf7", "unterminated shift sequence",
4010 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004011 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004012 goto onError;
4013 if (s < e)
4014 goto restart;
4015 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004016 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004017
4018 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004019 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004020 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004021 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004022 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004023 }
4024 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004025 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004026 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004027 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004028
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004029 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004030 goto onError;
4031
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004032 Py_XDECREF(errorHandler);
4033 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004034 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004035
Benjamin Peterson29060642009-01-31 22:14:21 +00004036 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004037 Py_XDECREF(errorHandler);
4038 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004039 Py_DECREF(unicode);
4040 return NULL;
4041}
4042
4043
Alexander Belopolsky40018472011-02-26 01:02:56 +00004044PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004045_PyUnicode_EncodeUTF7(PyObject *str,
4046 int base64SetO,
4047 int base64WhiteSpace,
4048 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004049{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004050 int kind;
4051 void *data;
4052 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004053 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004054 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004055 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004056 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004057 unsigned int base64bits = 0;
4058 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004059 char * out;
4060 char * start;
4061
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004062 if (PyUnicode_READY(str) < 0)
4063 return NULL;
4064 kind = PyUnicode_KIND(str);
4065 data = PyUnicode_DATA(str);
4066 len = PyUnicode_GET_LENGTH(str);
4067
4068 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004069 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004070
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004071 /* It might be possible to tighten this worst case */
4072 allocated = 8 * len;
4073 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004074 return PyErr_NoMemory();
4075
Antoine Pitrou244651a2009-05-04 18:56:13 +00004076 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004077 if (v == NULL)
4078 return NULL;
4079
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004080 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004081 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004082 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004083
Antoine Pitrou244651a2009-05-04 18:56:13 +00004084 if (inShift) {
4085 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4086 /* shifting out */
4087 if (base64bits) { /* output remaining bits */
4088 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4089 base64buffer = 0;
4090 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004091 }
4092 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004093 /* Characters not in the BASE64 set implicitly unshift the sequence
4094 so no '-' is required, except if the character is itself a '-' */
4095 if (IS_BASE64(ch) || ch == '-') {
4096 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004097 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004098 *out++ = (char) ch;
4099 }
4100 else {
4101 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004102 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004103 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004104 else { /* not in a shift sequence */
4105 if (ch == '+') {
4106 *out++ = '+';
4107 *out++ = '-';
4108 }
4109 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4110 *out++ = (char) ch;
4111 }
4112 else {
4113 *out++ = '+';
4114 inShift = 1;
4115 goto encode_char;
4116 }
4117 }
4118 continue;
4119encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004120 if (ch >= 0x10000) {
Victor Stinner0d3721d2011-11-22 03:27:53 +01004121 assert(ch <= 0x10FFFF);
4122
Antoine Pitrou244651a2009-05-04 18:56:13 +00004123 /* code first surrogate */
4124 base64bits += 16;
4125 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4126 while (base64bits >= 6) {
4127 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4128 base64bits -= 6;
4129 }
4130 /* prepare second surrogate */
4131 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4132 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004133 base64bits += 16;
4134 base64buffer = (base64buffer << 16) | ch;
4135 while (base64bits >= 6) {
4136 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4137 base64bits -= 6;
4138 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004139 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004140 if (base64bits)
4141 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4142 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004143 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004144 if (_PyBytes_Resize(&v, out - start) < 0)
4145 return NULL;
4146 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004147}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004148PyObject *
4149PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4150 Py_ssize_t size,
4151 int base64SetO,
4152 int base64WhiteSpace,
4153 const char *errors)
4154{
4155 PyObject *result;
4156 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4157 if (tmp == NULL)
4158 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004159 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004160 base64WhiteSpace, errors);
4161 Py_DECREF(tmp);
4162 return result;
4163}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004164
Antoine Pitrou244651a2009-05-04 18:56:13 +00004165#undef IS_BASE64
4166#undef FROM_BASE64
4167#undef TO_BASE64
4168#undef DECODE_DIRECT
4169#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004170
Guido van Rossumd57fd912000-03-10 22:53:23 +00004171/* --- UTF-8 Codec -------------------------------------------------------- */
4172
Tim Petersced69f82003-09-16 20:30:58 +00004173static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004174char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004175 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4176 illegal prefix. See RFC 3629 for details */
4177 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4178 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004179 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004180 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4181 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4182 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4183 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004184 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4185 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 +00004186 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4187 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004188 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4189 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4190 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4191 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4192 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 +00004193};
4194
Alexander Belopolsky40018472011-02-26 01:02:56 +00004195PyObject *
4196PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004197 Py_ssize_t size,
4198 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004199{
Walter Dörwald69652032004-09-07 20:24:22 +00004200 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4201}
4202
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004203#include "stringlib/ucs1lib.h"
4204#include "stringlib/codecs.h"
4205#include "stringlib/undef.h"
4206
4207#include "stringlib/ucs2lib.h"
4208#include "stringlib/codecs.h"
4209#include "stringlib/undef.h"
4210
4211#include "stringlib/ucs4lib.h"
4212#include "stringlib/codecs.h"
4213#include "stringlib/undef.h"
4214
Antoine Pitrouab868312009-01-10 15:40:25 +00004215/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4216#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4217
4218/* Mask to quickly check whether a C 'long' contains a
4219 non-ASCII, UTF8-encoded char. */
4220#if (SIZEOF_LONG == 8)
4221# define ASCII_CHAR_MASK 0x8080808080808080L
4222#elif (SIZEOF_LONG == 4)
4223# define ASCII_CHAR_MASK 0x80808080L
4224#else
4225# error C 'long' size should be either 4 or 8!
4226#endif
4227
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004228/* Scans a UTF-8 string and returns the maximum character to be expected
4229 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004230
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004231 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004232 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004233 */
4234static Py_UCS4
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004235utf8_max_char_size_and_char_count(const char *s, Py_ssize_t string_size,
4236 Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004237{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004238 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004239 const unsigned char *p = (const unsigned char *)s;
4240 const unsigned char *end = p + string_size;
4241 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004242
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004243 assert(unicode_size != NULL);
4244
4245 /* By having a cascade of independent loops which fallback onto each
4246 other, we minimize the amount of work done in the average loop
4247 iteration, and we also maximize the CPU's ability to predict
4248 branches correctly (because a given condition will have always the
4249 same boolean outcome except perhaps in the last iteration of the
4250 corresponding loop).
4251 In the general case this brings us rather close to decoding
4252 performance pre-PEP 393, despite the two-pass decoding.
4253
4254 Note that the pure ASCII loop is not duplicated once a non-ASCII
4255 character has been encountered. It is actually a pessimization (by
4256 a significant factor) to use this loop on text with many non-ASCII
4257 characters, and it is important to avoid bad performance on valid
4258 utf-8 data (invalid utf-8 being a different can of worms).
4259 */
4260
4261 /* ASCII */
4262 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004263 /* Only check value if it's not a ASCII char... */
4264 if (*p < 0x80) {
4265 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4266 an explanation. */
4267 if (!((size_t) p & LONG_PTR_MASK)) {
4268 /* Help register allocation */
4269 register const unsigned char *_p = p;
4270 while (_p < aligned_end) {
4271 unsigned long value = *(unsigned long *) _p;
4272 if (value & ASCII_CHAR_MASK)
4273 break;
4274 _p += SIZEOF_LONG;
4275 char_count += SIZEOF_LONG;
4276 }
4277 p = _p;
4278 if (p == end)
4279 break;
4280 }
4281 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004282 if (*p < 0x80)
4283 ++char_count;
4284 else
4285 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004286 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004287 *unicode_size = char_count;
4288 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004289
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004290_ucs1loop:
4291 for (; p < end; ++p) {
4292 if (*p < 0xc4)
4293 char_count += ((*p & 0xc0) != 0x80);
4294 else
4295 goto _ucs2loop;
4296 }
4297 *unicode_size = char_count;
4298 return 255;
4299
4300_ucs2loop:
4301 for (; p < end; ++p) {
4302 if (*p < 0xf0)
4303 char_count += ((*p & 0xc0) != 0x80);
4304 else
4305 goto _ucs4loop;
4306 }
4307 *unicode_size = char_count;
4308 return 65535;
4309
4310_ucs4loop:
4311 for (; p < end; ++p) {
4312 char_count += ((*p & 0xc0) != 0x80);
4313 }
4314 *unicode_size = char_count;
4315 return 65537;
4316}
4317
4318/* Called when we encountered some error that wasn't detected in the original
4319 scan, e.g. an encoded surrogate character. The original maxchar computation
4320 may have been incorrect, so redo it. */
4321static int
4322refit_partial_string(PyObject **unicode, int kind, void *data, Py_ssize_t n)
4323{
4324 PyObject *tmp;
Victor Stinnerf8facac2011-11-22 02:30:47 +01004325 Py_ssize_t k;
4326 Py_UCS4 maxchar;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004327 for (k = 0, maxchar = 0; k < n; k++)
4328 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4329 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(*unicode), maxchar);
4330 if (tmp == NULL)
4331 return -1;
4332 PyUnicode_CopyCharacters(tmp, 0, *unicode, 0, n);
4333 Py_DECREF(*unicode);
4334 *unicode = tmp;
4335 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004336}
4337
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004338/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4339 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4340 onError. Potential resizing overallocates, so the result needs to shrink
4341 at the end.
4342*/
4343#define WRITE_MAYBE_FAIL(index, value) \
4344 do { \
4345 if (has_errors) { \
4346 Py_ssize_t pos = index; \
4347 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4348 unicode_resize(&unicode, pos + pos/8) < 0) \
4349 goto onError; \
4350 if (unicode_putchar(&unicode, &pos, value) < 0) \
4351 goto onError; \
4352 } \
4353 else \
4354 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004355 } while (0)
4356
Alexander Belopolsky40018472011-02-26 01:02:56 +00004357PyObject *
4358PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004359 Py_ssize_t size,
4360 const char *errors,
4361 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004362{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004363 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004364 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004365 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004366 Py_ssize_t startinpos;
4367 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004368 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004369 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004370 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004371 PyObject *errorHandler = NULL;
4372 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004373 Py_UCS4 maxchar = 0;
4374 Py_ssize_t unicode_size;
4375 Py_ssize_t i;
4376 int kind;
4377 void *data;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004378 int has_errors = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004379
Walter Dörwald69652032004-09-07 20:24:22 +00004380 if (size == 0) {
4381 if (consumed)
4382 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004383 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004384 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004385 maxchar = utf8_max_char_size_and_char_count(s, size, &unicode_size);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004386 /* When the string is ASCII only, just use memcpy and return.
4387 unicode_size may be != size if there is an incomplete UTF-8
4388 sequence at the end of the ASCII block. */
4389 if (maxchar < 128 && size == unicode_size) {
Victor Stinner42885202011-11-22 01:23:02 +01004390 if (consumed)
4391 *consumed = size;
4392
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004393 if (size == 1)
4394 return get_latin1_char((unsigned char)s[0]);
4395
4396 unicode = PyUnicode_New(unicode_size, maxchar);
4397 if (!unicode)
4398 return NULL;
4399 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4400 assert(_PyUnicode_CheckConsistency(unicode, 1));
4401 return unicode;
4402 }
4403
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004404 /* In case of errors, maxchar and size computation might be incorrect;
4405 code below refits and resizes as necessary. */
4406 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004407 if (!unicode)
4408 return NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 kind = PyUnicode_KIND(unicode);
4410 data = PyUnicode_DATA(unicode);
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004411
Guido van Rossumd57fd912000-03-10 22:53:23 +00004412 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004413 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004414 e = s + size;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004415 switch (kind) {
4416 case PyUnicode_1BYTE_KIND:
4417 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4418 break;
4419 case PyUnicode_2BYTE_KIND:
4420 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4421 break;
4422 case PyUnicode_4BYTE_KIND:
4423 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4424 break;
4425 }
4426 if (!has_errors) {
4427 /* Ensure the unicode size calculation was correct */
4428 assert(i == unicode_size);
4429 assert(s == e);
4430 if (consumed)
4431 *consumed = s-starts;
4432 return unicode;
4433 }
4434 /* Fall through to the generic decoding loop for the rest of
4435 the string */
4436 if (refit_partial_string(&unicode, kind, data, i) < 0)
4437 goto onError;
4438
Antoine Pitrouab868312009-01-10 15:40:25 +00004439 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004440
4441 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004442 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004443
4444 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004445 /* Fast path for runs of ASCII characters. Given that common UTF-8
4446 input will consist of an overwhelming majority of ASCII
4447 characters, we try to optimize for this case by checking
4448 as many characters as a C 'long' can contain.
4449 First, check if we can do an aligned read, as most CPUs have
4450 a penalty for unaligned reads.
4451 */
4452 if (!((size_t) s & LONG_PTR_MASK)) {
4453 /* Help register allocation */
4454 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004455 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004456 while (_s < aligned_end) {
4457 /* Read a whole long at a time (either 4 or 8 bytes),
4458 and do a fast unrolled copy if it only contains ASCII
4459 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004460 unsigned long value = *(unsigned long *) _s;
4461 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004462 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004463 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4464 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4465 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4466 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004467#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004468 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4469 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4470 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4471 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004472#endif
4473 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004474 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004475 }
4476 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004477 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004478 if (s == e)
4479 break;
4480 ch = (unsigned char)*s;
4481 }
4482 }
4483
4484 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004485 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004486 s++;
4487 continue;
4488 }
4489
4490 n = utf8_code_length[ch];
4491
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004492 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004493 if (consumed)
4494 break;
4495 else {
4496 errmsg = "unexpected end of data";
4497 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004498 endinpos = startinpos+1;
4499 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4500 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 goto utf8Error;
4502 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004503 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004504
4505 switch (n) {
4506
4507 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004508 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 startinpos = s-starts;
4510 endinpos = startinpos+1;
4511 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004512
4513 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004514 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004515 startinpos = s-starts;
4516 endinpos = startinpos+1;
4517 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518
4519 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004520 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004521 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004522 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004523 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004524 goto utf8Error;
4525 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004526 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004527 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004528 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529 break;
4530
4531 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004532 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4533 will result in surrogates in range d800-dfff. Surrogates are
4534 not valid UTF-8 so they are rejected.
4535 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4536 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004537 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004538 (s[2] & 0xc0) != 0x80 ||
4539 ((unsigned char)s[0] == 0xE0 &&
4540 (unsigned char)s[1] < 0xA0) ||
4541 ((unsigned char)s[0] == 0xED &&
4542 (unsigned char)s[1] > 0x9F)) {
4543 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004544 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004545 endinpos = startinpos + 1;
4546
4547 /* if s[1] first two bits are 1 and 0, then the invalid
4548 continuation byte is s[2], so increment endinpos by 1,
4549 if not, s[1] is invalid and endinpos doesn't need to
4550 be incremented. */
4551 if ((s[1] & 0xC0) == 0x80)
4552 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004553 goto utf8Error;
4554 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004555 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004556 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004557 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004558 break;
4559
4560 case 4:
4561 if ((s[1] & 0xc0) != 0x80 ||
4562 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004563 (s[3] & 0xc0) != 0x80 ||
4564 ((unsigned char)s[0] == 0xF0 &&
4565 (unsigned char)s[1] < 0x90) ||
4566 ((unsigned char)s[0] == 0xF4 &&
4567 (unsigned char)s[1] > 0x8F)) {
4568 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004569 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004570 endinpos = startinpos + 1;
4571 if ((s[1] & 0xC0) == 0x80) {
4572 endinpos++;
4573 if ((s[2] & 0xC0) == 0x80)
4574 endinpos++;
4575 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004576 goto utf8Error;
4577 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004578 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004579 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4580 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4581
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004582 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004583 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004584 }
4585 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004586 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004587
Benjamin Peterson29060642009-01-31 22:14:21 +00004588 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004589 if (!has_errors) {
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004590 if (refit_partial_string(&unicode, kind, data, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004591 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004592 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004593 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004594 if (unicode_decode_call_errorhandler(
4595 errors, &errorHandler,
4596 "utf8", errmsg,
4597 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004598 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004599 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004600 /* Update data because unicode_decode_call_errorhandler might have
4601 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004602 data = PyUnicode_DATA(unicode);
4603 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004604 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004606 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004607 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004608
Walter Dörwald69652032004-09-07 20:24:22 +00004609 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004610 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004612 /* Adjust length and ready string when it contained errors and
4613 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004614 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004615 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004616 goto onError;
4617 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004618
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004619 Py_XDECREF(errorHandler);
4620 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004621 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004622 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004623
Benjamin Peterson29060642009-01-31 22:14:21 +00004624 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004625 Py_XDECREF(errorHandler);
4626 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004627 Py_DECREF(unicode);
4628 return NULL;
4629}
4630
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004631#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004632
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004633#ifdef __APPLE__
4634
4635/* Simplified UTF-8 decoder using surrogateescape error handler,
4636 used to decode the command line arguments on Mac OS X. */
4637
4638wchar_t*
4639_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4640{
4641 int n;
4642 const char *e;
4643 wchar_t *unicode, *p;
4644
4645 /* Note: size will always be longer than the resulting Unicode
4646 character count */
4647 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4648 PyErr_NoMemory();
4649 return NULL;
4650 }
4651 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4652 if (!unicode)
4653 return NULL;
4654
4655 /* Unpack UTF-8 encoded data */
4656 p = unicode;
4657 e = s + size;
4658 while (s < e) {
4659 Py_UCS4 ch = (unsigned char)*s;
4660
4661 if (ch < 0x80) {
4662 *p++ = (wchar_t)ch;
4663 s++;
4664 continue;
4665 }
4666
4667 n = utf8_code_length[ch];
4668 if (s + n > e) {
4669 goto surrogateescape;
4670 }
4671
4672 switch (n) {
4673 case 0:
4674 case 1:
4675 goto surrogateescape;
4676
4677 case 2:
4678 if ((s[1] & 0xc0) != 0x80)
4679 goto surrogateescape;
4680 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4681 assert ((ch > 0x007F) && (ch <= 0x07FF));
4682 *p++ = (wchar_t)ch;
4683 break;
4684
4685 case 3:
4686 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4687 will result in surrogates in range d800-dfff. Surrogates are
4688 not valid UTF-8 so they are rejected.
4689 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4690 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4691 if ((s[1] & 0xc0) != 0x80 ||
4692 (s[2] & 0xc0) != 0x80 ||
4693 ((unsigned char)s[0] == 0xE0 &&
4694 (unsigned char)s[1] < 0xA0) ||
4695 ((unsigned char)s[0] == 0xED &&
4696 (unsigned char)s[1] > 0x9F)) {
4697
4698 goto surrogateescape;
4699 }
4700 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4701 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004702 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004703 break;
4704
4705 case 4:
4706 if ((s[1] & 0xc0) != 0x80 ||
4707 (s[2] & 0xc0) != 0x80 ||
4708 (s[3] & 0xc0) != 0x80 ||
4709 ((unsigned char)s[0] == 0xF0 &&
4710 (unsigned char)s[1] < 0x90) ||
4711 ((unsigned char)s[0] == 0xF4 &&
4712 (unsigned char)s[1] > 0x8F)) {
4713 goto surrogateescape;
4714 }
4715 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4716 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4717 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4718
4719#if SIZEOF_WCHAR_T == 4
4720 *p++ = (wchar_t)ch;
4721#else
4722 /* compute and append the two surrogates: */
4723
4724 /* translate from 10000..10FFFF to 0..FFFF */
4725 ch -= 0x10000;
4726
4727 /* high surrogate = top 10 bits added to D800 */
4728 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4729
4730 /* low surrogate = bottom 10 bits added to DC00 */
4731 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4732#endif
4733 break;
4734 }
4735 s += n;
4736 continue;
4737
4738 surrogateescape:
4739 *p++ = 0xDC00 + ch;
4740 s++;
4741 }
4742 *p = L'\0';
4743 return unicode;
4744}
4745
4746#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004748/* Primary internal function which creates utf8 encoded bytes objects.
4749
4750 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004751 and allocate exactly as much space needed at the end. Else allocate the
4752 maximum possible needed (4 result bytes per Unicode character), and return
4753 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004754*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004755PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004756_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004757{
Tim Peters602f7402002-04-27 18:03:26 +00004758#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004759
Guido van Rossum98297ee2007-11-06 21:34:58 +00004760 Py_ssize_t i; /* index into s of next input byte */
4761 PyObject *result; /* result string object */
4762 char *p; /* next free byte in output buffer */
4763 Py_ssize_t nallocated; /* number of result bytes allocated */
4764 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004765 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004766 PyObject *errorHandler = NULL;
4767 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004768 int kind;
4769 void *data;
4770 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004771 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004773 if (!PyUnicode_Check(unicode)) {
4774 PyErr_BadArgument();
4775 return NULL;
4776 }
4777
4778 if (PyUnicode_READY(unicode) == -1)
4779 return NULL;
4780
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004781 if (PyUnicode_UTF8(unicode))
4782 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4783 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004784
4785 kind = PyUnicode_KIND(unicode);
4786 data = PyUnicode_DATA(unicode);
4787 size = PyUnicode_GET_LENGTH(unicode);
4788
Tim Peters602f7402002-04-27 18:03:26 +00004789 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790
Tim Peters602f7402002-04-27 18:03:26 +00004791 if (size <= MAX_SHORT_UNICHARS) {
4792 /* Write into the stack buffer; nallocated can't overflow.
4793 * At the end, we'll allocate exactly as much heap space as it
4794 * turns out we need.
4795 */
4796 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004797 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004798 p = stackbuf;
4799 }
4800 else {
4801 /* Overallocate on the heap, and give the excess back at the end. */
4802 nallocated = size * 4;
4803 if (nallocated / 4 != size) /* overflow! */
4804 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004805 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004806 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004807 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004808 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004809 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004810
Tim Peters602f7402002-04-27 18:03:26 +00004811 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004812 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004813
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004814 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004815 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004816 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004817
Guido van Rossumd57fd912000-03-10 22:53:23 +00004818 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004819 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004820 *p++ = (char)(0xc0 | (ch >> 6));
4821 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004822 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004823 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004824 Py_ssize_t repsize, k, startpos;
4825 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004826 rep = unicode_encode_call_errorhandler(
4827 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004828 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004829 if (!rep)
4830 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004832 if (PyBytes_Check(rep))
4833 repsize = PyBytes_GET_SIZE(rep);
4834 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004835 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004836
4837 if (repsize > 4) {
4838 Py_ssize_t offset;
4839
4840 if (result == NULL)
4841 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004842 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004843 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004845 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4846 /* integer overflow */
4847 PyErr_NoMemory();
4848 goto error;
4849 }
4850 nallocated += repsize - 4;
4851 if (result != NULL) {
4852 if (_PyBytes_Resize(&result, nallocated) < 0)
4853 goto error;
4854 } else {
4855 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004856 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004857 goto error;
4858 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4859 }
4860 p = PyBytes_AS_STRING(result) + offset;
4861 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004863 if (PyBytes_Check(rep)) {
4864 char *prep = PyBytes_AS_STRING(rep);
4865 for(k = repsize; k > 0; k--)
4866 *p++ = *prep++;
4867 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004868 enum PyUnicode_Kind repkind;
4869 void *repdata;
4870
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004871 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004872 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004873 repkind = PyUnicode_KIND(rep);
4874 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004875
4876 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004877 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004878 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004879 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004880 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004881 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004882 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004883 goto error;
4884 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004885 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004886 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004887 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004888 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004889 } else if (ch < 0x10000) {
4890 *p++ = (char)(0xe0 | (ch >> 12));
4891 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4892 *p++ = (char)(0x80 | (ch & 0x3f));
4893 } else /* ch >= 0x10000 */ {
Victor Stinner0d3721d2011-11-22 03:27:53 +01004894 assert(ch <= 0x10FFFF);
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) {
Victor Stinner0d3721d2011-11-22 03:27:53 +01005967 assert(ch <= 0x10FFFF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005968 *p++ = '\\';
5969 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005970 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5971 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5972 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5973 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5974 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5975 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5976 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5977 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005979 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005980
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005982 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 *p++ = '\\';
5984 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005985 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5986 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5987 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5988 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005990
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005991 /* Map special whitespace to '\t', \n', '\r' */
5992 else if (ch == '\t') {
5993 *p++ = '\\';
5994 *p++ = 't';
5995 }
5996 else if (ch == '\n') {
5997 *p++ = '\\';
5998 *p++ = 'n';
5999 }
6000 else if (ch == '\r') {
6001 *p++ = '\\';
6002 *p++ = 'r';
6003 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006004
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006005 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006006 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006008 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006009 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6010 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006011 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006012
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013 /* Copy everything else as-is */
6014 else
6015 *p++ = (char) ch;
6016 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006018 assert(p - PyBytes_AS_STRING(repr) > 0);
6019 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6020 return NULL;
6021 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022}
6023
Alexander Belopolsky40018472011-02-26 01:02:56 +00006024PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006025PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6026 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006028 PyObject *result;
6029 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6030 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006032 result = PyUnicode_AsUnicodeEscapeString(tmp);
6033 Py_DECREF(tmp);
6034 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035}
6036
6037/* --- Raw Unicode Escape Codec ------------------------------------------- */
6038
Alexander Belopolsky40018472011-02-26 01:02:56 +00006039PyObject *
6040PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006041 Py_ssize_t size,
6042 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006044 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006045 Py_ssize_t startinpos;
6046 Py_ssize_t endinpos;
6047 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006048 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049 const char *end;
6050 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006051 PyObject *errorHandler = NULL;
6052 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006053
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054 /* Escaped strings will always be longer than the resulting
6055 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006056 length after conversion to the true value. (But decoding error
6057 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006058 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006062 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006063 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 end = s + size;
6065 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 unsigned char c;
6067 Py_UCS4 x;
6068 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006069 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070
Benjamin Peterson29060642009-01-31 22:14:21 +00006071 /* Non-escape characters are interpreted as Unicode ordinals */
6072 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006073 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6074 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006076 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 startinpos = s-starts;
6078
6079 /* \u-escapes are only interpreted iff the number of leading
6080 backslashes if odd */
6081 bs = s;
6082 for (;s < end;) {
6083 if (*s != '\\')
6084 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006085 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6086 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 }
6088 if (((s - bs) & 1) == 0 ||
6089 s >= end ||
6090 (*s != 'u' && *s != 'U')) {
6091 continue;
6092 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006093 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006094 count = *s=='u' ? 4 : 8;
6095 s++;
6096
6097 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 for (x = 0, i = 0; i < count; ++i, ++s) {
6099 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006100 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006101 endinpos = s-starts;
6102 if (unicode_decode_call_errorhandler(
6103 errors, &errorHandler,
6104 "rawunicodeescape", "truncated \\uXXXX",
6105 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006106 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 goto onError;
6108 goto nextByte;
6109 }
6110 x = (x<<4) & ~0xF;
6111 if (c >= '0' && c <= '9')
6112 x += c - '0';
6113 else if (c >= 'a' && c <= 'f')
6114 x += 10 + c - 'a';
6115 else
6116 x += 10 + c - 'A';
6117 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006118 if (x <= 0x10ffff) {
6119 if (unicode_putchar(&v, &outpos, x) < 0)
6120 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006121 } else {
6122 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006123 if (unicode_decode_call_errorhandler(
6124 errors, &errorHandler,
6125 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006127 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006128 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006129 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 nextByte:
6131 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006133 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006135 Py_XDECREF(errorHandler);
6136 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006137 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006138
Benjamin Peterson29060642009-01-31 22:14:21 +00006139 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006140 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006141 Py_XDECREF(errorHandler);
6142 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006143 return NULL;
6144}
6145
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006146
Alexander Belopolsky40018472011-02-26 01:02:56 +00006147PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006148PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006150 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 char *p;
6152 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 Py_ssize_t expandsize, pos;
6154 int kind;
6155 void *data;
6156 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006158 if (!PyUnicode_Check(unicode)) {
6159 PyErr_BadArgument();
6160 return NULL;
6161 }
6162 if (PyUnicode_READY(unicode) < 0)
6163 return NULL;
6164 kind = PyUnicode_KIND(unicode);
6165 data = PyUnicode_DATA(unicode);
6166 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson5944c362011-11-22 19:05:49 -06006167 expandsize = 0;
6168 switch (kind) {
6169 case PyUnicode_1BYTE_KIND:
6170 expandsize = 4;
6171 break;
6172 case PyUnicode_2BYTE_KIND:
6173 expandsize = 6;
6174 break;
6175 case PyUnicode_4BYTE_KIND:
6176 expandsize = 10;
6177 break;
6178 default:
6179 assert(0);
6180 break;
6181 }
Victor Stinner0e368262011-11-10 20:12:49 +01006182
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006183 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006185
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006186 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 if (repr == NULL)
6188 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006190 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006192 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 for (pos = 0; pos < len; pos++) {
6194 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 /* Map 32-bit characters to '\Uxxxxxxxx' */
6196 if (ch >= 0x10000) {
Victor Stinner0d3721d2011-11-22 03:27:53 +01006197 assert(ch <= 0x10FFFF);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006198 *p++ = '\\';
6199 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006200 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6201 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6202 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6203 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6204 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6205 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6206 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6207 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006208 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006209 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006210 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211 *p++ = '\\';
6212 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006213 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6214 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6215 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6216 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006218 /* Copy everything else as-is */
6219 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 *p++ = (char) ch;
6221 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006222
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006223 assert(p > q);
6224 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006225 return NULL;
6226 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227}
6228
Alexander Belopolsky40018472011-02-26 01:02:56 +00006229PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006230PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6231 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006233 PyObject *result;
6234 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6235 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006236 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6238 Py_DECREF(tmp);
6239 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240}
6241
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006242/* --- Unicode Internal Codec ------------------------------------------- */
6243
Alexander Belopolsky40018472011-02-26 01:02:56 +00006244PyObject *
6245_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006246 Py_ssize_t size,
6247 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006248{
6249 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006250 Py_ssize_t startinpos;
6251 Py_ssize_t endinpos;
6252 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006253 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006254 const char *end;
6255 const char *reason;
6256 PyObject *errorHandler = NULL;
6257 PyObject *exc = NULL;
6258
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006259 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006260 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006261 1))
6262 return NULL;
6263
Thomas Wouters89f507f2006-12-13 04:49:30 +00006264 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006265 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006266 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006268 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006269 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006270 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006271 end = s + size;
6272
6273 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006274 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006275 Py_UCS4 ch;
6276 /* We copy the raw representation one byte at a time because the
6277 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006278 ((char *) &uch)[0] = s[0];
6279 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006280#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006281 ((char *) &uch)[2] = s[2];
6282 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006283#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006284 ch = uch;
6285
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006286 /* We have to sanity check the raw data, otherwise doom looms for
6287 some malformed UCS-4 data. */
6288 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006289#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006290 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006291#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006292 end-s < Py_UNICODE_SIZE
6293 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006295 startinpos = s - starts;
6296 if (end-s < Py_UNICODE_SIZE) {
6297 endinpos = end-starts;
6298 reason = "truncated input";
6299 }
6300 else {
6301 endinpos = s - starts + Py_UNICODE_SIZE;
6302 reason = "illegal code point (> 0x10FFFF)";
6303 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006304 if (unicode_decode_call_errorhandler(
6305 errors, &errorHandler,
6306 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006307 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006308 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006309 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006310 continue;
6311 }
6312
6313 s += Py_UNICODE_SIZE;
6314#ifndef Py_UNICODE_WIDE
6315 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6316 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006317 Py_UNICODE uch2;
6318 ((char *) &uch2)[0] = s[0];
6319 ((char *) &uch2)[1] = s[1];
6320 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006321 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006322 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006323 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006324 }
6325 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006326#endif
6327
6328 if (unicode_putchar(&v, &outpos, ch) < 0)
6329 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006330 }
6331
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006332 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 goto onError;
6334 Py_XDECREF(errorHandler);
6335 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006336 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006337
Benjamin Peterson29060642009-01-31 22:14:21 +00006338 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339 Py_XDECREF(v);
6340 Py_XDECREF(errorHandler);
6341 Py_XDECREF(exc);
6342 return NULL;
6343}
6344
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345/* --- Latin-1 Codec ------------------------------------------------------ */
6346
Alexander Belopolsky40018472011-02-26 01:02:56 +00006347PyObject *
6348PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006349 Py_ssize_t size,
6350 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006351{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006352 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006353 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354}
6355
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006357static void
6358make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006359 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006360 PyObject *unicode,
6361 Py_ssize_t startpos, Py_ssize_t endpos,
6362 const char *reason)
6363{
6364 if (*exceptionObject == NULL) {
6365 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006366 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006367 encoding, unicode, startpos, endpos, reason);
6368 }
6369 else {
6370 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6371 goto onError;
6372 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6373 goto onError;
6374 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6375 goto onError;
6376 return;
6377 onError:
6378 Py_DECREF(*exceptionObject);
6379 *exceptionObject = NULL;
6380 }
6381}
6382
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006383/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006384static void
6385raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006386 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006387 PyObject *unicode,
6388 Py_ssize_t startpos, Py_ssize_t endpos,
6389 const char *reason)
6390{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006391 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006392 encoding, unicode, startpos, endpos, reason);
6393 if (*exceptionObject != NULL)
6394 PyCodec_StrictErrors(*exceptionObject);
6395}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006396
6397/* error handling callback helper:
6398 build arguments, call the callback and check the arguments,
6399 put the result into newpos and return the replacement string, which
6400 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006401static PyObject *
6402unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006403 PyObject **errorHandler,
6404 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006405 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006406 Py_ssize_t startpos, Py_ssize_t endpos,
6407 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006409 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006410 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 PyObject *restuple;
6412 PyObject *resunicode;
6413
6414 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 }
6419
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 if (PyUnicode_READY(unicode) < 0)
6421 return NULL;
6422 len = PyUnicode_GET_LENGTH(unicode);
6423
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006424 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006425 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428
6429 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006434 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006435 Py_DECREF(restuple);
6436 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006437 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006438 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006439 &resunicode, newpos)) {
6440 Py_DECREF(restuple);
6441 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006443 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6444 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6445 Py_DECREF(restuple);
6446 return NULL;
6447 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006448 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006449 *newpos = len + *newpos;
6450 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006451 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6452 Py_DECREF(restuple);
6453 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006454 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006455 Py_INCREF(resunicode);
6456 Py_DECREF(restuple);
6457 return resunicode;
6458}
6459
Alexander Belopolsky40018472011-02-26 01:02:56 +00006460static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006461unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006462 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006463 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006465 /* input state */
6466 Py_ssize_t pos=0, size;
6467 int kind;
6468 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 /* output object */
6470 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006471 /* pointer into the output */
6472 char *str;
6473 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006474 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006475 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6476 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006477 PyObject *errorHandler = NULL;
6478 PyObject *exc = NULL;
6479 /* the following variable is used for caching string comparisons
6480 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6481 int known_errorHandler = -1;
6482
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 if (PyUnicode_READY(unicode) < 0)
6484 return NULL;
6485 size = PyUnicode_GET_LENGTH(unicode);
6486 kind = PyUnicode_KIND(unicode);
6487 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006488 /* allocate enough for a simple encoding without
6489 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006490 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006491 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006492 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006494 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006495 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006496 ressize = size;
6497
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006498 while (pos < size) {
6499 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006500
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 /* can we encode this? */
6502 if (c<limit) {
6503 /* no overflow check, because we know that the space is enough */
6504 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006506 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006508 Py_ssize_t requiredsize;
6509 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006512 Py_ssize_t collstart = pos;
6513 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006515 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006516 ++collend;
6517 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6518 if (known_errorHandler==-1) {
6519 if ((errors==NULL) || (!strcmp(errors, "strict")))
6520 known_errorHandler = 1;
6521 else if (!strcmp(errors, "replace"))
6522 known_errorHandler = 2;
6523 else if (!strcmp(errors, "ignore"))
6524 known_errorHandler = 3;
6525 else if (!strcmp(errors, "xmlcharrefreplace"))
6526 known_errorHandler = 4;
6527 else
6528 known_errorHandler = 0;
6529 }
6530 switch (known_errorHandler) {
6531 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006532 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 goto onError;
6534 case 2: /* replace */
6535 while (collstart++<collend)
6536 *str++ = '?'; /* fall through */
6537 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006538 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 break;
6540 case 4: /* xmlcharrefreplace */
6541 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006542 /* determine replacement size */
6543 for (i = collstart, repsize = 0; i < collend; ++i) {
6544 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6545 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006551 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006557 else {
6558 assert(ch <= 0x10FFFF);
Benjamin Peterson29060642009-01-31 22:14:21 +00006559 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006560 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006561 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006562 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006563 if (requiredsize > ressize) {
6564 if (requiredsize<2*ressize)
6565 requiredsize = 2*ressize;
6566 if (_PyBytes_Resize(&res, requiredsize))
6567 goto onError;
6568 str = PyBytes_AS_STRING(res) + respos;
6569 ressize = requiredsize;
6570 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 /* generate replacement */
6572 for (i = collstart; i < collend; ++i) {
6573 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006575 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 break;
6577 default:
6578 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006579 encoding, reason, unicode, &exc,
6580 collstart, collend, &newpos);
6581 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6582 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006584 if (PyBytes_Check(repunicode)) {
6585 /* Directly copy bytes result to output. */
6586 repsize = PyBytes_Size(repunicode);
6587 if (repsize > 1) {
6588 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006589 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006590 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6591 Py_DECREF(repunicode);
6592 goto onError;
6593 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006594 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006595 ressize += repsize-1;
6596 }
6597 memcpy(str, PyBytes_AsString(repunicode), repsize);
6598 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006600 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006601 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006602 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 /* need more space? (at least enough for what we
6604 have+the replacement+the rest of the string, so
6605 we won't have to check space for encodable characters) */
6606 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006607 repsize = PyUnicode_GET_LENGTH(repunicode);
6608 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006609 if (requiredsize > ressize) {
6610 if (requiredsize<2*ressize)
6611 requiredsize = 2*ressize;
6612 if (_PyBytes_Resize(&res, requiredsize)) {
6613 Py_DECREF(repunicode);
6614 goto onError;
6615 }
6616 str = PyBytes_AS_STRING(res) + respos;
6617 ressize = requiredsize;
6618 }
6619 /* check if there is anything unencodable in the replacement
6620 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 for (i = 0; repsize-->0; ++i, ++str) {
6622 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006623 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006624 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006625 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 Py_DECREF(repunicode);
6627 goto onError;
6628 }
6629 *str = (char)c;
6630 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006632 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006633 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006634 }
6635 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006636 /* Resize if we allocated to much */
6637 size = str - PyBytes_AS_STRING(res);
6638 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006639 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006640 if (_PyBytes_Resize(&res, size) < 0)
6641 goto onError;
6642 }
6643
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 Py_XDECREF(errorHandler);
6645 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006646 return res;
6647
6648 onError:
6649 Py_XDECREF(res);
6650 Py_XDECREF(errorHandler);
6651 Py_XDECREF(exc);
6652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653}
6654
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006655/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006656PyObject *
6657PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006658 Py_ssize_t size,
6659 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006660{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006661 PyObject *result;
6662 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6663 if (unicode == NULL)
6664 return NULL;
6665 result = unicode_encode_ucs1(unicode, errors, 256);
6666 Py_DECREF(unicode);
6667 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668}
6669
Alexander Belopolsky40018472011-02-26 01:02:56 +00006670PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006671_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006672{
6673 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 PyErr_BadArgument();
6675 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006677 if (PyUnicode_READY(unicode) == -1)
6678 return NULL;
6679 /* Fast path: if it is a one-byte string, construct
6680 bytes object directly. */
6681 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6682 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6683 PyUnicode_GET_LENGTH(unicode));
6684 /* Non-Latin-1 characters present. Defer to above function to
6685 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006686 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006687}
6688
6689PyObject*
6690PyUnicode_AsLatin1String(PyObject *unicode)
6691{
6692 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006693}
6694
6695/* --- 7-bit ASCII Codec -------------------------------------------------- */
6696
Alexander Belopolsky40018472011-02-26 01:02:56 +00006697PyObject *
6698PyUnicode_DecodeASCII(const char *s,
6699 Py_ssize_t size,
6700 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006701{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006702 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006703 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006704 int kind;
6705 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006706 Py_ssize_t startinpos;
6707 Py_ssize_t endinpos;
6708 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006709 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006710 int has_error;
6711 const unsigned char *p = (const unsigned char *)s;
6712 const unsigned char *end = p + size;
6713 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006714 PyObject *errorHandler = NULL;
6715 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006716
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006717 if (size == 0) {
6718 Py_INCREF(unicode_empty);
6719 return unicode_empty;
6720 }
6721
Guido van Rossumd57fd912000-03-10 22:53:23 +00006722 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006723 if (size == 1 && (unsigned char)s[0] < 128)
6724 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006725
Victor Stinner702c7342011-10-05 13:50:52 +02006726 has_error = 0;
6727 while (p < end && !has_error) {
6728 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6729 an explanation. */
6730 if (!((size_t) p & LONG_PTR_MASK)) {
6731 /* Help register allocation */
6732 register const unsigned char *_p = p;
6733 while (_p < aligned_end) {
6734 unsigned long value = *(unsigned long *) _p;
6735 if (value & ASCII_CHAR_MASK) {
6736 has_error = 1;
6737 break;
6738 }
6739 _p += SIZEOF_LONG;
6740 }
6741 if (_p == end)
6742 break;
6743 if (has_error)
6744 break;
6745 p = _p;
6746 }
6747 if (*p & 0x80) {
6748 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006749 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006750 }
6751 else {
6752 ++p;
6753 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006754 }
Victor Stinner702c7342011-10-05 13:50:52 +02006755 if (!has_error)
6756 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006757
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006758 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006760 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006761 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006762 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006763 kind = PyUnicode_KIND(v);
6764 data = PyUnicode_DATA(v);
6765 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006766 e = s + size;
6767 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 register unsigned char c = (unsigned char)*s;
6769 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006770 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 ++s;
6772 }
6773 else {
6774 startinpos = s-starts;
6775 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 if (unicode_decode_call_errorhandler(
6777 errors, &errorHandler,
6778 "ascii", "ordinal not in range(128)",
6779 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006780 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006781 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006782 kind = PyUnicode_KIND(v);
6783 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006784 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006785 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006786 if (PyUnicode_Resize(&v, outpos) < 0)
6787 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006788 Py_XDECREF(errorHandler);
6789 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006790 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006791 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006792
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006794 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006795 Py_XDECREF(errorHandler);
6796 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006797 return NULL;
6798}
6799
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006800/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006801PyObject *
6802PyUnicode_EncodeASCII(const Py_UNICODE *p,
6803 Py_ssize_t size,
6804 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006806 PyObject *result;
6807 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6808 if (unicode == NULL)
6809 return NULL;
6810 result = unicode_encode_ucs1(unicode, errors, 128);
6811 Py_DECREF(unicode);
6812 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813}
6814
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006816_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006817{
6818 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 PyErr_BadArgument();
6820 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006822 if (PyUnicode_READY(unicode) == -1)
6823 return NULL;
6824 /* Fast path: if it is an ASCII-only string, construct bytes object
6825 directly. Else defer to above function to raise the exception. */
6826 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6827 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6828 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006829 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006830}
6831
6832PyObject *
6833PyUnicode_AsASCIIString(PyObject *unicode)
6834{
6835 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006836}
6837
Victor Stinner99b95382011-07-04 14:23:54 +02006838#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006839
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006840/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006841
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006842#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006843#define NEED_RETRY
6844#endif
6845
Victor Stinner3a50e702011-10-18 21:21:00 +02006846#ifndef WC_ERR_INVALID_CHARS
6847# define WC_ERR_INVALID_CHARS 0x0080
6848#endif
6849
6850static char*
6851code_page_name(UINT code_page, PyObject **obj)
6852{
6853 *obj = NULL;
6854 if (code_page == CP_ACP)
6855 return "mbcs";
6856 if (code_page == CP_UTF7)
6857 return "CP_UTF7";
6858 if (code_page == CP_UTF8)
6859 return "CP_UTF8";
6860
6861 *obj = PyBytes_FromFormat("cp%u", code_page);
6862 if (*obj == NULL)
6863 return NULL;
6864 return PyBytes_AS_STRING(*obj);
6865}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006866
Alexander Belopolsky40018472011-02-26 01:02:56 +00006867static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006868is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869{
6870 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006871 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006872
Victor Stinner3a50e702011-10-18 21:21:00 +02006873 if (!IsDBCSLeadByteEx(code_page, *curr))
6874 return 0;
6875
6876 prev = CharPrevExA(code_page, s, curr, 0);
6877 if (prev == curr)
6878 return 1;
6879 /* FIXME: This code is limited to "true" double-byte encodings,
6880 as it assumes an incomplete character consists of a single
6881 byte. */
6882 if (curr - prev == 2)
6883 return 1;
6884 if (!IsDBCSLeadByteEx(code_page, *prev))
6885 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006886 return 0;
6887}
6888
Victor Stinner3a50e702011-10-18 21:21:00 +02006889static DWORD
6890decode_code_page_flags(UINT code_page)
6891{
6892 if (code_page == CP_UTF7) {
6893 /* The CP_UTF7 decoder only supports flags=0 */
6894 return 0;
6895 }
6896 else
6897 return MB_ERR_INVALID_CHARS;
6898}
6899
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006900/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006901 * Decode a byte string from a Windows code page into unicode object in strict
6902 * mode.
6903 *
6904 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6905 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006906 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006907static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006908decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006909 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006910 const char *in,
6911 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006912{
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006914 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006915 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006916
6917 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006918 assert(insize > 0);
6919 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6920 if (outsize <= 0)
6921 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006922
6923 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006924 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006925 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006926 if (*v == NULL)
6927 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006928 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006929 }
6930 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006931 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006932 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006933 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006935 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006936 }
6937
6938 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006939 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6940 if (outsize <= 0)
6941 goto error;
6942 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006943
Victor Stinner3a50e702011-10-18 21:21:00 +02006944error:
6945 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6946 return -2;
6947 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006948 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006949}
6950
Victor Stinner3a50e702011-10-18 21:21:00 +02006951/*
6952 * Decode a byte string from a code page into unicode object with an error
6953 * handler.
6954 *
6955 * Returns consumed size if succeed, or raise a WindowsError or
6956 * UnicodeDecodeError exception and returns -1 on error.
6957 */
6958static int
6959decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006960 PyObject **v,
6961 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006962 const char *errors)
6963{
6964 const char *startin = in;
6965 const char *endin = in + size;
6966 const DWORD flags = decode_code_page_flags(code_page);
6967 /* Ideally, we should get reason from FormatMessage. This is the Windows
6968 2000 English version of the message. */
6969 const char *reason = "No mapping for the Unicode character exists "
6970 "in the target code page.";
6971 /* each step cannot decode more than 1 character, but a character can be
6972 represented as a surrogate pair */
6973 wchar_t buffer[2], *startout, *out;
6974 int insize, outsize;
6975 PyObject *errorHandler = NULL;
6976 PyObject *exc = NULL;
6977 PyObject *encoding_obj = NULL;
6978 char *encoding;
6979 DWORD err;
6980 int ret = -1;
6981
6982 assert(size > 0);
6983
6984 encoding = code_page_name(code_page, &encoding_obj);
6985 if (encoding == NULL)
6986 return -1;
6987
6988 if (errors == NULL || strcmp(errors, "strict") == 0) {
6989 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6990 UnicodeDecodeError. */
6991 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6992 if (exc != NULL) {
6993 PyCodec_StrictErrors(exc);
6994 Py_CLEAR(exc);
6995 }
6996 goto error;
6997 }
6998
6999 if (*v == NULL) {
7000 /* Create unicode object */
7001 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7002 PyErr_NoMemory();
7003 goto error;
7004 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007005 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007006 if (*v == NULL)
7007 goto error;
7008 startout = PyUnicode_AS_UNICODE(*v);
7009 }
7010 else {
7011 /* Extend unicode object */
7012 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7013 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7014 PyErr_NoMemory();
7015 goto error;
7016 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007017 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007018 goto error;
7019 startout = PyUnicode_AS_UNICODE(*v) + n;
7020 }
7021
7022 /* Decode the byte string character per character */
7023 out = startout;
7024 while (in < endin)
7025 {
7026 /* Decode a character */
7027 insize = 1;
7028 do
7029 {
7030 outsize = MultiByteToWideChar(code_page, flags,
7031 in, insize,
7032 buffer, Py_ARRAY_LENGTH(buffer));
7033 if (outsize > 0)
7034 break;
7035 err = GetLastError();
7036 if (err != ERROR_NO_UNICODE_TRANSLATION
7037 && err != ERROR_INSUFFICIENT_BUFFER)
7038 {
7039 PyErr_SetFromWindowsErr(0);
7040 goto error;
7041 }
7042 insize++;
7043 }
7044 /* 4=maximum length of a UTF-8 sequence */
7045 while (insize <= 4 && (in + insize) <= endin);
7046
7047 if (outsize <= 0) {
7048 Py_ssize_t startinpos, endinpos, outpos;
7049
7050 startinpos = in - startin;
7051 endinpos = startinpos + 1;
7052 outpos = out - PyUnicode_AS_UNICODE(*v);
7053 if (unicode_decode_call_errorhandler(
7054 errors, &errorHandler,
7055 encoding, reason,
7056 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007057 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007058 {
7059 goto error;
7060 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007061 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007062 }
7063 else {
7064 in += insize;
7065 memcpy(out, buffer, outsize * sizeof(wchar_t));
7066 out += outsize;
7067 }
7068 }
7069
7070 /* write a NUL character at the end */
7071 *out = 0;
7072
7073 /* Extend unicode object */
7074 outsize = out - startout;
7075 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007076 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007078 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007079
7080error:
7081 Py_XDECREF(encoding_obj);
7082 Py_XDECREF(errorHandler);
7083 Py_XDECREF(exc);
7084 return ret;
7085}
7086
Victor Stinner3a50e702011-10-18 21:21:00 +02007087static PyObject *
7088decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007089 const char *s, Py_ssize_t size,
7090 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091{
Victor Stinner76a31a62011-11-04 00:05:13 +01007092 PyObject *v = NULL;
7093 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007094
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 if (code_page < 0) {
7096 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7097 return NULL;
7098 }
7099
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007100 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007101 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102
Victor Stinner76a31a62011-11-04 00:05:13 +01007103 do
7104 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007106 if (size > INT_MAX) {
7107 chunk_size = INT_MAX;
7108 final = 0;
7109 done = 0;
7110 }
7111 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007113 {
7114 chunk_size = (int)size;
7115 final = (consumed == NULL);
7116 done = 1;
7117 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118
Victor Stinner76a31a62011-11-04 00:05:13 +01007119 /* Skip trailing lead-byte unless 'final' is set */
7120 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7121 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007122
Victor Stinner76a31a62011-11-04 00:05:13 +01007123 if (chunk_size == 0 && done) {
7124 if (v != NULL)
7125 break;
7126 Py_INCREF(unicode_empty);
7127 return unicode_empty;
7128 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007129
Victor Stinner76a31a62011-11-04 00:05:13 +01007130
7131 converted = decode_code_page_strict(code_page, &v,
7132 s, chunk_size);
7133 if (converted == -2)
7134 converted = decode_code_page_errors(code_page, &v,
7135 s, chunk_size,
7136 errors);
7137 assert(converted != 0);
7138
7139 if (converted < 0) {
7140 Py_XDECREF(v);
7141 return NULL;
7142 }
7143
7144 if (consumed)
7145 *consumed += converted;
7146
7147 s += converted;
7148 size -= converted;
7149 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007150
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007151 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007152}
7153
Alexander Belopolsky40018472011-02-26 01:02:56 +00007154PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007155PyUnicode_DecodeCodePageStateful(int code_page,
7156 const char *s,
7157 Py_ssize_t size,
7158 const char *errors,
7159 Py_ssize_t *consumed)
7160{
7161 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7162}
7163
7164PyObject *
7165PyUnicode_DecodeMBCSStateful(const char *s,
7166 Py_ssize_t size,
7167 const char *errors,
7168 Py_ssize_t *consumed)
7169{
7170 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7171}
7172
7173PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007174PyUnicode_DecodeMBCS(const char *s,
7175 Py_ssize_t size,
7176 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007177{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007178 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7179}
7180
Victor Stinner3a50e702011-10-18 21:21:00 +02007181static DWORD
7182encode_code_page_flags(UINT code_page, const char *errors)
7183{
7184 if (code_page == CP_UTF8) {
7185 if (winver.dwMajorVersion >= 6)
7186 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7187 and later */
7188 return WC_ERR_INVALID_CHARS;
7189 else
7190 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7191 return 0;
7192 }
7193 else if (code_page == CP_UTF7) {
7194 /* CP_UTF7 only supports flags=0 */
7195 return 0;
7196 }
7197 else {
7198 if (errors != NULL && strcmp(errors, "replace") == 0)
7199 return 0;
7200 else
7201 return WC_NO_BEST_FIT_CHARS;
7202 }
7203}
7204
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007205/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 * Encode a Unicode string to a Windows code page into a byte string in strict
7207 * mode.
7208 *
7209 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7210 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007212static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007213encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007214 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007216{
Victor Stinner554f3f02010-06-16 23:33:54 +00007217 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 BOOL *pusedDefaultChar = &usedDefaultChar;
7219 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007220 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007221 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 const DWORD flags = encode_code_page_flags(code_page, NULL);
7224 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007225 /* Create a substring so that we can get the UTF-16 representation
7226 of just the slice under consideration. */
7227 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007228
Martin v. Löwis3d325192011-11-04 18:23:06 +01007229 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007232 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007234 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007235
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 substring = PyUnicode_Substring(unicode, offset, offset+len);
7237 if (substring == NULL)
7238 return -1;
7239 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7240 if (p == NULL) {
7241 Py_DECREF(substring);
7242 return -1;
7243 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007244
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007245 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 outsize = WideCharToMultiByte(code_page, flags,
7247 p, size,
7248 NULL, 0,
7249 NULL, pusedDefaultChar);
7250 if (outsize <= 0)
7251 goto error;
7252 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 if (pusedDefaultChar && *pusedDefaultChar) {
7254 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007256 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007257
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007259 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007261 if (*outbytes == NULL) {
7262 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007263 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007264 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266 }
7267 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007268 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 const Py_ssize_t n = PyBytes_Size(*outbytes);
7270 if (outsize > PY_SSIZE_T_MAX - n) {
7271 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007272 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007273 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007274 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007275 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7276 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007277 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007278 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007279 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007280 }
7281
7282 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 outsize = WideCharToMultiByte(code_page, flags,
7284 p, size,
7285 out, outsize,
7286 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007287 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007288 if (outsize <= 0)
7289 goto error;
7290 if (pusedDefaultChar && *pusedDefaultChar)
7291 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007293
Victor Stinner3a50e702011-10-18 21:21:00 +02007294error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007295 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007296 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7297 return -2;
7298 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007299 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007300}
7301
Victor Stinner3a50e702011-10-18 21:21:00 +02007302/*
7303 * Encode a Unicode string to a Windows code page into a byte string using a
7304 * error handler.
7305 *
7306 * Returns consumed characters if succeed, or raise a WindowsError and returns
7307 * -1 on other error.
7308 */
7309static int
7310encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007311 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007312 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007313{
Victor Stinner3a50e702011-10-18 21:21:00 +02007314 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007315 Py_ssize_t pos = unicode_offset;
7316 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 /* Ideally, we should get reason from FormatMessage. This is the Windows
7318 2000 English version of the message. */
7319 const char *reason = "invalid character";
7320 /* 4=maximum length of a UTF-8 sequence */
7321 char buffer[4];
7322 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7323 Py_ssize_t outsize;
7324 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007325 PyObject *errorHandler = NULL;
7326 PyObject *exc = NULL;
7327 PyObject *encoding_obj = NULL;
7328 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007329 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 PyObject *rep;
7331 int ret = -1;
7332
7333 assert(insize > 0);
7334
7335 encoding = code_page_name(code_page, &encoding_obj);
7336 if (encoding == NULL)
7337 return -1;
7338
7339 if (errors == NULL || strcmp(errors, "strict") == 0) {
7340 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7341 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007342 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 if (exc != NULL) {
7344 PyCodec_StrictErrors(exc);
7345 Py_DECREF(exc);
7346 }
7347 Py_XDECREF(encoding_obj);
7348 return -1;
7349 }
7350
7351 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7352 pusedDefaultChar = &usedDefaultChar;
7353 else
7354 pusedDefaultChar = NULL;
7355
7356 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7357 PyErr_NoMemory();
7358 goto error;
7359 }
7360 outsize = insize * Py_ARRAY_LENGTH(buffer);
7361
7362 if (*outbytes == NULL) {
7363 /* Create string object */
7364 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7365 if (*outbytes == NULL)
7366 goto error;
7367 out = PyBytes_AS_STRING(*outbytes);
7368 }
7369 else {
7370 /* Extend string object */
7371 Py_ssize_t n = PyBytes_Size(*outbytes);
7372 if (n > PY_SSIZE_T_MAX - outsize) {
7373 PyErr_NoMemory();
7374 goto error;
7375 }
7376 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7377 goto error;
7378 out = PyBytes_AS_STRING(*outbytes) + n;
7379 }
7380
7381 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007382 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7385 wchar_t chars[2];
7386 int charsize;
7387 if (ch < 0x10000) {
7388 chars[0] = (wchar_t)ch;
7389 charsize = 1;
7390 }
7391 else {
7392 ch -= 0x10000;
7393 chars[0] = 0xd800 + (ch >> 10);
7394 chars[1] = 0xdc00 + (ch & 0x3ff);
7395 charsize = 2;
7396 }
7397
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007399 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 buffer, Py_ARRAY_LENGTH(buffer),
7401 NULL, pusedDefaultChar);
7402 if (outsize > 0) {
7403 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7404 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 memcpy(out, buffer, outsize);
7407 out += outsize;
7408 continue;
7409 }
7410 }
7411 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7412 PyErr_SetFromWindowsErr(0);
7413 goto error;
7414 }
7415
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 rep = unicode_encode_call_errorhandler(
7417 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007418 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007419 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 if (rep == NULL)
7421 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007422 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007423
7424 if (PyBytes_Check(rep)) {
7425 outsize = PyBytes_GET_SIZE(rep);
7426 if (outsize != 1) {
7427 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7428 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7429 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7430 Py_DECREF(rep);
7431 goto error;
7432 }
7433 out = PyBytes_AS_STRING(*outbytes) + offset;
7434 }
7435 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7436 out += outsize;
7437 }
7438 else {
7439 Py_ssize_t i;
7440 enum PyUnicode_Kind kind;
7441 void *data;
7442
7443 if (PyUnicode_READY(rep) < 0) {
7444 Py_DECREF(rep);
7445 goto error;
7446 }
7447
7448 outsize = PyUnicode_GET_LENGTH(rep);
7449 if (outsize != 1) {
7450 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7451 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7452 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7453 Py_DECREF(rep);
7454 goto error;
7455 }
7456 out = PyBytes_AS_STRING(*outbytes) + offset;
7457 }
7458 kind = PyUnicode_KIND(rep);
7459 data = PyUnicode_DATA(rep);
7460 for (i=0; i < outsize; i++) {
7461 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7462 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007463 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007464 encoding, unicode,
7465 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 "unable to encode error handler result to ASCII");
7467 Py_DECREF(rep);
7468 goto error;
7469 }
7470 *out = (unsigned char)ch;
7471 out++;
7472 }
7473 }
7474 Py_DECREF(rep);
7475 }
7476 /* write a NUL byte */
7477 *out = 0;
7478 outsize = out - PyBytes_AS_STRING(*outbytes);
7479 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7480 if (_PyBytes_Resize(outbytes, outsize) < 0)
7481 goto error;
7482 ret = 0;
7483
7484error:
7485 Py_XDECREF(encoding_obj);
7486 Py_XDECREF(errorHandler);
7487 Py_XDECREF(exc);
7488 return ret;
7489}
7490
Victor Stinner3a50e702011-10-18 21:21:00 +02007491static PyObject *
7492encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007493 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 const char *errors)
7495{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007496 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007498 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007499 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007500
Victor Stinner2fc507f2011-11-04 20:06:39 +01007501 if (PyUnicode_READY(unicode) < 0)
7502 return NULL;
7503 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007504
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 if (code_page < 0) {
7506 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7507 return NULL;
7508 }
7509
Martin v. Löwis3d325192011-11-04 18:23:06 +01007510 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007511 return PyBytes_FromStringAndSize(NULL, 0);
7512
Victor Stinner7581cef2011-11-03 22:32:33 +01007513 offset = 0;
7514 do
7515 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007516#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007517 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007518 chunks. */
7519 if (len > INT_MAX/2) {
7520 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007521 done = 0;
7522 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007523 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007524#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007525 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007526 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007527 done = 1;
7528 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007529
Victor Stinner76a31a62011-11-04 00:05:13 +01007530 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007532 errors);
7533 if (ret == -2)
7534 ret = encode_code_page_errors(code_page, &outbytes,
7535 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007536 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007537 if (ret < 0) {
7538 Py_XDECREF(outbytes);
7539 return NULL;
7540 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007541
Victor Stinner7581cef2011-11-03 22:32:33 +01007542 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007543 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007544 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007545
Victor Stinner3a50e702011-10-18 21:21:00 +02007546 return outbytes;
7547}
7548
7549PyObject *
7550PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7551 Py_ssize_t size,
7552 const char *errors)
7553{
Victor Stinner7581cef2011-11-03 22:32:33 +01007554 PyObject *unicode, *res;
7555 unicode = PyUnicode_FromUnicode(p, size);
7556 if (unicode == NULL)
7557 return NULL;
7558 res = encode_code_page(CP_ACP, unicode, errors);
7559 Py_DECREF(unicode);
7560 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007561}
7562
7563PyObject *
7564PyUnicode_EncodeCodePage(int code_page,
7565 PyObject *unicode,
7566 const char *errors)
7567{
Victor Stinner7581cef2011-11-03 22:32:33 +01007568 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007569}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007570
Alexander Belopolsky40018472011-02-26 01:02:56 +00007571PyObject *
7572PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007573{
7574 if (!PyUnicode_Check(unicode)) {
7575 PyErr_BadArgument();
7576 return NULL;
7577 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007578 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007579}
7580
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007581#undef NEED_RETRY
7582
Victor Stinner99b95382011-07-04 14:23:54 +02007583#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007584
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585/* --- Character Mapping Codec -------------------------------------------- */
7586
Alexander Belopolsky40018472011-02-26 01:02:56 +00007587PyObject *
7588PyUnicode_DecodeCharmap(const char *s,
7589 Py_ssize_t size,
7590 PyObject *mapping,
7591 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007592{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007593 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007594 Py_ssize_t startinpos;
7595 Py_ssize_t endinpos;
7596 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007597 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007598 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007599 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007600 PyObject *errorHandler = NULL;
7601 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007602
Guido van Rossumd57fd912000-03-10 22:53:23 +00007603 /* Default to Latin-1 */
7604 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007606
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007607 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007608 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007609 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007610 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007611 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007612 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007613 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007614 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007615 Py_ssize_t maplen;
7616 enum PyUnicode_Kind kind;
7617 void *data;
7618 Py_UCS4 x;
7619
7620 if (PyUnicode_READY(mapping) < 0)
7621 return NULL;
7622
7623 maplen = PyUnicode_GET_LENGTH(mapping);
7624 data = PyUnicode_DATA(mapping);
7625 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 while (s < e) {
7627 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007628
Benjamin Peterson29060642009-01-31 22:14:21 +00007629 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007630 x = PyUnicode_READ(kind, data, ch);
7631 else
7632 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007633
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007634 if (x == 0xfffe)
7635 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007637 startinpos = s-starts;
7638 endinpos = startinpos+1;
7639 if (unicode_decode_call_errorhandler(
7640 errors, &errorHandler,
7641 "charmap", "character maps to <undefined>",
7642 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007643 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007644 goto onError;
7645 }
7646 continue;
7647 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007648
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007649 if (unicode_putchar(&v, &outpos, x) < 0)
7650 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007651 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007652 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007653 }
7654 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 while (s < e) {
7656 unsigned char ch = *s;
7657 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007658
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7660 w = PyLong_FromLong((long)ch);
7661 if (w == NULL)
7662 goto onError;
7663 x = PyObject_GetItem(mapping, w);
7664 Py_DECREF(w);
7665 if (x == NULL) {
7666 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7667 /* No mapping found means: mapping is undefined. */
7668 PyErr_Clear();
7669 x = Py_None;
7670 Py_INCREF(x);
7671 } else
7672 goto onError;
7673 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007674
Benjamin Peterson29060642009-01-31 22:14:21 +00007675 /* Apply mapping */
7676 if (PyLong_Check(x)) {
7677 long value = PyLong_AS_LONG(x);
7678 if (value < 0 || value > 65535) {
7679 PyErr_SetString(PyExc_TypeError,
7680 "character mapping must be in range(65536)");
7681 Py_DECREF(x);
7682 goto onError;
7683 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007684 if (unicode_putchar(&v, &outpos, value) < 0)
7685 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007686 }
7687 else if (x == Py_None) {
7688 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007689 startinpos = s-starts;
7690 endinpos = startinpos+1;
7691 if (unicode_decode_call_errorhandler(
7692 errors, &errorHandler,
7693 "charmap", "character maps to <undefined>",
7694 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007695 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007696 Py_DECREF(x);
7697 goto onError;
7698 }
7699 Py_DECREF(x);
7700 continue;
7701 }
7702 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007703 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007704
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007705 if (PyUnicode_READY(x) < 0)
7706 goto onError;
7707 targetsize = PyUnicode_GET_LENGTH(x);
7708
7709 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007711 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007712 PyUnicode_READ_CHAR(x, 0)) < 0)
7713 goto onError;
7714 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007715 else if (targetsize > 1) {
7716 /* 1-n mapping */
7717 if (targetsize > extrachars) {
7718 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 Py_ssize_t needed = (targetsize - extrachars) + \
7720 (targetsize << 2);
7721 extrachars += needed;
7722 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007723 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007724 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007725 Py_DECREF(x);
7726 goto onError;
7727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007728 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007729 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7730 goto onError;
7731 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7732 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007733 extrachars -= targetsize;
7734 }
7735 /* 1-0 mapping: skip the character */
7736 }
7737 else {
7738 /* wrong return value */
7739 PyErr_SetString(PyExc_TypeError,
7740 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007741 Py_DECREF(x);
7742 goto onError;
7743 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007744 Py_DECREF(x);
7745 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007746 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007748 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007749 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007750 Py_XDECREF(errorHandler);
7751 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007752 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007753
Benjamin Peterson29060642009-01-31 22:14:21 +00007754 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007755 Py_XDECREF(errorHandler);
7756 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007757 Py_XDECREF(v);
7758 return NULL;
7759}
7760
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007761/* Charmap encoding: the lookup table */
7762
Alexander Belopolsky40018472011-02-26 01:02:56 +00007763struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 PyObject_HEAD
7765 unsigned char level1[32];
7766 int count2, count3;
7767 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768};
7769
7770static PyObject*
7771encoding_map_size(PyObject *obj, PyObject* args)
7772{
7773 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007774 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007776}
7777
7778static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007779 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007780 PyDoc_STR("Return the size (in bytes) of this object") },
7781 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007782};
7783
7784static void
7785encoding_map_dealloc(PyObject* o)
7786{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007787 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007788}
7789
7790static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007791 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007792 "EncodingMap", /*tp_name*/
7793 sizeof(struct encoding_map), /*tp_basicsize*/
7794 0, /*tp_itemsize*/
7795 /* methods */
7796 encoding_map_dealloc, /*tp_dealloc*/
7797 0, /*tp_print*/
7798 0, /*tp_getattr*/
7799 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007800 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007801 0, /*tp_repr*/
7802 0, /*tp_as_number*/
7803 0, /*tp_as_sequence*/
7804 0, /*tp_as_mapping*/
7805 0, /*tp_hash*/
7806 0, /*tp_call*/
7807 0, /*tp_str*/
7808 0, /*tp_getattro*/
7809 0, /*tp_setattro*/
7810 0, /*tp_as_buffer*/
7811 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7812 0, /*tp_doc*/
7813 0, /*tp_traverse*/
7814 0, /*tp_clear*/
7815 0, /*tp_richcompare*/
7816 0, /*tp_weaklistoffset*/
7817 0, /*tp_iter*/
7818 0, /*tp_iternext*/
7819 encoding_map_methods, /*tp_methods*/
7820 0, /*tp_members*/
7821 0, /*tp_getset*/
7822 0, /*tp_base*/
7823 0, /*tp_dict*/
7824 0, /*tp_descr_get*/
7825 0, /*tp_descr_set*/
7826 0, /*tp_dictoffset*/
7827 0, /*tp_init*/
7828 0, /*tp_alloc*/
7829 0, /*tp_new*/
7830 0, /*tp_free*/
7831 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007832};
7833
7834PyObject*
7835PyUnicode_BuildEncodingMap(PyObject* string)
7836{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007837 PyObject *result;
7838 struct encoding_map *mresult;
7839 int i;
7840 int need_dict = 0;
7841 unsigned char level1[32];
7842 unsigned char level2[512];
7843 unsigned char *mlevel1, *mlevel2, *mlevel3;
7844 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007845 int kind;
7846 void *data;
7847 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007848
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007849 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007850 PyErr_BadArgument();
7851 return NULL;
7852 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007853 kind = PyUnicode_KIND(string);
7854 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007855 memset(level1, 0xFF, sizeof level1);
7856 memset(level2, 0xFF, sizeof level2);
7857
7858 /* If there isn't a one-to-one mapping of NULL to \0,
7859 or if there are non-BMP characters, we need to use
7860 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007861 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007862 need_dict = 1;
7863 for (i = 1; i < 256; i++) {
7864 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007865 ch = PyUnicode_READ(kind, data, i);
7866 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007867 need_dict = 1;
7868 break;
7869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007870 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871 /* unmapped character */
7872 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007873 l1 = ch >> 11;
7874 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 if (level1[l1] == 0xFF)
7876 level1[l1] = count2++;
7877 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007878 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007879 }
7880
7881 if (count2 >= 0xFF || count3 >= 0xFF)
7882 need_dict = 1;
7883
7884 if (need_dict) {
7885 PyObject *result = PyDict_New();
7886 PyObject *key, *value;
7887 if (!result)
7888 return NULL;
7889 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007890 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007891 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 if (!key || !value)
7893 goto failed1;
7894 if (PyDict_SetItem(result, key, value) == -1)
7895 goto failed1;
7896 Py_DECREF(key);
7897 Py_DECREF(value);
7898 }
7899 return result;
7900 failed1:
7901 Py_XDECREF(key);
7902 Py_XDECREF(value);
7903 Py_DECREF(result);
7904 return NULL;
7905 }
7906
7907 /* Create a three-level trie */
7908 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7909 16*count2 + 128*count3 - 1);
7910 if (!result)
7911 return PyErr_NoMemory();
7912 PyObject_Init(result, &EncodingMapType);
7913 mresult = (struct encoding_map*)result;
7914 mresult->count2 = count2;
7915 mresult->count3 = count3;
7916 mlevel1 = mresult->level1;
7917 mlevel2 = mresult->level23;
7918 mlevel3 = mresult->level23 + 16*count2;
7919 memcpy(mlevel1, level1, 32);
7920 memset(mlevel2, 0xFF, 16*count2);
7921 memset(mlevel3, 0, 128*count3);
7922 count3 = 0;
7923 for (i = 1; i < 256; i++) {
7924 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007925 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007926 /* unmapped character */
7927 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007928 o1 = PyUnicode_READ(kind, data, i)>>11;
7929 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930 i2 = 16*mlevel1[o1] + o2;
7931 if (mlevel2[i2] == 0xFF)
7932 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007933 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934 i3 = 128*mlevel2[i2] + o3;
7935 mlevel3[i3] = i;
7936 }
7937 return result;
7938}
7939
7940static int
Victor Stinner22168992011-11-20 17:09:18 +01007941encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942{
7943 struct encoding_map *map = (struct encoding_map*)mapping;
7944 int l1 = c>>11;
7945 int l2 = (c>>7) & 0xF;
7946 int l3 = c & 0x7F;
7947 int i;
7948
Victor Stinner22168992011-11-20 17:09:18 +01007949 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007950 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007951 if (c == 0)
7952 return 0;
7953 /* level 1*/
7954 i = map->level1[l1];
7955 if (i == 0xFF) {
7956 return -1;
7957 }
7958 /* level 2*/
7959 i = map->level23[16*i+l2];
7960 if (i == 0xFF) {
7961 return -1;
7962 }
7963 /* level 3 */
7964 i = map->level23[16*map->count2 + 128*i + l3];
7965 if (i == 0) {
7966 return -1;
7967 }
7968 return i;
7969}
7970
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007971/* Lookup the character ch in the mapping. If the character
7972 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007973 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007974static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007975charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976{
Christian Heimes217cfd12007-12-02 14:31:20 +00007977 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978 PyObject *x;
7979
7980 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007982 x = PyObject_GetItem(mapping, w);
7983 Py_DECREF(w);
7984 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007985 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7986 /* No mapping found means: mapping is undefined. */
7987 PyErr_Clear();
7988 x = Py_None;
7989 Py_INCREF(x);
7990 return x;
7991 } else
7992 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007994 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007996 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 long value = PyLong_AS_LONG(x);
7998 if (value < 0 || value > 255) {
7999 PyErr_SetString(PyExc_TypeError,
8000 "character mapping must be in range(256)");
8001 Py_DECREF(x);
8002 return NULL;
8003 }
8004 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008006 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008007 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008008 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008009 /* wrong return value */
8010 PyErr_Format(PyExc_TypeError,
8011 "character mapping must return integer, bytes or None, not %.400s",
8012 x->ob_type->tp_name);
8013 Py_DECREF(x);
8014 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015 }
8016}
8017
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008018static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008019charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008021 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8022 /* exponentially overallocate to minimize reallocations */
8023 if (requiredsize < 2*outsize)
8024 requiredsize = 2*outsize;
8025 if (_PyBytes_Resize(outobj, requiredsize))
8026 return -1;
8027 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028}
8029
Benjamin Peterson14339b62009-01-31 16:36:08 +00008030typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008032} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008033/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008034 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008035 space is available. Return a new reference to the object that
8036 was put in the output buffer, or Py_None, if the mapping was undefined
8037 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008038 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008039static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008040charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008041 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043 PyObject *rep;
8044 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008045 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008046
Christian Heimes90aa7642007-12-19 02:45:37 +00008047 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008048 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 if (res == -1)
8051 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 if (outsize<requiredsize)
8053 if (charmapencode_resize(outobj, outpos, requiredsize))
8054 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008055 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 outstart[(*outpos)++] = (char)res;
8057 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008058 }
8059
8060 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008061 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008064 Py_DECREF(rep);
8065 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008066 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 if (PyLong_Check(rep)) {
8068 Py_ssize_t requiredsize = *outpos+1;
8069 if (outsize<requiredsize)
8070 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8071 Py_DECREF(rep);
8072 return enc_EXCEPTION;
8073 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008074 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008076 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 else {
8078 const char *repchars = PyBytes_AS_STRING(rep);
8079 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8080 Py_ssize_t requiredsize = *outpos+repsize;
8081 if (outsize<requiredsize)
8082 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8083 Py_DECREF(rep);
8084 return enc_EXCEPTION;
8085 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008086 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 memcpy(outstart + *outpos, repchars, repsize);
8088 *outpos += repsize;
8089 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008090 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091 Py_DECREF(rep);
8092 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008093}
8094
8095/* handle an error in PyUnicode_EncodeCharmap
8096 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008097static int
8098charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008099 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008100 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008101 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008102 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103{
8104 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008105 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008106 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008107 enum PyUnicode_Kind kind;
8108 void *data;
8109 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008111 Py_ssize_t collstartpos = *inpos;
8112 Py_ssize_t collendpos = *inpos+1;
8113 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008114 char *encoding = "charmap";
8115 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008117 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008118 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008119
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008120 if (PyUnicode_READY(unicode) < 0)
8121 return -1;
8122 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008123 /* find all unencodable characters */
8124 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008125 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008126 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008127 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008128 val = encoding_map_lookup(ch, mapping);
8129 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 break;
8131 ++collendpos;
8132 continue;
8133 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008134
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008135 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8136 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 if (rep==NULL)
8138 return -1;
8139 else if (rep!=Py_None) {
8140 Py_DECREF(rep);
8141 break;
8142 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008143 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008145 }
8146 /* cache callback name lookup
8147 * (if not done yet, i.e. it's the first error) */
8148 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 if ((errors==NULL) || (!strcmp(errors, "strict")))
8150 *known_errorHandler = 1;
8151 else if (!strcmp(errors, "replace"))
8152 *known_errorHandler = 2;
8153 else if (!strcmp(errors, "ignore"))
8154 *known_errorHandler = 3;
8155 else if (!strcmp(errors, "xmlcharrefreplace"))
8156 *known_errorHandler = 4;
8157 else
8158 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008159 }
8160 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008161 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008162 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008163 return -1;
8164 case 2: /* replace */
8165 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 x = charmapencode_output('?', mapping, res, respos);
8167 if (x==enc_EXCEPTION) {
8168 return -1;
8169 }
8170 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008171 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 return -1;
8173 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008174 }
8175 /* fall through */
8176 case 3: /* ignore */
8177 *inpos = collendpos;
8178 break;
8179 case 4: /* xmlcharrefreplace */
8180 /* generate replacement (temporarily (mis)uses p) */
8181 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 char buffer[2+29+1+1];
8183 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008184 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 for (cp = buffer; *cp; ++cp) {
8186 x = charmapencode_output(*cp, mapping, res, respos);
8187 if (x==enc_EXCEPTION)
8188 return -1;
8189 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008190 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 return -1;
8192 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008193 }
8194 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008195 *inpos = collendpos;
8196 break;
8197 default:
8198 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008199 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008201 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008203 if (PyBytes_Check(repunicode)) {
8204 /* Directly copy bytes result to output. */
8205 Py_ssize_t outsize = PyBytes_Size(*res);
8206 Py_ssize_t requiredsize;
8207 repsize = PyBytes_Size(repunicode);
8208 requiredsize = *respos + repsize;
8209 if (requiredsize > outsize)
8210 /* Make room for all additional bytes. */
8211 if (charmapencode_resize(res, respos, requiredsize)) {
8212 Py_DECREF(repunicode);
8213 return -1;
8214 }
8215 memcpy(PyBytes_AsString(*res) + *respos,
8216 PyBytes_AsString(repunicode), repsize);
8217 *respos += repsize;
8218 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008219 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008220 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008221 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008222 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008223 if (PyUnicode_READY(repunicode) < 0) {
8224 Py_DECREF(repunicode);
8225 return -1;
8226 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008227 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008228 data = PyUnicode_DATA(repunicode);
8229 kind = PyUnicode_KIND(repunicode);
8230 for (index = 0; index < repsize; index++) {
8231 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8232 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008234 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 return -1;
8236 }
8237 else if (x==enc_FAILED) {
8238 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008239 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 return -1;
8241 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008242 }
8243 *inpos = newpos;
8244 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008245 }
8246 return 0;
8247}
8248
Alexander Belopolsky40018472011-02-26 01:02:56 +00008249PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250_PyUnicode_EncodeCharmap(PyObject *unicode,
8251 PyObject *mapping,
8252 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008254 /* output object */
8255 PyObject *res = NULL;
8256 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008257 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008258 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008260 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 PyObject *errorHandler = NULL;
8262 PyObject *exc = NULL;
8263 /* the following variable is used for caching string comparisons
8264 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8265 * 3=ignore, 4=xmlcharrefreplace */
8266 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008268 if (PyUnicode_READY(unicode) < 0)
8269 return NULL;
8270 size = PyUnicode_GET_LENGTH(unicode);
8271
Guido van Rossumd57fd912000-03-10 22:53:23 +00008272 /* Default to Latin-1 */
8273 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008274 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008275
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 /* allocate enough for a simple encoding without
8277 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008278 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279 if (res == NULL)
8280 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008281 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008283
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008287 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 if (x==enc_EXCEPTION) /* error */
8289 goto onError;
8290 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008291 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 &exc,
8293 &known_errorHandler, &errorHandler, errors,
8294 &res, &respos)) {
8295 goto onError;
8296 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008297 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 else
8299 /* done with this character => adjust input position */
8300 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008302
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008304 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008305 if (_PyBytes_Resize(&res, respos) < 0)
8306 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008307
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 Py_XDECREF(exc);
8309 Py_XDECREF(errorHandler);
8310 return res;
8311
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008313 Py_XDECREF(res);
8314 Py_XDECREF(exc);
8315 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008316 return NULL;
8317}
8318
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008319/* Deprecated */
8320PyObject *
8321PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8322 Py_ssize_t size,
8323 PyObject *mapping,
8324 const char *errors)
8325{
8326 PyObject *result;
8327 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8328 if (unicode == NULL)
8329 return NULL;
8330 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8331 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008332 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008333}
8334
Alexander Belopolsky40018472011-02-26 01:02:56 +00008335PyObject *
8336PyUnicode_AsCharmapString(PyObject *unicode,
8337 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338{
8339 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 PyErr_BadArgument();
8341 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008342 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008343 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344}
8345
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008347static void
8348make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008349 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008350 Py_ssize_t startpos, Py_ssize_t endpos,
8351 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008352{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008354 *exceptionObject = _PyUnicodeTranslateError_Create(
8355 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008356 }
8357 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8359 goto onError;
8360 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8361 goto onError;
8362 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8363 goto onError;
8364 return;
8365 onError:
8366 Py_DECREF(*exceptionObject);
8367 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008368 }
8369}
8370
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008372static void
8373raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008374 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008375 Py_ssize_t startpos, Py_ssize_t endpos,
8376 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377{
8378 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382}
8383
8384/* error handling callback helper:
8385 build arguments, call the callback and check the arguments,
8386 put the result into newpos and return the replacement string, which
8387 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008388static PyObject *
8389unicode_translate_call_errorhandler(const char *errors,
8390 PyObject **errorHandler,
8391 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008393 Py_ssize_t startpos, Py_ssize_t endpos,
8394 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008395{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008396 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008397
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008398 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 PyObject *restuple;
8400 PyObject *resunicode;
8401
8402 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008406 }
8407
8408 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008409 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412
8413 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008417 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008418 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 Py_DECREF(restuple);
8420 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 }
8422 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 &resunicode, &i_newpos)) {
8424 Py_DECREF(restuple);
8425 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008427 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008429 else
8430 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008431 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8433 Py_DECREF(restuple);
8434 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008435 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 Py_INCREF(resunicode);
8437 Py_DECREF(restuple);
8438 return resunicode;
8439}
8440
8441/* Lookup the character ch in the mapping and put the result in result,
8442 which must be decrefed by the caller.
8443 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008444static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446{
Christian Heimes217cfd12007-12-02 14:31:20 +00008447 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 PyObject *x;
8449
8450 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 x = PyObject_GetItem(mapping, w);
8453 Py_DECREF(w);
8454 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8456 /* No mapping found means: use 1:1 mapping. */
8457 PyErr_Clear();
8458 *result = NULL;
8459 return 0;
8460 } else
8461 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462 }
8463 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 *result = x;
8465 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008467 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 long value = PyLong_AS_LONG(x);
8469 long max = PyUnicode_GetMax();
8470 if (value < 0 || value > max) {
8471 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008472 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 Py_DECREF(x);
8474 return -1;
8475 }
8476 *result = x;
8477 return 0;
8478 }
8479 else if (PyUnicode_Check(x)) {
8480 *result = x;
8481 return 0;
8482 }
8483 else {
8484 /* wrong return value */
8485 PyErr_SetString(PyExc_TypeError,
8486 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008487 Py_DECREF(x);
8488 return -1;
8489 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008490}
8491/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 if not reallocate and adjust various state variables.
8493 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008494static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008499 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 /* exponentially overallocate to minimize reallocations */
8501 if (requiredsize < 2 * oldsize)
8502 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008503 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8504 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 }
8508 return 0;
8509}
8510/* lookup the character, put the result in the output string and adjust
8511 various state variables. Return a new reference to the object that
8512 was put in the output buffer in *result, or Py_None, if the mapping was
8513 undefined (in which case no character was written).
8514 The called must decref result.
8515 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008516static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8518 PyObject *mapping, Py_UCS4 **output,
8519 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008520 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008521{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8523 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528 }
8529 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008531 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 }
8535 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 Py_ssize_t repsize;
8537 if (PyUnicode_READY(*res) == -1)
8538 return -1;
8539 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 if (repsize==1) {
8541 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 }
8544 else if (repsize!=0) {
8545 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008546 Py_ssize_t requiredsize = *opos +
8547 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 Py_ssize_t i;
8550 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 for(i = 0; i < repsize; i++)
8553 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008555 }
8556 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558 return 0;
8559}
8560
Alexander Belopolsky40018472011-02-26 01:02:56 +00008561PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562_PyUnicode_TranslateCharmap(PyObject *input,
8563 PyObject *mapping,
8564 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 /* input object */
8567 char *idata;
8568 Py_ssize_t size, i;
8569 int kind;
8570 /* output buffer */
8571 Py_UCS4 *output = NULL;
8572 Py_ssize_t osize;
8573 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008575 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576 char *reason = "character maps to <undefined>";
8577 PyObject *errorHandler = NULL;
8578 PyObject *exc = NULL;
8579 /* the following variable is used for caching string comparisons
8580 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8581 * 3=ignore, 4=xmlcharrefreplace */
8582 int known_errorHandler = -1;
8583
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 PyErr_BadArgument();
8586 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008587 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 if (PyUnicode_READY(input) == -1)
8590 return NULL;
8591 idata = (char*)PyUnicode_DATA(input);
8592 kind = PyUnicode_KIND(input);
8593 size = PyUnicode_GET_LENGTH(input);
8594 i = 0;
8595
8596 if (size == 0) {
8597 Py_INCREF(input);
8598 return input;
8599 }
8600
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008601 /* allocate enough for a simple 1:1 translation without
8602 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603 osize = size;
8604 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8605 opos = 0;
8606 if (output == NULL) {
8607 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 /* try to encode it */
8613 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 if (charmaptranslate_output(input, i, mapping,
8615 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 Py_XDECREF(x);
8617 goto onError;
8618 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008619 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 else { /* untranslatable character */
8623 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8624 Py_ssize_t repsize;
8625 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628 Py_ssize_t collstart = i;
8629 Py_ssize_t collend = i+1;
8630 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 while (collend < size) {
8634 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 goto onError;
8636 Py_XDECREF(x);
8637 if (x!=Py_None)
8638 break;
8639 ++collend;
8640 }
8641 /* cache callback name lookup
8642 * (if not done yet, i.e. it's the first error) */
8643 if (known_errorHandler==-1) {
8644 if ((errors==NULL) || (!strcmp(errors, "strict")))
8645 known_errorHandler = 1;
8646 else if (!strcmp(errors, "replace"))
8647 known_errorHandler = 2;
8648 else if (!strcmp(errors, "ignore"))
8649 known_errorHandler = 3;
8650 else if (!strcmp(errors, "xmlcharrefreplace"))
8651 known_errorHandler = 4;
8652 else
8653 known_errorHandler = 0;
8654 }
8655 switch (known_errorHandler) {
8656 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 raise_translate_exception(&exc, input, collstart,
8658 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008659 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 case 2: /* replace */
8661 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 for (coll = collstart; coll<collend; coll++)
8663 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 /* fall through */
8665 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 break;
8668 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 /* generate replacement (temporarily (mis)uses i) */
8670 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 char buffer[2+29+1+1];
8672 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8674 if (charmaptranslate_makespace(&output, &osize,
8675 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 goto onError;
8677 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008680 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 break;
8682 default:
8683 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 reason, input, &exc,
8685 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008686 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008688 if (PyUnicode_READY(repunicode) < 0) {
8689 Py_DECREF(repunicode);
8690 goto onError;
8691 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 repsize = PyUnicode_GET_LENGTH(repunicode);
8694 if (charmaptranslate_makespace(&output, &osize,
8695 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 Py_DECREF(repunicode);
8697 goto onError;
8698 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 for (uni2 = 0; repsize-->0; ++uni2)
8700 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8701 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008703 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008704 }
8705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8707 if (!res)
8708 goto onError;
8709 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 Py_XDECREF(exc);
8711 Py_XDECREF(errorHandler);
8712 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008713
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008715 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716 Py_XDECREF(exc);
8717 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008718 return NULL;
8719}
8720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008721/* Deprecated. Use PyUnicode_Translate instead. */
8722PyObject *
8723PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8724 Py_ssize_t size,
8725 PyObject *mapping,
8726 const char *errors)
8727{
8728 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8729 if (!unicode)
8730 return NULL;
8731 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8732}
8733
Alexander Belopolsky40018472011-02-26 01:02:56 +00008734PyObject *
8735PyUnicode_Translate(PyObject *str,
8736 PyObject *mapping,
8737 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008738{
8739 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008740
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741 str = PyUnicode_FromObject(str);
8742 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008745 Py_DECREF(str);
8746 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008747
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749 Py_XDECREF(str);
8750 return NULL;
8751}
Tim Petersced69f82003-09-16 20:30:58 +00008752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008753static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008754fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008755{
8756 /* No need to call PyUnicode_READY(self) because this function is only
8757 called as a callback from fixup() which does it already. */
8758 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8759 const int kind = PyUnicode_KIND(self);
8760 void *data = PyUnicode_DATA(self);
8761 Py_UCS4 maxchar = 0, ch, fixed;
8762 Py_ssize_t i;
8763
8764 for (i = 0; i < len; ++i) {
8765 ch = PyUnicode_READ(kind, data, i);
8766 fixed = 0;
8767 if (ch > 127) {
8768 if (Py_UNICODE_ISSPACE(ch))
8769 fixed = ' ';
8770 else {
8771 const int decimal = Py_UNICODE_TODECIMAL(ch);
8772 if (decimal >= 0)
8773 fixed = '0' + decimal;
8774 }
8775 if (fixed != 0) {
8776 if (fixed > maxchar)
8777 maxchar = fixed;
8778 PyUnicode_WRITE(kind, data, i, fixed);
8779 }
8780 else if (ch > maxchar)
8781 maxchar = ch;
8782 }
8783 else if (ch > maxchar)
8784 maxchar = ch;
8785 }
8786
8787 return maxchar;
8788}
8789
8790PyObject *
8791_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8792{
8793 if (!PyUnicode_Check(unicode)) {
8794 PyErr_BadInternalCall();
8795 return NULL;
8796 }
8797 if (PyUnicode_READY(unicode) == -1)
8798 return NULL;
8799 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8800 /* If the string is already ASCII, just return the same string */
8801 Py_INCREF(unicode);
8802 return unicode;
8803 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008804 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805}
8806
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008807PyObject *
8808PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8809 Py_ssize_t length)
8810{
Victor Stinnerf0124502011-11-21 23:12:56 +01008811 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008812 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008813 Py_UCS4 maxchar;
8814 enum PyUnicode_Kind kind;
8815 void *data;
8816
8817 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008818 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008819 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008820 if (ch > 127) {
8821 int decimal = Py_UNICODE_TODECIMAL(ch);
8822 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008823 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008824 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008825 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008826 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008827
8828 /* Copy to a new string */
8829 decimal = PyUnicode_New(length, maxchar);
8830 if (decimal == NULL)
8831 return decimal;
8832 kind = PyUnicode_KIND(decimal);
8833 data = PyUnicode_DATA(decimal);
8834 /* Iterate over code points */
8835 for (i = 0; i < length; i++) {
8836 Py_UNICODE ch = s[i];
8837 if (ch > 127) {
8838 int decimal = Py_UNICODE_TODECIMAL(ch);
8839 if (decimal >= 0)
8840 ch = '0' + decimal;
8841 }
8842 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008844 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008845}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008846/* --- Decimal Encoder ---------------------------------------------------- */
8847
Alexander Belopolsky40018472011-02-26 01:02:56 +00008848int
8849PyUnicode_EncodeDecimal(Py_UNICODE *s,
8850 Py_ssize_t length,
8851 char *output,
8852 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008853{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008854 PyObject *errorHandler = NULL;
8855 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008856 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008857 const char *encoding = "decimal";
8858 const char *reason = "invalid decimal Unicode string";
8859 /* the following variable is used for caching string comparisons
8860 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8861 int known_errorHandler = -1;
Victor Stinner42bf7752011-11-21 22:52:58 +01008862 Py_ssize_t i, j;
8863 enum PyUnicode_Kind kind;
8864 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008865
8866 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008867 PyErr_BadArgument();
8868 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008869 }
8870
Victor Stinner42bf7752011-11-21 22:52:58 +01008871 unicode = PyUnicode_FromUnicode(s, length);
8872 if (unicode == NULL)
8873 return -1;
8874
8875 if (PyUnicode_READY(unicode) < 0)
8876 goto onError;
8877 kind = PyUnicode_KIND(unicode);
8878 data = PyUnicode_DATA(unicode);
8879
Victor Stinnerb84d7232011-11-22 01:50:07 +01008880 for (i=0; i < length; ) {
Victor Stinner42bf7752011-11-21 22:52:58 +01008881 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008882 int decimal;
Victor Stinner42bf7752011-11-21 22:52:58 +01008883 Py_ssize_t startpos, endpos;
Tim Petersced69f82003-09-16 20:30:58 +00008884
Benjamin Peterson29060642009-01-31 22:14:21 +00008885 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008886 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008887 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008888 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008889 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 decimal = Py_UNICODE_TODECIMAL(ch);
8891 if (decimal >= 0) {
8892 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008893 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 continue;
8895 }
8896 if (0 < ch && ch < 256) {
8897 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008898 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 continue;
8900 }
8901 /* All other characters are considered unencodable */
Victor Stinner42bf7752011-11-21 22:52:58 +01008902 startpos = i;
8903 endpos = i+1;
8904 for (; endpos < length; endpos++) {
8905 ch = PyUnicode_READ(kind, data, endpos);
8906 if ((0 < ch && ch < 256) ||
Victor Stinnerb84d7232011-11-22 01:50:07 +01008907 Py_UNICODE_ISSPACE(ch) ||
8908 0 <= Py_UNICODE_TODECIMAL(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00008909 break;
8910 }
8911 /* cache callback name lookup
8912 * (if not done yet, i.e. it's the first error) */
8913 if (known_errorHandler==-1) {
8914 if ((errors==NULL) || (!strcmp(errors, "strict")))
8915 known_errorHandler = 1;
8916 else if (!strcmp(errors, "replace"))
8917 known_errorHandler = 2;
8918 else if (!strcmp(errors, "ignore"))
8919 known_errorHandler = 3;
8920 else if (!strcmp(errors, "xmlcharrefreplace"))
8921 known_errorHandler = 4;
8922 else
8923 known_errorHandler = 0;
8924 }
8925 switch (known_errorHandler) {
8926 case 1: /* strict */
Victor Stinner42bf7752011-11-21 22:52:58 +01008927 raise_encode_exception(&exc, encoding, unicode, startpos, endpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 goto onError;
8929 case 2: /* replace */
Victor Stinner42bf7752011-11-21 22:52:58 +01008930 for (j=startpos; j < endpos; j++)
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 *output++ = '?';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008932 i = endpos;
8933 break;
Benjamin Peterson29060642009-01-31 22:14:21 +00008934 case 3: /* ignore */
Victor Stinner42bf7752011-11-21 22:52:58 +01008935 i = endpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008936 break;
8937 case 4: /* xmlcharrefreplace */
Victor Stinner42bf7752011-11-21 22:52:58 +01008938 /* generate replacement */
8939 for (j=startpos; j < endpos; j++) {
8940 ch = PyUnicode_READ(kind, data, i);
8941 output += sprintf(output, "&#%d;", (int)ch);
8942 i++;
8943 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 break;
8945 default:
Victor Stinner42bf7752011-11-21 22:52:58 +01008946 {
8947 PyObject *repunicode;
8948 Py_ssize_t repsize, newpos, k;
8949 enum PyUnicode_Kind repkind;
8950 void *repdata;
8951
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008953 encoding, reason, unicode, &exc,
Victor Stinner42bf7752011-11-21 22:52:58 +01008954 startpos, endpos, &newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 if (repunicode == NULL)
8956 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008957 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008958 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008959 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8960 Py_DECREF(repunicode);
8961 goto onError;
8962 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008963 if (PyUnicode_READY(repunicode) < 0) {
8964 Py_DECREF(repunicode);
8965 goto onError;
8966 }
8967 repkind = PyUnicode_KIND(repunicode);
8968 repdata = PyUnicode_DATA(repunicode);
8969
Benjamin Peterson29060642009-01-31 22:14:21 +00008970 /* generate replacement */
8971 repsize = PyUnicode_GET_SIZE(repunicode);
Victor Stinner42bf7752011-11-21 22:52:58 +01008972 for (k=0; k<repsize; k++) {
8973 ch = PyUnicode_READ(repkind, repdata, k);
Benjamin Peterson29060642009-01-31 22:14:21 +00008974 if (Py_UNICODE_ISSPACE(ch))
8975 *output++ = ' ';
8976 else {
8977 decimal = Py_UNICODE_TODECIMAL(ch);
8978 if (decimal >= 0)
8979 *output++ = '0' + decimal;
8980 else if (0 < ch && ch < 256)
8981 *output++ = (char)ch;
8982 else {
8983 Py_DECREF(repunicode);
8984 raise_encode_exception(&exc, encoding,
Victor Stinner42bf7752011-11-21 22:52:58 +01008985 unicode, startpos, endpos,
8986 reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008987 goto onError;
8988 }
8989 }
8990 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008991 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 Py_DECREF(repunicode);
8993 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008994 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008995 }
8996 /* 0-terminate the output string */
8997 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008998 Py_XDECREF(exc);
8999 Py_XDECREF(errorHandler);
Victor Stinner42bf7752011-11-21 22:52:58 +01009000 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009001 return 0;
9002
Benjamin Peterson29060642009-01-31 22:14:21 +00009003 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009004 Py_XDECREF(exc);
9005 Py_XDECREF(errorHandler);
Victor Stinner42bf7752011-11-21 22:52:58 +01009006 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009007 return -1;
9008}
9009
Guido van Rossumd57fd912000-03-10 22:53:23 +00009010/* --- Helpers ------------------------------------------------------------ */
9011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009013any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014 Py_ssize_t start,
9015 Py_ssize_t end)
9016{
9017 int kind1, kind2, kind;
9018 void *buf1, *buf2;
9019 Py_ssize_t len1, len2, result;
9020
9021 kind1 = PyUnicode_KIND(s1);
9022 kind2 = PyUnicode_KIND(s2);
9023 kind = kind1 > kind2 ? kind1 : kind2;
9024 buf1 = PyUnicode_DATA(s1);
9025 buf2 = PyUnicode_DATA(s2);
9026 if (kind1 != kind)
9027 buf1 = _PyUnicode_AsKind(s1, kind);
9028 if (!buf1)
9029 return -2;
9030 if (kind2 != kind)
9031 buf2 = _PyUnicode_AsKind(s2, kind);
9032 if (!buf2) {
9033 if (kind1 != kind) PyMem_Free(buf1);
9034 return -2;
9035 }
9036 len1 = PyUnicode_GET_LENGTH(s1);
9037 len2 = PyUnicode_GET_LENGTH(s2);
9038
Victor Stinner794d5672011-10-10 03:21:36 +02009039 if (direction > 0) {
9040 switch(kind) {
9041 case PyUnicode_1BYTE_KIND:
9042 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9043 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9044 else
9045 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9046 break;
9047 case PyUnicode_2BYTE_KIND:
9048 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9049 break;
9050 case PyUnicode_4BYTE_KIND:
9051 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9052 break;
9053 default:
9054 assert(0); result = -2;
9055 }
9056 }
9057 else {
9058 switch(kind) {
9059 case PyUnicode_1BYTE_KIND:
9060 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9061 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9062 else
9063 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9064 break;
9065 case PyUnicode_2BYTE_KIND:
9066 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9067 break;
9068 case PyUnicode_4BYTE_KIND:
9069 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9070 break;
9071 default:
9072 assert(0); result = -2;
9073 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 }
9075
9076 if (kind1 != kind)
9077 PyMem_Free(buf1);
9078 if (kind2 != kind)
9079 PyMem_Free(buf2);
9080
9081 return result;
9082}
9083
9084Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009085_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 Py_ssize_t n_buffer,
9087 void *digits, Py_ssize_t n_digits,
9088 Py_ssize_t min_width,
9089 const char *grouping,
9090 const char *thousands_sep)
9091{
9092 switch(kind) {
9093 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009094 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9095 return _PyUnicode_ascii_InsertThousandsGrouping(
9096 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9097 min_width, grouping, thousands_sep);
9098 else
9099 return _PyUnicode_ucs1_InsertThousandsGrouping(
9100 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9101 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102 case PyUnicode_2BYTE_KIND:
9103 return _PyUnicode_ucs2_InsertThousandsGrouping(
9104 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9105 min_width, grouping, thousands_sep);
9106 case PyUnicode_4BYTE_KIND:
9107 return _PyUnicode_ucs4_InsertThousandsGrouping(
9108 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9109 min_width, grouping, thousands_sep);
9110 }
9111 assert(0);
9112 return -1;
9113}
9114
9115
Thomas Wouters477c8d52006-05-27 19:21:47 +00009116/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009117#define ADJUST_INDICES(start, end, len) \
9118 if (end > len) \
9119 end = len; \
9120 else if (end < 0) { \
9121 end += len; \
9122 if (end < 0) \
9123 end = 0; \
9124 } \
9125 if (start < 0) { \
9126 start += len; \
9127 if (start < 0) \
9128 start = 0; \
9129 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009130
Alexander Belopolsky40018472011-02-26 01:02:56 +00009131Py_ssize_t
9132PyUnicode_Count(PyObject *str,
9133 PyObject *substr,
9134 Py_ssize_t start,
9135 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009136{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009137 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009138 PyObject* str_obj;
9139 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140 int kind1, kind2, kind;
9141 void *buf1 = NULL, *buf2 = NULL;
9142 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009143
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009144 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009145 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009146 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009147 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009148 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 Py_DECREF(str_obj);
9150 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151 }
Tim Petersced69f82003-09-16 20:30:58 +00009152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009153 kind1 = PyUnicode_KIND(str_obj);
9154 kind2 = PyUnicode_KIND(sub_obj);
9155 kind = kind1 > kind2 ? kind1 : kind2;
9156 buf1 = PyUnicode_DATA(str_obj);
9157 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009158 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 if (!buf1)
9160 goto onError;
9161 buf2 = PyUnicode_DATA(sub_obj);
9162 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009163 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 if (!buf2)
9165 goto onError;
9166 len1 = PyUnicode_GET_LENGTH(str_obj);
9167 len2 = PyUnicode_GET_LENGTH(sub_obj);
9168
9169 ADJUST_INDICES(start, end, len1);
9170 switch(kind) {
9171 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009172 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9173 result = asciilib_count(
9174 ((Py_UCS1*)buf1) + start, end - start,
9175 buf2, len2, PY_SSIZE_T_MAX
9176 );
9177 else
9178 result = ucs1lib_count(
9179 ((Py_UCS1*)buf1) + start, end - start,
9180 buf2, len2, PY_SSIZE_T_MAX
9181 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 break;
9183 case PyUnicode_2BYTE_KIND:
9184 result = ucs2lib_count(
9185 ((Py_UCS2*)buf1) + start, end - start,
9186 buf2, len2, PY_SSIZE_T_MAX
9187 );
9188 break;
9189 case PyUnicode_4BYTE_KIND:
9190 result = ucs4lib_count(
9191 ((Py_UCS4*)buf1) + start, end - start,
9192 buf2, len2, PY_SSIZE_T_MAX
9193 );
9194 break;
9195 default:
9196 assert(0); result = 0;
9197 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009198
9199 Py_DECREF(sub_obj);
9200 Py_DECREF(str_obj);
9201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 if (kind1 != kind)
9203 PyMem_Free(buf1);
9204 if (kind2 != kind)
9205 PyMem_Free(buf2);
9206
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 onError:
9209 Py_DECREF(sub_obj);
9210 Py_DECREF(str_obj);
9211 if (kind1 != kind && buf1)
9212 PyMem_Free(buf1);
9213 if (kind2 != kind && buf2)
9214 PyMem_Free(buf2);
9215 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009216}
9217
Alexander Belopolsky40018472011-02-26 01:02:56 +00009218Py_ssize_t
9219PyUnicode_Find(PyObject *str,
9220 PyObject *sub,
9221 Py_ssize_t start,
9222 Py_ssize_t end,
9223 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009225 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009226
Guido van Rossumd57fd912000-03-10 22:53:23 +00009227 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009229 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009230 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009232 Py_DECREF(str);
9233 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234 }
Tim Petersced69f82003-09-16 20:30:58 +00009235
Victor Stinner794d5672011-10-10 03:21:36 +02009236 result = any_find_slice(direction,
9237 str, sub, start, end
9238 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009239
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009241 Py_DECREF(sub);
9242
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243 return result;
9244}
9245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009246Py_ssize_t
9247PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9248 Py_ssize_t start, Py_ssize_t end,
9249 int direction)
9250{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009251 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009252 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 if (PyUnicode_READY(str) == -1)
9254 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009255 if (start < 0 || end < 0) {
9256 PyErr_SetString(PyExc_IndexError, "string index out of range");
9257 return -2;
9258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (end > PyUnicode_GET_LENGTH(str))
9260 end = PyUnicode_GET_LENGTH(str);
9261 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009262 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9263 kind, end-start, ch, direction);
9264 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009266 else
9267 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268}
9269
Alexander Belopolsky40018472011-02-26 01:02:56 +00009270static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009271tailmatch(PyObject *self,
9272 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009273 Py_ssize_t start,
9274 Py_ssize_t end,
9275 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277 int kind_self;
9278 int kind_sub;
9279 void *data_self;
9280 void *data_sub;
9281 Py_ssize_t offset;
9282 Py_ssize_t i;
9283 Py_ssize_t end_sub;
9284
9285 if (PyUnicode_READY(self) == -1 ||
9286 PyUnicode_READY(substring) == -1)
9287 return 0;
9288
9289 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 return 1;
9291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9293 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009294 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009295 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 kind_self = PyUnicode_KIND(self);
9298 data_self = PyUnicode_DATA(self);
9299 kind_sub = PyUnicode_KIND(substring);
9300 data_sub = PyUnicode_DATA(substring);
9301 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9302
9303 if (direction > 0)
9304 offset = end;
9305 else
9306 offset = start;
9307
9308 if (PyUnicode_READ(kind_self, data_self, offset) ==
9309 PyUnicode_READ(kind_sub, data_sub, 0) &&
9310 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9311 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9312 /* If both are of the same kind, memcmp is sufficient */
9313 if (kind_self == kind_sub) {
9314 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009315 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 data_sub,
9317 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009318 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 }
9320 /* otherwise we have to compare each character by first accesing it */
9321 else {
9322 /* We do not need to compare 0 and len(substring)-1 because
9323 the if statement above ensured already that they are equal
9324 when we end up here. */
9325 // TODO: honor direction and do a forward or backwards search
9326 for (i = 1; i < end_sub; ++i) {
9327 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9328 PyUnicode_READ(kind_sub, data_sub, i))
9329 return 0;
9330 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009331 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333 }
9334
9335 return 0;
9336}
9337
Alexander Belopolsky40018472011-02-26 01:02:56 +00009338Py_ssize_t
9339PyUnicode_Tailmatch(PyObject *str,
9340 PyObject *substr,
9341 Py_ssize_t start,
9342 Py_ssize_t end,
9343 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009345 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009346
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347 str = PyUnicode_FromObject(str);
9348 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009349 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350 substr = PyUnicode_FromObject(substr);
9351 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 Py_DECREF(str);
9353 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354 }
Tim Petersced69f82003-09-16 20:30:58 +00009355
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009356 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009357 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358 Py_DECREF(str);
9359 Py_DECREF(substr);
9360 return result;
9361}
9362
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363/* Apply fixfct filter to the Unicode object self and return a
9364 reference to the modified object */
9365
Alexander Belopolsky40018472011-02-26 01:02:56 +00009366static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009367fixup(PyObject *self,
9368 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 PyObject *u;
9371 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372
Victor Stinner87af4f22011-11-21 23:03:47 +01009373 u = PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009375 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009376 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009377
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009378 /* fix functions return the new maximum character in a string,
9379 if the kind of the resulting unicode object does not change,
9380 everything is fine. Otherwise we need to change the string kind
9381 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009382 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383 if (maxchar_new == 0)
9384 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9385 else if (maxchar_new <= 127)
9386 maxchar_new = 127;
9387 else if (maxchar_new <= 255)
9388 maxchar_new = 255;
9389 else if (maxchar_new <= 65535)
9390 maxchar_new = 65535;
9391 else
9392 maxchar_new = 1114111; /* 0x10ffff */
9393
9394 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009395 /* fixfct should return TRUE if it modified the buffer. If
9396 FALSE, return a reference to the original buffer instead
9397 (to save space, not time) */
9398 Py_INCREF(self);
9399 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009400 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009402 else if (maxchar_new == maxchar_old) {
9403 return u;
9404 }
9405 else {
9406 /* In case the maximum character changed, we need to
9407 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009408 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 if (v == NULL) {
9410 Py_DECREF(u);
9411 return NULL;
9412 }
9413 if (maxchar_new > maxchar_old) {
9414 /* If the maxchar increased so that the kind changed, not all
9415 characters are representable anymore and we need to fix the
9416 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009417 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009418 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9420 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009421 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009422 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009423 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424
9425 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009426 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 return v;
9428 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429}
9430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009432fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 /* No need to call PyUnicode_READY(self) because this function is only
9435 called as a callback from fixup() which does it already. */
9436 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9437 const int kind = PyUnicode_KIND(self);
9438 void *data = PyUnicode_DATA(self);
9439 int touched = 0;
9440 Py_UCS4 maxchar = 0;
9441 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 for (i = 0; i < len; ++i) {
9444 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9445 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9446 if (up != ch) {
9447 if (up > maxchar)
9448 maxchar = up;
9449 PyUnicode_WRITE(kind, data, i, up);
9450 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 else if (ch > maxchar)
9453 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454 }
9455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 if (touched)
9457 return maxchar;
9458 else
9459 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460}
9461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009463fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9466 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9467 const int kind = PyUnicode_KIND(self);
9468 void *data = PyUnicode_DATA(self);
9469 int touched = 0;
9470 Py_UCS4 maxchar = 0;
9471 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 for(i = 0; i < len; ++i) {
9474 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9475 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9476 if (lo != ch) {
9477 if (lo > maxchar)
9478 maxchar = lo;
9479 PyUnicode_WRITE(kind, data, i, lo);
9480 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 else if (ch > maxchar)
9483 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484 }
9485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 if (touched)
9487 return maxchar;
9488 else
9489 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490}
9491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009493fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9496 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9497 const int kind = PyUnicode_KIND(self);
9498 void *data = PyUnicode_DATA(self);
9499 int touched = 0;
9500 Py_UCS4 maxchar = 0;
9501 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 for(i = 0; i < len; ++i) {
9504 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9505 Py_UCS4 nu = 0;
9506
9507 if (Py_UNICODE_ISUPPER(ch))
9508 nu = Py_UNICODE_TOLOWER(ch);
9509 else if (Py_UNICODE_ISLOWER(ch))
9510 nu = Py_UNICODE_TOUPPER(ch);
9511
9512 if (nu != 0) {
9513 if (nu > maxchar)
9514 maxchar = nu;
9515 PyUnicode_WRITE(kind, data, i, nu);
9516 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009517 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 else if (ch > maxchar)
9519 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520 }
9521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 if (touched)
9523 return maxchar;
9524 else
9525 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526}
9527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009529fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9532 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9533 const int kind = PyUnicode_KIND(self);
9534 void *data = PyUnicode_DATA(self);
9535 int touched = 0;
9536 Py_UCS4 maxchar = 0;
9537 Py_ssize_t i = 0;
9538 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009539
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009540 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009541 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542
9543 ch = PyUnicode_READ(kind, data, i);
9544 if (!Py_UNICODE_ISUPPER(ch)) {
9545 maxchar = Py_UNICODE_TOUPPER(ch);
9546 PyUnicode_WRITE(kind, data, i, maxchar);
9547 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 ++i;
9550 for(; i < len; ++i) {
9551 ch = PyUnicode_READ(kind, data, i);
9552 if (!Py_UNICODE_ISLOWER(ch)) {
9553 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9554 if (lo > maxchar)
9555 maxchar = lo;
9556 PyUnicode_WRITE(kind, data, i, lo);
9557 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 else if (ch > maxchar)
9560 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562
9563 if (touched)
9564 return maxchar;
9565 else
9566 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009570fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9573 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9574 const int kind = PyUnicode_KIND(self);
9575 void *data = PyUnicode_DATA(self);
9576 Py_UCS4 maxchar = 0;
9577 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578 int previous_is_cased;
9579
9580 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 if (len == 1) {
9582 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9583 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9584 if (ti != ch) {
9585 PyUnicode_WRITE(kind, data, i, ti);
9586 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009587 }
9588 else
9589 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 for(; i < len; ++i) {
9593 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9594 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009595
Benjamin Peterson29060642009-01-31 22:14:21 +00009596 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009598 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009599 nu = Py_UNICODE_TOTITLE(ch);
9600
9601 if (nu > maxchar)
9602 maxchar = nu;
9603 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009604
Benjamin Peterson29060642009-01-31 22:14:21 +00009605 if (Py_UNICODE_ISLOWER(ch) ||
9606 Py_UNICODE_ISUPPER(ch) ||
9607 Py_UNICODE_ISTITLE(ch))
9608 previous_is_cased = 1;
9609 else
9610 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009612 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613}
9614
Tim Peters8ce9f162004-08-27 01:49:32 +00009615PyObject *
9616PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009621 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009622 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9623 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009624 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009626 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009628 int use_memcpy;
9629 unsigned char *res_data = NULL, *sep_data = NULL;
9630 PyObject *last_obj;
9631 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632
Tim Peters05eba1f2004-08-27 21:32:02 +00009633 fseq = PySequence_Fast(seq, "");
9634 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009635 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009636 }
9637
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009638 /* NOTE: the following code can't call back into Python code,
9639 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009640 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009641
Tim Peters05eba1f2004-08-27 21:32:02 +00009642 seqlen = PySequence_Fast_GET_SIZE(fseq);
9643 /* If empty sequence, return u"". */
9644 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009645 Py_DECREF(fseq);
9646 Py_INCREF(unicode_empty);
9647 res = unicode_empty;
9648 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009649 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009650
Tim Peters05eba1f2004-08-27 21:32:02 +00009651 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009652 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009653 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009654 if (seqlen == 1) {
9655 if (PyUnicode_CheckExact(items[0])) {
9656 res = items[0];
9657 Py_INCREF(res);
9658 Py_DECREF(fseq);
9659 return res;
9660 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009661 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009662 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009663 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009664 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009665 /* Set up sep and seplen */
9666 if (separator == NULL) {
9667 /* fall back to a blank space separator */
9668 sep = PyUnicode_FromOrdinal(' ');
9669 if (!sep)
9670 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009671 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009672 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009673 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009674 else {
9675 if (!PyUnicode_Check(separator)) {
9676 PyErr_Format(PyExc_TypeError,
9677 "separator: expected str instance,"
9678 " %.80s found",
9679 Py_TYPE(separator)->tp_name);
9680 goto onError;
9681 }
9682 if (PyUnicode_READY(separator))
9683 goto onError;
9684 sep = separator;
9685 seplen = PyUnicode_GET_LENGTH(separator);
9686 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9687 /* inc refcount to keep this code path symmetric with the
9688 above case of a blank separator */
9689 Py_INCREF(sep);
9690 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009691 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 }
9693
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009694 /* There are at least two things to join, or else we have a subclass
9695 * of str in the sequence.
9696 * Do a pre-pass to figure out the total amount of space we'll
9697 * need (sz), and see whether all argument are strings.
9698 */
9699 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009700#ifdef Py_DEBUG
9701 use_memcpy = 0;
9702#else
9703 use_memcpy = 1;
9704#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009705 for (i = 0; i < seqlen; i++) {
9706 const Py_ssize_t old_sz = sz;
9707 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009708 if (!PyUnicode_Check(item)) {
9709 PyErr_Format(PyExc_TypeError,
9710 "sequence item %zd: expected str instance,"
9711 " %.80s found",
9712 i, Py_TYPE(item)->tp_name);
9713 goto onError;
9714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009715 if (PyUnicode_READY(item) == -1)
9716 goto onError;
9717 sz += PyUnicode_GET_LENGTH(item);
9718 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009719 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009720 if (i != 0)
9721 sz += seplen;
9722 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9723 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009724 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009725 goto onError;
9726 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 if (use_memcpy && last_obj != NULL) {
9728 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9729 use_memcpy = 0;
9730 }
9731 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009732 }
Tim Petersced69f82003-09-16 20:30:58 +00009733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009735 if (res == NULL)
9736 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009737
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009738 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009739#ifdef Py_DEBUG
9740 use_memcpy = 0;
9741#else
9742 if (use_memcpy) {
9743 res_data = PyUnicode_1BYTE_DATA(res);
9744 kind = PyUnicode_KIND(res);
9745 if (seplen != 0)
9746 sep_data = PyUnicode_1BYTE_DATA(sep);
9747 }
9748#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009750 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009751 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009752 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009753 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009754 if (use_memcpy) {
9755 Py_MEMCPY(res_data,
9756 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009757 kind * seplen);
9758 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009759 }
9760 else {
9761 copy_characters(res, res_offset, sep, 0, seplen);
9762 res_offset += seplen;
9763 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009764 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009765 itemlen = PyUnicode_GET_LENGTH(item);
9766 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009767 if (use_memcpy) {
9768 Py_MEMCPY(res_data,
9769 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009770 kind * itemlen);
9771 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009772 }
9773 else {
9774 copy_characters(res, res_offset, item, 0, itemlen);
9775 res_offset += itemlen;
9776 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009777 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009778 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009779 if (use_memcpy)
9780 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009781 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009782 else
9783 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009784
Tim Peters05eba1f2004-08-27 21:32:02 +00009785 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009786 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009787 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009788 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009789
Benjamin Peterson29060642009-01-31 22:14:21 +00009790 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009791 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009793 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009794 return NULL;
9795}
9796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797#define FILL(kind, data, value, start, length) \
9798 do { \
9799 Py_ssize_t i_ = 0; \
9800 assert(kind != PyUnicode_WCHAR_KIND); \
9801 switch ((kind)) { \
9802 case PyUnicode_1BYTE_KIND: { \
9803 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9804 memset(to_, (unsigned char)value, length); \
9805 break; \
9806 } \
9807 case PyUnicode_2BYTE_KIND: { \
9808 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9809 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9810 break; \
9811 } \
9812 default: { \
9813 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9814 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9815 break; \
9816 } \
9817 } \
9818 } while (0)
9819
Victor Stinner9310abb2011-10-05 00:59:23 +02009820static PyObject *
9821pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009822 Py_ssize_t left,
9823 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 PyObject *u;
9827 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009828 int kind;
9829 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830
9831 if (left < 0)
9832 left = 0;
9833 if (right < 0)
9834 right = 0;
9835
Tim Peters7a29bd52001-09-12 03:03:31 +00009836 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009837 Py_INCREF(self);
9838 return self;
9839 }
9840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9842 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009843 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9844 return NULL;
9845 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009846 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9847 if (fill > maxchar)
9848 maxchar = fill;
9849 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009850 if (!u)
9851 return NULL;
9852
9853 kind = PyUnicode_KIND(u);
9854 data = PyUnicode_DATA(u);
9855 if (left)
9856 FILL(kind, data, fill, 0, left);
9857 if (right)
9858 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009859 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009860 assert(_PyUnicode_CheckConsistency(u, 1));
9861 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009862}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864
Alexander Belopolsky40018472011-02-26 01:02:56 +00009865PyObject *
9866PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009867{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009869
9870 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009872 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 switch(PyUnicode_KIND(string)) {
9875 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009876 if (PyUnicode_IS_ASCII(string))
9877 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009878 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009879 PyUnicode_GET_LENGTH(string), keepends);
9880 else
9881 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009882 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009883 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 break;
9885 case PyUnicode_2BYTE_KIND:
9886 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009887 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009888 PyUnicode_GET_LENGTH(string), keepends);
9889 break;
9890 case PyUnicode_4BYTE_KIND:
9891 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009892 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 PyUnicode_GET_LENGTH(string), keepends);
9894 break;
9895 default:
9896 assert(0);
9897 list = 0;
9898 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899 Py_DECREF(string);
9900 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009901}
9902
Alexander Belopolsky40018472011-02-26 01:02:56 +00009903static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009904split(PyObject *self,
9905 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009906 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 int kind1, kind2, kind;
9909 void *buf1, *buf2;
9910 Py_ssize_t len1, len2;
9911 PyObject* out;
9912
Guido van Rossumd57fd912000-03-10 22:53:23 +00009913 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009914 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 if (PyUnicode_READY(self) == -1)
9917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 if (substring == NULL)
9920 switch(PyUnicode_KIND(self)) {
9921 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009922 if (PyUnicode_IS_ASCII(self))
9923 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009924 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009925 PyUnicode_GET_LENGTH(self), maxcount
9926 );
9927 else
9928 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009929 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009930 PyUnicode_GET_LENGTH(self), maxcount
9931 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 case PyUnicode_2BYTE_KIND:
9933 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009934 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 PyUnicode_GET_LENGTH(self), maxcount
9936 );
9937 case PyUnicode_4BYTE_KIND:
9938 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009939 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 PyUnicode_GET_LENGTH(self), maxcount
9941 );
9942 default:
9943 assert(0);
9944 return NULL;
9945 }
9946
9947 if (PyUnicode_READY(substring) == -1)
9948 return NULL;
9949
9950 kind1 = PyUnicode_KIND(self);
9951 kind2 = PyUnicode_KIND(substring);
9952 kind = kind1 > kind2 ? kind1 : kind2;
9953 buf1 = PyUnicode_DATA(self);
9954 buf2 = PyUnicode_DATA(substring);
9955 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009956 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 if (!buf1)
9958 return NULL;
9959 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 if (!buf2) {
9962 if (kind1 != kind) PyMem_Free(buf1);
9963 return NULL;
9964 }
9965 len1 = PyUnicode_GET_LENGTH(self);
9966 len2 = PyUnicode_GET_LENGTH(substring);
9967
9968 switch(kind) {
9969 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009970 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9971 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009972 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009973 else
9974 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009975 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 break;
9977 case PyUnicode_2BYTE_KIND:
9978 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009979 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009980 break;
9981 case PyUnicode_4BYTE_KIND:
9982 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 break;
9985 default:
9986 out = NULL;
9987 }
9988 if (kind1 != kind)
9989 PyMem_Free(buf1);
9990 if (kind2 != kind)
9991 PyMem_Free(buf2);
9992 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993}
9994
Alexander Belopolsky40018472011-02-26 01:02:56 +00009995static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009996rsplit(PyObject *self,
9997 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009998 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009999{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 int kind1, kind2, kind;
10001 void *buf1, *buf2;
10002 Py_ssize_t len1, len2;
10003 PyObject* out;
10004
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010005 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010006 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 if (PyUnicode_READY(self) == -1)
10009 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 if (substring == NULL)
10012 switch(PyUnicode_KIND(self)) {
10013 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010014 if (PyUnicode_IS_ASCII(self))
10015 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010016 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010017 PyUnicode_GET_LENGTH(self), maxcount
10018 );
10019 else
10020 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010021 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010022 PyUnicode_GET_LENGTH(self), maxcount
10023 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024 case PyUnicode_2BYTE_KIND:
10025 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010026 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010027 PyUnicode_GET_LENGTH(self), maxcount
10028 );
10029 case PyUnicode_4BYTE_KIND:
10030 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010031 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 PyUnicode_GET_LENGTH(self), maxcount
10033 );
10034 default:
10035 assert(0);
10036 return NULL;
10037 }
10038
10039 if (PyUnicode_READY(substring) == -1)
10040 return NULL;
10041
10042 kind1 = PyUnicode_KIND(self);
10043 kind2 = PyUnicode_KIND(substring);
10044 kind = kind1 > kind2 ? kind1 : kind2;
10045 buf1 = PyUnicode_DATA(self);
10046 buf2 = PyUnicode_DATA(substring);
10047 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010048 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (!buf1)
10050 return NULL;
10051 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 if (!buf2) {
10054 if (kind1 != kind) PyMem_Free(buf1);
10055 return NULL;
10056 }
10057 len1 = PyUnicode_GET_LENGTH(self);
10058 len2 = PyUnicode_GET_LENGTH(substring);
10059
10060 switch(kind) {
10061 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010062 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10063 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010064 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010065 else
10066 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010067 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 break;
10069 case PyUnicode_2BYTE_KIND:
10070 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010071 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 break;
10073 case PyUnicode_4BYTE_KIND:
10074 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010075 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 break;
10077 default:
10078 out = NULL;
10079 }
10080 if (kind1 != kind)
10081 PyMem_Free(buf1);
10082 if (kind2 != kind)
10083 PyMem_Free(buf2);
10084 return out;
10085}
10086
10087static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010088anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10089 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090{
10091 switch(kind) {
10092 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010093 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10094 return asciilib_find(buf1, len1, buf2, len2, offset);
10095 else
10096 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 case PyUnicode_2BYTE_KIND:
10098 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10099 case PyUnicode_4BYTE_KIND:
10100 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10101 }
10102 assert(0);
10103 return -1;
10104}
10105
10106static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010107anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10108 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109{
10110 switch(kind) {
10111 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010112 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10113 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10114 else
10115 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 case PyUnicode_2BYTE_KIND:
10117 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10118 case PyUnicode_4BYTE_KIND:
10119 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10120 }
10121 assert(0);
10122 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010123}
10124
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126replace(PyObject *self, PyObject *str1,
10127 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 PyObject *u;
10130 char *sbuf = PyUnicode_DATA(self);
10131 char *buf1 = PyUnicode_DATA(str1);
10132 char *buf2 = PyUnicode_DATA(str2);
10133 int srelease = 0, release1 = 0, release2 = 0;
10134 int skind = PyUnicode_KIND(self);
10135 int kind1 = PyUnicode_KIND(str1);
10136 int kind2 = PyUnicode_KIND(str2);
10137 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10138 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10139 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010140 int mayshrink;
10141 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010142
10143 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010144 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010146 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010147
Victor Stinner59de0ee2011-10-07 10:01:28 +020010148 if (str1 == str2)
10149 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 if (skind < kind1)
10151 /* substring too wide to be present */
10152 goto nothing;
10153
Victor Stinner49a0a212011-10-12 23:46:10 +020010154 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10155 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10156 /* Replacing str1 with str2 may cause a maxchar reduction in the
10157 result string. */
10158 mayshrink = (maxchar_str2 < maxchar);
10159 maxchar = Py_MAX(maxchar, maxchar_str2);
10160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010162 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010163 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010165 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010167 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010168 Py_UCS4 u1, u2;
10169 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010171 if (findchar(sbuf, PyUnicode_KIND(self),
10172 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010173 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010176 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010178 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 rkind = PyUnicode_KIND(u);
10180 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10181 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010182 if (--maxcount < 0)
10183 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010185 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010186 }
10187 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 int rkind = skind;
10189 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 if (kind1 < rkind) {
10192 /* widen substring */
10193 buf1 = _PyUnicode_AsKind(str1, rkind);
10194 if (!buf1) goto error;
10195 release1 = 1;
10196 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010197 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010198 if (i < 0)
10199 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 if (rkind > kind2) {
10201 /* widen replacement */
10202 buf2 = _PyUnicode_AsKind(str2, rkind);
10203 if (!buf2) goto error;
10204 release2 = 1;
10205 }
10206 else if (rkind < kind2) {
10207 /* widen self and buf1 */
10208 rkind = kind2;
10209 if (release1) PyMem_Free(buf1);
10210 sbuf = _PyUnicode_AsKind(self, rkind);
10211 if (!sbuf) goto error;
10212 srelease = 1;
10213 buf1 = _PyUnicode_AsKind(str1, rkind);
10214 if (!buf1) goto error;
10215 release1 = 1;
10216 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010217 u = PyUnicode_New(slen, maxchar);
10218 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010220 assert(PyUnicode_KIND(u) == rkind);
10221 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010222
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010223 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010224 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010225 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010227 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010229
10230 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010231 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010232 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010234 if (i == -1)
10235 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010236 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010238 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010240 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010241 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010242 }
10243 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 Py_ssize_t n, i, j, ires;
10245 Py_ssize_t product, new_size;
10246 int rkind = skind;
10247 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010250 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 buf1 = _PyUnicode_AsKind(str1, rkind);
10252 if (!buf1) goto error;
10253 release1 = 1;
10254 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010255 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010256 if (n == 0)
10257 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010259 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 buf2 = _PyUnicode_AsKind(str2, rkind);
10261 if (!buf2) goto error;
10262 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010265 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 rkind = kind2;
10267 sbuf = _PyUnicode_AsKind(self, rkind);
10268 if (!sbuf) goto error;
10269 srelease = 1;
10270 if (release1) PyMem_Free(buf1);
10271 buf1 = _PyUnicode_AsKind(str1, rkind);
10272 if (!buf1) goto error;
10273 release1 = 1;
10274 }
10275 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10276 PyUnicode_GET_LENGTH(str1))); */
10277 product = n * (len2-len1);
10278 if ((product / (len2-len1)) != n) {
10279 PyErr_SetString(PyExc_OverflowError,
10280 "replace string is too long");
10281 goto error;
10282 }
10283 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010284 if (new_size == 0) {
10285 Py_INCREF(unicode_empty);
10286 u = unicode_empty;
10287 goto done;
10288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10290 PyErr_SetString(PyExc_OverflowError,
10291 "replace string is too long");
10292 goto error;
10293 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010294 u = PyUnicode_New(new_size, maxchar);
10295 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010297 assert(PyUnicode_KIND(u) == rkind);
10298 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 ires = i = 0;
10300 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010301 while (n-- > 0) {
10302 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010303 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010304 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010305 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010306 if (j == -1)
10307 break;
10308 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010309 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010310 memcpy(res + rkind * ires,
10311 sbuf + rkind * i,
10312 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010314 }
10315 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010317 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010319 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010321 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010323 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010325 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010326 memcpy(res + rkind * ires,
10327 sbuf + rkind * i,
10328 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010329 }
10330 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010331 /* interleave */
10332 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010333 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010335 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010337 if (--n <= 0)
10338 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010339 memcpy(res + rkind * ires,
10340 sbuf + rkind * i,
10341 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 ires++;
10343 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010344 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010345 memcpy(res + rkind * ires,
10346 sbuf + rkind * i,
10347 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010348 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010349 }
10350
10351 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010352 unicode_adjust_maxchar(&u);
10353 if (u == NULL)
10354 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010356
10357 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 if (srelease)
10359 PyMem_FREE(sbuf);
10360 if (release1)
10361 PyMem_FREE(buf1);
10362 if (release2)
10363 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010364 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010366
Benjamin Peterson29060642009-01-31 22:14:21 +000010367 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010368 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 if (srelease)
10370 PyMem_FREE(sbuf);
10371 if (release1)
10372 PyMem_FREE(buf1);
10373 if (release2)
10374 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010375 if (PyUnicode_CheckExact(self)) {
10376 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010377 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010378 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010379 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 error:
10381 if (srelease && sbuf)
10382 PyMem_FREE(sbuf);
10383 if (release1 && buf1)
10384 PyMem_FREE(buf1);
10385 if (release2 && buf2)
10386 PyMem_FREE(buf2);
10387 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010388}
10389
10390/* --- Unicode Object Methods --------------------------------------------- */
10391
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010392PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010393 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394\n\
10395Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010396characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397
10398static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010399unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401 return fixup(self, fixtitle);
10402}
10403
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010404PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010405 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406\n\
10407Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010408have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010409
10410static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010411unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413 return fixup(self, fixcapitalize);
10414}
10415
10416#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010417PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010418 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010419\n\
10420Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010421normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010422
10423static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010424unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010425{
10426 PyObject *list;
10427 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010428 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430 /* Split into words */
10431 list = split(self, NULL, -1);
10432 if (!list)
10433 return NULL;
10434
10435 /* Capitalize each word */
10436 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010437 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010438 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010439 if (item == NULL)
10440 goto onError;
10441 Py_DECREF(PyList_GET_ITEM(list, i));
10442 PyList_SET_ITEM(list, i, item);
10443 }
10444
10445 /* Join the words to form a new string */
10446 item = PyUnicode_Join(NULL, list);
10447
Benjamin Peterson29060642009-01-31 22:14:21 +000010448 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010449 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010450 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451}
10452#endif
10453
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010454/* Argument converter. Coerces to a single unicode character */
10455
10456static int
10457convert_uc(PyObject *obj, void *addr)
10458{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010460 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010461
Benjamin Peterson14339b62009-01-31 16:36:08 +000010462 uniobj = PyUnicode_FromObject(obj);
10463 if (uniobj == NULL) {
10464 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010465 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010466 return 0;
10467 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010469 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010470 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010471 Py_DECREF(uniobj);
10472 return 0;
10473 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010475 Py_DECREF(uniobj);
10476 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010477}
10478
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010479PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010480 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010482Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010483done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484
10485static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010486unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010488 Py_ssize_t marg, left;
10489 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 Py_UCS4 fillchar = ' ';
10491
Victor Stinnere9a29352011-10-01 02:14:59 +020010492 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494
Victor Stinnere9a29352011-10-01 02:14:59 +020010495 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010496 return NULL;
10497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010500 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010501 }
10502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504 left = marg / 2 + (marg & width & 1);
10505
Victor Stinner9310abb2011-10-05 00:59:23 +020010506 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507}
10508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509/* This function assumes that str1 and str2 are readied by the caller. */
10510
Marc-André Lemburge5034372000-08-08 08:04:29 +000010511static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010512unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010514 int kind1, kind2;
10515 void *data1, *data2;
10516 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 kind1 = PyUnicode_KIND(str1);
10519 kind2 = PyUnicode_KIND(str2);
10520 data1 = PyUnicode_DATA(str1);
10521 data2 = PyUnicode_DATA(str2);
10522 len1 = PyUnicode_GET_LENGTH(str1);
10523 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 for (i = 0; i < len1 && i < len2; ++i) {
10526 Py_UCS4 c1, c2;
10527 c1 = PyUnicode_READ(kind1, data1, i);
10528 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010529
10530 if (c1 != c2)
10531 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010532 }
10533
10534 return (len1 < len2) ? -1 : (len1 != len2);
10535}
10536
Alexander Belopolsky40018472011-02-26 01:02:56 +000010537int
10538PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010539{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10541 if (PyUnicode_READY(left) == -1 ||
10542 PyUnicode_READY(right) == -1)
10543 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010544 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010545 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010546 PyErr_Format(PyExc_TypeError,
10547 "Can't compare %.100s and %.100s",
10548 left->ob_type->tp_name,
10549 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550 return -1;
10551}
10552
Martin v. Löwis5b222132007-06-10 09:51:05 +000010553int
10554PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10555{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 Py_ssize_t i;
10557 int kind;
10558 void *data;
10559 Py_UCS4 chr;
10560
Victor Stinner910337b2011-10-03 03:20:16 +020010561 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 if (PyUnicode_READY(uni) == -1)
10563 return -1;
10564 kind = PyUnicode_KIND(uni);
10565 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010566 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10568 if (chr != str[i])
10569 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010570 /* This check keeps Python strings that end in '\0' from comparing equal
10571 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010573 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010574 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010575 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010576 return 0;
10577}
10578
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010579
Benjamin Peterson29060642009-01-31 22:14:21 +000010580#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010581 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010582
Alexander Belopolsky40018472011-02-26 01:02:56 +000010583PyObject *
10584PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010585{
10586 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010587
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010588 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10589 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (PyUnicode_READY(left) == -1 ||
10591 PyUnicode_READY(right) == -1)
10592 return NULL;
10593 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10594 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010595 if (op == Py_EQ) {
10596 Py_INCREF(Py_False);
10597 return Py_False;
10598 }
10599 if (op == Py_NE) {
10600 Py_INCREF(Py_True);
10601 return Py_True;
10602 }
10603 }
10604 if (left == right)
10605 result = 0;
10606 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010607 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010608
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010609 /* Convert the return value to a Boolean */
10610 switch (op) {
10611 case Py_EQ:
10612 v = TEST_COND(result == 0);
10613 break;
10614 case Py_NE:
10615 v = TEST_COND(result != 0);
10616 break;
10617 case Py_LE:
10618 v = TEST_COND(result <= 0);
10619 break;
10620 case Py_GE:
10621 v = TEST_COND(result >= 0);
10622 break;
10623 case Py_LT:
10624 v = TEST_COND(result == -1);
10625 break;
10626 case Py_GT:
10627 v = TEST_COND(result == 1);
10628 break;
10629 default:
10630 PyErr_BadArgument();
10631 return NULL;
10632 }
10633 Py_INCREF(v);
10634 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010635 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010636
Brian Curtindfc80e32011-08-10 20:28:54 -050010637 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010638}
10639
Alexander Belopolsky40018472011-02-26 01:02:56 +000010640int
10641PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010642{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010643 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 int kind1, kind2, kind;
10645 void *buf1, *buf2;
10646 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010647 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010648
10649 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010650 sub = PyUnicode_FromObject(element);
10651 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010652 PyErr_Format(PyExc_TypeError,
10653 "'in <string>' requires string as left operand, not %s",
10654 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010655 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 if (PyUnicode_READY(sub) == -1)
10658 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010659
Thomas Wouters477c8d52006-05-27 19:21:47 +000010660 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010661 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 Py_DECREF(sub);
10663 return -1;
10664 }
10665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 kind1 = PyUnicode_KIND(str);
10667 kind2 = PyUnicode_KIND(sub);
10668 kind = kind1 > kind2 ? kind1 : kind2;
10669 buf1 = PyUnicode_DATA(str);
10670 buf2 = PyUnicode_DATA(sub);
10671 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010672 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 if (!buf1) {
10674 Py_DECREF(sub);
10675 return -1;
10676 }
10677 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010678 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 if (!buf2) {
10680 Py_DECREF(sub);
10681 if (kind1 != kind) PyMem_Free(buf1);
10682 return -1;
10683 }
10684 len1 = PyUnicode_GET_LENGTH(str);
10685 len2 = PyUnicode_GET_LENGTH(sub);
10686
10687 switch(kind) {
10688 case PyUnicode_1BYTE_KIND:
10689 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10690 break;
10691 case PyUnicode_2BYTE_KIND:
10692 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10693 break;
10694 case PyUnicode_4BYTE_KIND:
10695 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10696 break;
10697 default:
10698 result = -1;
10699 assert(0);
10700 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010701
10702 Py_DECREF(str);
10703 Py_DECREF(sub);
10704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705 if (kind1 != kind)
10706 PyMem_Free(buf1);
10707 if (kind2 != kind)
10708 PyMem_Free(buf2);
10709
Guido van Rossum403d68b2000-03-13 15:55:09 +000010710 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010711}
10712
Guido van Rossumd57fd912000-03-10 22:53:23 +000010713/* Concat to string or Unicode object giving a new Unicode object. */
10714
Alexander Belopolsky40018472011-02-26 01:02:56 +000010715PyObject *
10716PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010718 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010719 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720
10721 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010722 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010724 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010725 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010727 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010728
10729 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010730 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010731 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010733 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010734 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010735 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010736 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010737 }
10738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010740 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10741 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 w = PyUnicode_New(
10745 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10746 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010748 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010749 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10750 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751 Py_DECREF(u);
10752 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010753 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755
Benjamin Peterson29060642009-01-31 22:14:21 +000010756 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757 Py_XDECREF(u);
10758 Py_XDECREF(v);
10759 return NULL;
10760}
10761
Victor Stinnerb0923652011-10-04 01:17:31 +020010762static void
10763unicode_append_inplace(PyObject **p_left, PyObject *right)
10764{
10765 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010766
10767 assert(PyUnicode_IS_READY(*p_left));
10768 assert(PyUnicode_IS_READY(right));
10769
10770 left_len = PyUnicode_GET_LENGTH(*p_left);
10771 right_len = PyUnicode_GET_LENGTH(right);
10772 if (left_len > PY_SSIZE_T_MAX - right_len) {
10773 PyErr_SetString(PyExc_OverflowError,
10774 "strings are too large to concat");
10775 goto error;
10776 }
10777 new_len = left_len + right_len;
10778
10779 /* Now we own the last reference to 'left', so we can resize it
10780 * in-place.
10781 */
10782 if (unicode_resize(p_left, new_len) != 0) {
10783 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10784 * deallocated so it cannot be put back into
10785 * 'variable'. The MemoryError is raised when there
10786 * is no value in 'variable', which might (very
10787 * remotely) be a cause of incompatibilities.
10788 */
10789 goto error;
10790 }
10791 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010792 copy_characters(*p_left, left_len, right, 0, right_len);
10793 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010794 return;
10795
10796error:
10797 Py_DECREF(*p_left);
10798 *p_left = NULL;
10799}
10800
Walter Dörwald1ab83302007-05-18 17:15:44 +000010801void
Victor Stinner23e56682011-10-03 03:54:37 +020010802PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010803{
Victor Stinner23e56682011-10-03 03:54:37 +020010804 PyObject *left, *res;
10805
10806 if (p_left == NULL) {
10807 if (!PyErr_Occurred())
10808 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010809 return;
10810 }
Victor Stinner23e56682011-10-03 03:54:37 +020010811 left = *p_left;
10812 if (right == NULL || !PyUnicode_Check(left)) {
10813 if (!PyErr_Occurred())
10814 PyErr_BadInternalCall();
10815 goto error;
10816 }
10817
Victor Stinnere1335c72011-10-04 20:53:03 +020010818 if (PyUnicode_READY(left))
10819 goto error;
10820 if (PyUnicode_READY(right))
10821 goto error;
10822
Victor Stinner23e56682011-10-03 03:54:37 +020010823 if (PyUnicode_CheckExact(left) && left != unicode_empty
10824 && PyUnicode_CheckExact(right) && right != unicode_empty
10825 && unicode_resizable(left)
10826 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10827 || _PyUnicode_WSTR(left) != NULL))
10828 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010829 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10830 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010831 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010832 not so different than duplicating the string. */
10833 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010834 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010835 unicode_append_inplace(p_left, right);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010836 assert(p_left == NULL || _PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010837 return;
10838 }
10839 }
10840
10841 res = PyUnicode_Concat(left, right);
10842 if (res == NULL)
10843 goto error;
10844 Py_DECREF(left);
10845 *p_left = res;
10846 return;
10847
10848error:
10849 Py_DECREF(*p_left);
10850 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010851}
10852
10853void
10854PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10855{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010856 PyUnicode_Append(pleft, right);
10857 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010858}
10859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010860PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010861 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010863Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010864string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010865interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010866
10867static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010868unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010870 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010871 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010872 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010873 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010874 int kind1, kind2, kind;
10875 void *buf1, *buf2;
10876 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877
Jesus Ceaac451502011-04-20 17:09:23 +020010878 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10879 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010880 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010882 kind1 = PyUnicode_KIND(self);
10883 kind2 = PyUnicode_KIND(substring);
10884 kind = kind1 > kind2 ? kind1 : kind2;
10885 buf1 = PyUnicode_DATA(self);
10886 buf2 = PyUnicode_DATA(substring);
10887 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010888 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010889 if (!buf1) {
10890 Py_DECREF(substring);
10891 return NULL;
10892 }
10893 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010894 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 if (!buf2) {
10896 Py_DECREF(substring);
10897 if (kind1 != kind) PyMem_Free(buf1);
10898 return NULL;
10899 }
10900 len1 = PyUnicode_GET_LENGTH(self);
10901 len2 = PyUnicode_GET_LENGTH(substring);
10902
10903 ADJUST_INDICES(start, end, len1);
10904 switch(kind) {
10905 case PyUnicode_1BYTE_KIND:
10906 iresult = ucs1lib_count(
10907 ((Py_UCS1*)buf1) + start, end - start,
10908 buf2, len2, PY_SSIZE_T_MAX
10909 );
10910 break;
10911 case PyUnicode_2BYTE_KIND:
10912 iresult = ucs2lib_count(
10913 ((Py_UCS2*)buf1) + start, end - start,
10914 buf2, len2, PY_SSIZE_T_MAX
10915 );
10916 break;
10917 case PyUnicode_4BYTE_KIND:
10918 iresult = ucs4lib_count(
10919 ((Py_UCS4*)buf1) + start, end - start,
10920 buf2, len2, PY_SSIZE_T_MAX
10921 );
10922 break;
10923 default:
10924 assert(0); iresult = 0;
10925 }
10926
10927 result = PyLong_FromSsize_t(iresult);
10928
10929 if (kind1 != kind)
10930 PyMem_Free(buf1);
10931 if (kind2 != kind)
10932 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933
10934 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010935
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 return result;
10937}
10938
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010939PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010940 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010942Encode S using the codec registered for encoding. Default encoding\n\
10943is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010944handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010945a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10946'xmlcharrefreplace' as well as any other name registered with\n\
10947codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948
10949static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010950unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010952 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 char *encoding = NULL;
10954 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010955
Benjamin Peterson308d6372009-09-18 21:42:35 +000010956 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10957 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010959 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010960}
10961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010962PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010963 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964\n\
10965Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010966If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967
10968static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010969unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010971 Py_ssize_t i, j, line_pos, src_len, incr;
10972 Py_UCS4 ch;
10973 PyObject *u;
10974 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010976 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010977 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978
10979 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010980 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981
Antoine Pitrou22425222011-10-04 19:10:51 +020010982 if (PyUnicode_READY(self) == -1)
10983 return NULL;
10984
Thomas Wouters7e474022000-07-16 12:04:32 +000010985 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010986 src_len = PyUnicode_GET_LENGTH(self);
10987 i = j = line_pos = 0;
10988 kind = PyUnicode_KIND(self);
10989 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010990 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010991 for (; i < src_len; i++) {
10992 ch = PyUnicode_READ(kind, src_data, i);
10993 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010994 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010995 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010996 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010997 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010998 goto overflow;
10999 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011000 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011001 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011002 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011004 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011005 goto overflow;
11006 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011008 if (ch == '\n' || ch == '\r')
11009 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011011 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011012 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010011013 Py_INCREF(self);
11014 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011015 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011016
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011018 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 if (!u)
11020 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011021 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022
Antoine Pitroue71d5742011-10-04 15:55:09 +020011023 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024
Antoine Pitroue71d5742011-10-04 15:55:09 +020011025 for (; i < src_len; i++) {
11026 ch = PyUnicode_READ(kind, src_data, i);
11027 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011028 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011029 incr = tabsize - (line_pos % tabsize);
11030 line_pos += incr;
11031 while (incr--) {
11032 PyUnicode_WRITE(kind, dest_data, j, ' ');
11033 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011034 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011035 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011036 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011038 line_pos++;
11039 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011040 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011041 if (ch == '\n' || ch == '\r')
11042 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011044 }
11045 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011046 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011047
Antoine Pitroue71d5742011-10-04 15:55:09 +020011048 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011049 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11050 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051}
11052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011053PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011054 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055\n\
11056Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011057such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058arguments start and end are interpreted as in slice notation.\n\
11059\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011060Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061
11062static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011063unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011065 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011066 Py_ssize_t start;
11067 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011068 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069
Jesus Ceaac451502011-04-20 17:09:23 +020011070 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11071 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 if (PyUnicode_READY(self) == -1)
11075 return NULL;
11076 if (PyUnicode_READY(substring) == -1)
11077 return NULL;
11078
Victor Stinner7931d9a2011-11-04 00:22:48 +010011079 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080
11081 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083 if (result == -2)
11084 return NULL;
11085
Christian Heimes217cfd12007-12-02 14:31:20 +000011086 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087}
11088
11089static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011090unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011092 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11093 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011095 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096}
11097
Guido van Rossumc2504932007-09-18 19:42:40 +000011098/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011099 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011100static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011101unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102{
Guido van Rossumc2504932007-09-18 19:42:40 +000011103 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011104 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011106 if (_PyUnicode_HASH(self) != -1)
11107 return _PyUnicode_HASH(self);
11108 if (PyUnicode_READY(self) == -1)
11109 return -1;
11110 len = PyUnicode_GET_LENGTH(self);
11111
11112 /* The hash function as a macro, gets expanded three times below. */
11113#define HASH(P) \
11114 x = (Py_uhash_t)*P << 7; \
11115 while (--len >= 0) \
11116 x = (1000003*x) ^ (Py_uhash_t)*P++;
11117
11118 switch (PyUnicode_KIND(self)) {
11119 case PyUnicode_1BYTE_KIND: {
11120 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11121 HASH(c);
11122 break;
11123 }
11124 case PyUnicode_2BYTE_KIND: {
11125 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11126 HASH(s);
11127 break;
11128 }
11129 default: {
11130 Py_UCS4 *l;
11131 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11132 "Impossible switch case in unicode_hash");
11133 l = PyUnicode_4BYTE_DATA(self);
11134 HASH(l);
11135 break;
11136 }
11137 }
11138 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11139
Guido van Rossumc2504932007-09-18 19:42:40 +000011140 if (x == -1)
11141 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011143 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011147PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011148 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011150Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151
11152static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011153unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011155 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011156 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011157 Py_ssize_t start;
11158 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159
Jesus Ceaac451502011-04-20 17:09:23 +020011160 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11161 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011164 if (PyUnicode_READY(self) == -1)
11165 return NULL;
11166 if (PyUnicode_READY(substring) == -1)
11167 return NULL;
11168
Victor Stinner7931d9a2011-11-04 00:22:48 +010011169 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170
11171 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 if (result == -2)
11174 return NULL;
11175
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176 if (result < 0) {
11177 PyErr_SetString(PyExc_ValueError, "substring not found");
11178 return NULL;
11179 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011180
Christian Heimes217cfd12007-12-02 14:31:20 +000011181 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182}
11183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011184PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011185 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011187Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011188at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189
11190static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011191unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 Py_ssize_t i, length;
11194 int kind;
11195 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 int cased;
11197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198 if (PyUnicode_READY(self) == -1)
11199 return NULL;
11200 length = PyUnicode_GET_LENGTH(self);
11201 kind = PyUnicode_KIND(self);
11202 data = PyUnicode_DATA(self);
11203
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 if (length == 1)
11206 return PyBool_FromLong(
11207 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011209 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011210 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011211 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011212
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 for (i = 0; i < length; i++) {
11215 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011216
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11218 return PyBool_FromLong(0);
11219 else if (!cased && Py_UNICODE_ISLOWER(ch))
11220 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011222 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223}
11224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011225PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011228Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011229at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230
11231static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011232unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234 Py_ssize_t i, length;
11235 int kind;
11236 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237 int cased;
11238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 if (PyUnicode_READY(self) == -1)
11240 return NULL;
11241 length = PyUnicode_GET_LENGTH(self);
11242 kind = PyUnicode_KIND(self);
11243 data = PyUnicode_DATA(self);
11244
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 if (length == 1)
11247 return PyBool_FromLong(
11248 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011250 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011252 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011253
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255 for (i = 0; i < length; i++) {
11256 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011257
Benjamin Peterson29060642009-01-31 22:14:21 +000011258 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11259 return PyBool_FromLong(0);
11260 else if (!cased && Py_UNICODE_ISUPPER(ch))
11261 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011263 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264}
11265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011266PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011267 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011269Return True if S is a titlecased string and there is at least one\n\
11270character in S, i.e. upper- and titlecase characters may only\n\
11271follow uncased characters and lowercase characters only cased ones.\n\
11272Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273
11274static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011275unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 Py_ssize_t i, length;
11278 int kind;
11279 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280 int cased, previous_is_cased;
11281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011282 if (PyUnicode_READY(self) == -1)
11283 return NULL;
11284 length = PyUnicode_GET_LENGTH(self);
11285 kind = PyUnicode_KIND(self);
11286 data = PyUnicode_DATA(self);
11287
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 if (length == 1) {
11290 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11291 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11292 (Py_UNICODE_ISUPPER(ch) != 0));
11293 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011295 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011297 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011298
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299 cased = 0;
11300 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 for (i = 0; i < length; i++) {
11302 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011303
Benjamin Peterson29060642009-01-31 22:14:21 +000011304 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11305 if (previous_is_cased)
11306 return PyBool_FromLong(0);
11307 previous_is_cased = 1;
11308 cased = 1;
11309 }
11310 else if (Py_UNICODE_ISLOWER(ch)) {
11311 if (!previous_is_cased)
11312 return PyBool_FromLong(0);
11313 previous_is_cased = 1;
11314 cased = 1;
11315 }
11316 else
11317 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011319 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320}
11321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011322PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011323 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011325Return True if all characters in S are whitespace\n\
11326and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327
11328static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011329unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 Py_ssize_t i, length;
11332 int kind;
11333 void *data;
11334
11335 if (PyUnicode_READY(self) == -1)
11336 return NULL;
11337 length = PyUnicode_GET_LENGTH(self);
11338 kind = PyUnicode_KIND(self);
11339 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011342 if (length == 1)
11343 return PyBool_FromLong(
11344 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011346 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 for (i = 0; i < length; i++) {
11351 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011352 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011353 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011355 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356}
11357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011358PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011361Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011362and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011363
11364static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011365unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 Py_ssize_t i, length;
11368 int kind;
11369 void *data;
11370
11371 if (PyUnicode_READY(self) == -1)
11372 return NULL;
11373 length = PyUnicode_GET_LENGTH(self);
11374 kind = PyUnicode_KIND(self);
11375 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011376
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011377 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 if (length == 1)
11379 return PyBool_FromLong(
11380 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011381
11382 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011385
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 for (i = 0; i < length; i++) {
11387 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011388 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011389 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011390 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011391}
11392
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011393PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011395\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011396Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011397and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011398
11399static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011400unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011401{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 int kind;
11403 void *data;
11404 Py_ssize_t len, i;
11405
11406 if (PyUnicode_READY(self) == -1)
11407 return NULL;
11408
11409 kind = PyUnicode_KIND(self);
11410 data = PyUnicode_DATA(self);
11411 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011412
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011413 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011414 if (len == 1) {
11415 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11416 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11417 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011418
11419 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011421 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 for (i = 0; i < len; i++) {
11424 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011425 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011427 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011428 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011429}
11430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011431PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011434Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011435False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
11437static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011438unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 Py_ssize_t i, length;
11441 int kind;
11442 void *data;
11443
11444 if (PyUnicode_READY(self) == -1)
11445 return NULL;
11446 length = PyUnicode_GET_LENGTH(self);
11447 kind = PyUnicode_KIND(self);
11448 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 if (length == 1)
11452 return PyBool_FromLong(
11453 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011455 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011456 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 for (i = 0; i < length; i++) {
11460 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011463 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464}
11465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011466PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011467 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011469Return True if all characters in S are digits\n\
11470and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471
11472static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011473unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 Py_ssize_t i, length;
11476 int kind;
11477 void *data;
11478
11479 if (PyUnicode_READY(self) == -1)
11480 return NULL;
11481 length = PyUnicode_GET_LENGTH(self);
11482 kind = PyUnicode_KIND(self);
11483 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 if (length == 1) {
11487 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11488 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11489 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011491 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011492 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 for (i = 0; i < length; i++) {
11496 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011499 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500}
11501
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011502PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011503 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011505Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011506False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507
11508static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011509unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 Py_ssize_t i, length;
11512 int kind;
11513 void *data;
11514
11515 if (PyUnicode_READY(self) == -1)
11516 return NULL;
11517 length = PyUnicode_GET_LENGTH(self);
11518 kind = PyUnicode_KIND(self);
11519 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 if (length == 1)
11523 return PyBool_FromLong(
11524 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011526 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 for (i = 0; i < length; i++) {
11531 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011532 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011534 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535}
11536
Martin v. Löwis47383402007-08-15 07:32:56 +000011537int
11538PyUnicode_IsIdentifier(PyObject *self)
11539{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 int kind;
11541 void *data;
11542 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011543 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 if (PyUnicode_READY(self) == -1) {
11546 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011547 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 }
11549
11550 /* Special case for empty strings */
11551 if (PyUnicode_GET_LENGTH(self) == 0)
11552 return 0;
11553 kind = PyUnicode_KIND(self);
11554 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011555
11556 /* PEP 3131 says that the first character must be in
11557 XID_Start and subsequent characters in XID_Continue,
11558 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011559 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011560 letters, digits, underscore). However, given the current
11561 definition of XID_Start and XID_Continue, it is sufficient
11562 to check just for these, except that _ must be allowed
11563 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011565 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011566 return 0;
11567
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011568 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011569 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011571 return 1;
11572}
11573
11574PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011575 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011576\n\
11577Return True if S is a valid identifier according\n\
11578to the language definition.");
11579
11580static PyObject*
11581unicode_isidentifier(PyObject *self)
11582{
11583 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11584}
11585
Georg Brandl559e5d72008-06-11 18:37:52 +000011586PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011587 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011588\n\
11589Return True if all characters in S are considered\n\
11590printable in repr() or S is empty, False otherwise.");
11591
11592static PyObject*
11593unicode_isprintable(PyObject *self)
11594{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595 Py_ssize_t i, length;
11596 int kind;
11597 void *data;
11598
11599 if (PyUnicode_READY(self) == -1)
11600 return NULL;
11601 length = PyUnicode_GET_LENGTH(self);
11602 kind = PyUnicode_KIND(self);
11603 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011604
11605 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 if (length == 1)
11607 return PyBool_FromLong(
11608 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011610 for (i = 0; i < length; i++) {
11611 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011612 Py_RETURN_FALSE;
11613 }
11614 }
11615 Py_RETURN_TRUE;
11616}
11617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011618PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011619 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620\n\
11621Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011622iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623
11624static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011625unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011627 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628}
11629
Martin v. Löwis18e16552006-02-15 17:27:45 +000011630static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011631unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (PyUnicode_READY(self) == -1)
11634 return -1;
11635 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636}
11637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011638PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011641Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011642done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
11644static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011645unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011647 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 Py_UCS4 fillchar = ' ';
11649
11650 if (PyUnicode_READY(self) == -1)
11651 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011652
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011653 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654 return NULL;
11655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011658 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659 }
11660
Victor Stinner7931d9a2011-11-04 00:22:48 +010011661 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662}
11663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668
11669static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011670unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672 return fixup(self, fixlower);
11673}
11674
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011675#define LEFTSTRIP 0
11676#define RIGHTSTRIP 1
11677#define BOTHSTRIP 2
11678
11679/* Arrays indexed by above */
11680static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11681
11682#define STRIPNAME(i) (stripformat[i]+3)
11683
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011684/* externally visible for str.strip(unicode) */
11685PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011686_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011687{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 void *data;
11689 int kind;
11690 Py_ssize_t i, j, len;
11691 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11694 return NULL;
11695
11696 kind = PyUnicode_KIND(self);
11697 data = PyUnicode_DATA(self);
11698 len = PyUnicode_GET_LENGTH(self);
11699 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11700 PyUnicode_DATA(sepobj),
11701 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011702
Benjamin Peterson14339b62009-01-31 16:36:08 +000011703 i = 0;
11704 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 while (i < len &&
11706 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011707 i++;
11708 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011709 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710
Benjamin Peterson14339b62009-01-31 16:36:08 +000011711 j = len;
11712 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011713 do {
11714 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 } while (j >= i &&
11716 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011717 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011718 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011719
Victor Stinner7931d9a2011-11-04 00:22:48 +010011720 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721}
11722
11723PyObject*
11724PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11725{
11726 unsigned char *data;
11727 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011728 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729
Victor Stinnerde636f32011-10-01 03:55:54 +020011730 if (PyUnicode_READY(self) == -1)
11731 return NULL;
11732
11733 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11734
Victor Stinner12bab6d2011-10-01 01:53:49 +020011735 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011737 if (PyUnicode_CheckExact(self)) {
11738 Py_INCREF(self);
11739 return self;
11740 }
11741 else
11742 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 }
11744
Victor Stinner12bab6d2011-10-01 01:53:49 +020011745 length = end - start;
11746 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011747 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748
Victor Stinnerde636f32011-10-01 03:55:54 +020011749 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011750 PyErr_SetString(PyExc_IndexError, "string index out of range");
11751 return NULL;
11752 }
11753
Victor Stinnerb9275c12011-10-05 14:01:42 +020011754 if (PyUnicode_IS_ASCII(self)) {
11755 kind = PyUnicode_KIND(self);
11756 data = PyUnicode_1BYTE_DATA(self);
11757 return unicode_fromascii(data + start, length);
11758 }
11759 else {
11760 kind = PyUnicode_KIND(self);
11761 data = PyUnicode_1BYTE_DATA(self);
11762 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011763 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011764 length);
11765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767
11768static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011769do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 int kind;
11772 void *data;
11773 Py_ssize_t len, i, j;
11774
11775 if (PyUnicode_READY(self) == -1)
11776 return NULL;
11777
11778 kind = PyUnicode_KIND(self);
11779 data = PyUnicode_DATA(self);
11780 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011781
Benjamin Peterson14339b62009-01-31 16:36:08 +000011782 i = 0;
11783 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011785 i++;
11786 }
11787 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
Benjamin Peterson14339b62009-01-31 16:36:08 +000011789 j = len;
11790 if (striptype != LEFTSTRIP) {
11791 do {
11792 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011794 j++;
11795 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796
Victor Stinner7931d9a2011-11-04 00:22:48 +010011797 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798}
11799
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011800
11801static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011802do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011803{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011804 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011805
Benjamin Peterson14339b62009-01-31 16:36:08 +000011806 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11807 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011808
Benjamin Peterson14339b62009-01-31 16:36:08 +000011809 if (sep != NULL && sep != Py_None) {
11810 if (PyUnicode_Check(sep))
11811 return _PyUnicode_XStrip(self, striptype, sep);
11812 else {
11813 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011814 "%s arg must be None or str",
11815 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011816 return NULL;
11817 }
11818 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011819
Benjamin Peterson14339b62009-01-31 16:36:08 +000011820 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011821}
11822
11823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011824PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011825 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011826\n\
11827Return a copy of the string S with leading and trailing\n\
11828whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011829If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830
11831static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011832unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011833{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011834 if (PyTuple_GET_SIZE(args) == 0)
11835 return do_strip(self, BOTHSTRIP); /* Common case */
11836 else
11837 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011838}
11839
11840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011841PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011842 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011843\n\
11844Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011845If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011846
11847static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011848unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011849{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011850 if (PyTuple_GET_SIZE(args) == 0)
11851 return do_strip(self, LEFTSTRIP); /* Common case */
11852 else
11853 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011854}
11855
11856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011857PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011858 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011859\n\
11860Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011861If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011862
11863static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011864unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011865{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011866 if (PyTuple_GET_SIZE(args) == 0)
11867 return do_strip(self, RIGHTSTRIP); /* Common case */
11868 else
11869 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011870}
11871
11872
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011874unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011876 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011878
Georg Brandl222de0f2009-04-12 12:01:50 +000011879 if (len < 1) {
11880 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011881 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011882 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883
Tim Peters7a29bd52001-09-12 03:03:31 +000011884 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 /* no repeat, return original string */
11886 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011887 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888 }
Tim Peters8f422462000-09-09 06:13:41 +000011889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 if (PyUnicode_READY(str) == -1)
11891 return NULL;
11892
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011893 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011894 PyErr_SetString(PyExc_OverflowError,
11895 "repeated string is too long");
11896 return NULL;
11897 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011898 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011899
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011900 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901 if (!u)
11902 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011903 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 if (PyUnicode_GET_LENGTH(str) == 1) {
11906 const int kind = PyUnicode_KIND(str);
11907 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11908 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011909 if (kind == PyUnicode_1BYTE_KIND)
11910 memset(to, (unsigned char)fill_char, len);
11911 else {
11912 for (n = 0; n < len; ++n)
11913 PyUnicode_WRITE(kind, to, n, fill_char);
11914 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 }
11916 else {
11917 /* number of characters copied this far */
11918 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011919 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 char *to = (char *) PyUnicode_DATA(u);
11921 Py_MEMCPY(to, PyUnicode_DATA(str),
11922 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011923 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 n = (done <= nchars-done) ? done : nchars-done;
11925 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011926 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011927 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928 }
11929
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011930 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011931 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932}
11933
Alexander Belopolsky40018472011-02-26 01:02:56 +000011934PyObject *
11935PyUnicode_Replace(PyObject *obj,
11936 PyObject *subobj,
11937 PyObject *replobj,
11938 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939{
11940 PyObject *self;
11941 PyObject *str1;
11942 PyObject *str2;
11943 PyObject *result;
11944
11945 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011946 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011947 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011949 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 Py_DECREF(self);
11951 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952 }
11953 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011954 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 Py_DECREF(self);
11956 Py_DECREF(str1);
11957 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960 Py_DECREF(self);
11961 Py_DECREF(str1);
11962 Py_DECREF(str2);
11963 return result;
11964}
11965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011966PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011967 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968\n\
11969Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011970old replaced by new. If the optional argument count is\n\
11971given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972
11973static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011974unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 PyObject *str1;
11977 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011978 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979 PyObject *result;
11980
Martin v. Löwis18e16552006-02-15 17:27:45 +000011981 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011982 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011984 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 str1 = PyUnicode_FromObject(str1);
11986 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11987 return NULL;
11988 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011989 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011990 Py_DECREF(str1);
11991 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011992 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993
11994 result = replace(self, str1, str2, maxcount);
11995
11996 Py_DECREF(str1);
11997 Py_DECREF(str2);
11998 return result;
11999}
12000
Alexander Belopolsky40018472011-02-26 01:02:56 +000012001static PyObject *
12002unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012004 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012005 Py_ssize_t isize;
12006 Py_ssize_t osize, squote, dquote, i, o;
12007 Py_UCS4 max, quote;
12008 int ikind, okind;
12009 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012012 return NULL;
12013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 isize = PyUnicode_GET_LENGTH(unicode);
12015 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012017 /* Compute length of output, quote characters, and
12018 maximum character */
12019 osize = 2; /* quotes */
12020 max = 127;
12021 squote = dquote = 0;
12022 ikind = PyUnicode_KIND(unicode);
12023 for (i = 0; i < isize; i++) {
12024 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12025 switch (ch) {
12026 case '\'': squote++; osize++; break;
12027 case '"': dquote++; osize++; break;
12028 case '\\': case '\t': case '\r': case '\n':
12029 osize += 2; break;
12030 default:
12031 /* Fast-path ASCII */
12032 if (ch < ' ' || ch == 0x7f)
12033 osize += 4; /* \xHH */
12034 else if (ch < 0x7f)
12035 osize++;
12036 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12037 osize++;
12038 max = ch > max ? ch : max;
12039 }
12040 else if (ch < 0x100)
12041 osize += 4; /* \xHH */
12042 else if (ch < 0x10000)
12043 osize += 6; /* \uHHHH */
12044 else
12045 osize += 10; /* \uHHHHHHHH */
12046 }
12047 }
12048
12049 quote = '\'';
12050 if (squote) {
12051 if (dquote)
12052 /* Both squote and dquote present. Use squote,
12053 and escape them */
12054 osize += squote;
12055 else
12056 quote = '"';
12057 }
12058
12059 repr = PyUnicode_New(osize, max);
12060 if (repr == NULL)
12061 return NULL;
12062 okind = PyUnicode_KIND(repr);
12063 odata = PyUnicode_DATA(repr);
12064
12065 PyUnicode_WRITE(okind, odata, 0, quote);
12066 PyUnicode_WRITE(okind, odata, osize-1, quote);
12067
12068 for (i = 0, o = 1; i < isize; i++) {
12069 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012070
12071 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012072 if ((ch == quote) || (ch == '\\')) {
12073 PyUnicode_WRITE(okind, odata, o++, '\\');
12074 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012075 continue;
12076 }
12077
Benjamin Peterson29060642009-01-31 22:14:21 +000012078 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012079 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 PyUnicode_WRITE(okind, odata, o++, '\\');
12081 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012082 }
12083 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012084 PyUnicode_WRITE(okind, odata, o++, '\\');
12085 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012086 }
12087 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 PyUnicode_WRITE(okind, odata, o++, '\\');
12089 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012090 }
12091
12092 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012093 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094 PyUnicode_WRITE(okind, odata, o++, '\\');
12095 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012096 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12097 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012098 }
12099
Georg Brandl559e5d72008-06-11 18:37:52 +000012100 /* Copy ASCII characters as-is */
12101 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012103 }
12104
Benjamin Peterson29060642009-01-31 22:14:21 +000012105 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012106 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012107 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012108 (categories Z* and C* except ASCII space)
12109 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012110 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012111 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 if (ch <= 0xff) {
12113 PyUnicode_WRITE(okind, odata, o++, '\\');
12114 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012115 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12116 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012117 }
12118 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012119 else if (ch >= 0x10000) {
12120 PyUnicode_WRITE(okind, odata, o++, '\\');
12121 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012122 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12123 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12124 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12125 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12126 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12127 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12128 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12129 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012130 }
12131 /* Map 16-bit characters to '\uxxxx' */
12132 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 PyUnicode_WRITE(okind, odata, o++, '\\');
12134 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012135 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12136 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12137 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12138 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012139 }
12140 }
12141 /* Copy characters as-is */
12142 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012144 }
12145 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012148 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012149 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150}
12151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012152PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154\n\
12155Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012156such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157arguments start and end are interpreted as in slice notation.\n\
12158\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012159Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160
12161static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012164 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012165 Py_ssize_t start;
12166 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012167 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168
Jesus Ceaac451502011-04-20 17:09:23 +020012169 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12170 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012171 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 if (PyUnicode_READY(self) == -1)
12174 return NULL;
12175 if (PyUnicode_READY(substring) == -1)
12176 return NULL;
12177
Victor Stinner7931d9a2011-11-04 00:22:48 +010012178 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
12180 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 if (result == -2)
12183 return NULL;
12184
Christian Heimes217cfd12007-12-02 14:31:20 +000012185 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186}
12187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012188PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012189 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012191Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192
12193static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012196 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012197 Py_ssize_t start;
12198 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012199 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200
Jesus Ceaac451502011-04-20 17:09:23 +020012201 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12202 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012203 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 if (PyUnicode_READY(self) == -1)
12206 return NULL;
12207 if (PyUnicode_READY(substring) == -1)
12208 return NULL;
12209
Victor Stinner7931d9a2011-11-04 00:22:48 +010012210 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211
12212 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (result == -2)
12215 return NULL;
12216
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 if (result < 0) {
12218 PyErr_SetString(PyExc_ValueError, "substring not found");
12219 return NULL;
12220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221
Christian Heimes217cfd12007-12-02 14:31:20 +000012222 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223}
12224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012225PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012226 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012228Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012229done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230
12231static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012232unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012233{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012234 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 Py_UCS4 fillchar = ' ';
12236
Victor Stinnere9a29352011-10-01 02:14:59 +020012237 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012239
Victor Stinnere9a29352011-10-01 02:14:59 +020012240 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241 return NULL;
12242
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012243 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012245 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246 }
12247
Victor Stinner7931d9a2011-11-04 00:22:48 +010012248 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249}
12250
Alexander Belopolsky40018472011-02-26 01:02:56 +000012251PyObject *
12252PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253{
12254 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012255
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256 s = PyUnicode_FromObject(s);
12257 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012258 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012259 if (sep != NULL) {
12260 sep = PyUnicode_FromObject(sep);
12261 if (sep == NULL) {
12262 Py_DECREF(s);
12263 return NULL;
12264 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 }
12266
Victor Stinner9310abb2011-10-05 00:59:23 +020012267 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268
12269 Py_DECREF(s);
12270 Py_XDECREF(sep);
12271 return result;
12272}
12273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012274PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012275 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276\n\
12277Return a list of the words in S, using sep as the\n\
12278delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012279splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012280whitespace string is a separator and empty strings are\n\
12281removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282
12283static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012284unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285{
12286 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012287 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288
Martin v. Löwis18e16552006-02-15 17:27:45 +000012289 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 return NULL;
12291
12292 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012293 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012295 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012297 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298}
12299
Thomas Wouters477c8d52006-05-27 19:21:47 +000012300PyObject *
12301PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12302{
12303 PyObject* str_obj;
12304 PyObject* sep_obj;
12305 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 int kind1, kind2, kind;
12307 void *buf1 = NULL, *buf2 = NULL;
12308 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012309
12310 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012311 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012312 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012313 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012315 Py_DECREF(str_obj);
12316 return NULL;
12317 }
12318
Victor Stinner14f8f022011-10-05 20:58:25 +020012319 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012321 kind = Py_MAX(kind1, kind2);
12322 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012324 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 if (!buf1)
12326 goto onError;
12327 buf2 = PyUnicode_DATA(sep_obj);
12328 if (kind2 != kind)
12329 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12330 if (!buf2)
12331 goto onError;
12332 len1 = PyUnicode_GET_LENGTH(str_obj);
12333 len2 = PyUnicode_GET_LENGTH(sep_obj);
12334
Victor Stinner14f8f022011-10-05 20:58:25 +020012335 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012337 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12338 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12339 else
12340 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 break;
12342 case PyUnicode_2BYTE_KIND:
12343 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12344 break;
12345 case PyUnicode_4BYTE_KIND:
12346 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12347 break;
12348 default:
12349 assert(0);
12350 out = 0;
12351 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352
12353 Py_DECREF(sep_obj);
12354 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 if (kind1 != kind)
12356 PyMem_Free(buf1);
12357 if (kind2 != kind)
12358 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359
12360 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 onError:
12362 Py_DECREF(sep_obj);
12363 Py_DECREF(str_obj);
12364 if (kind1 != kind && buf1)
12365 PyMem_Free(buf1);
12366 if (kind2 != kind && buf2)
12367 PyMem_Free(buf2);
12368 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369}
12370
12371
12372PyObject *
12373PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12374{
12375 PyObject* str_obj;
12376 PyObject* sep_obj;
12377 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 int kind1, kind2, kind;
12379 void *buf1 = NULL, *buf2 = NULL;
12380 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012381
12382 str_obj = PyUnicode_FromObject(str_in);
12383 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012384 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012385 sep_obj = PyUnicode_FromObject(sep_in);
12386 if (!sep_obj) {
12387 Py_DECREF(str_obj);
12388 return NULL;
12389 }
12390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 kind1 = PyUnicode_KIND(str_in);
12392 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012393 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 buf1 = PyUnicode_DATA(str_in);
12395 if (kind1 != kind)
12396 buf1 = _PyUnicode_AsKind(str_in, kind);
12397 if (!buf1)
12398 goto onError;
12399 buf2 = PyUnicode_DATA(sep_obj);
12400 if (kind2 != kind)
12401 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12402 if (!buf2)
12403 goto onError;
12404 len1 = PyUnicode_GET_LENGTH(str_obj);
12405 len2 = PyUnicode_GET_LENGTH(sep_obj);
12406
12407 switch(PyUnicode_KIND(str_in)) {
12408 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012409 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12410 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12411 else
12412 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012413 break;
12414 case PyUnicode_2BYTE_KIND:
12415 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12416 break;
12417 case PyUnicode_4BYTE_KIND:
12418 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12419 break;
12420 default:
12421 assert(0);
12422 out = 0;
12423 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012424
12425 Py_DECREF(sep_obj);
12426 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 if (kind1 != kind)
12428 PyMem_Free(buf1);
12429 if (kind2 != kind)
12430 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
12432 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012433 onError:
12434 Py_DECREF(sep_obj);
12435 Py_DECREF(str_obj);
12436 if (kind1 != kind && buf1)
12437 PyMem_Free(buf1);
12438 if (kind2 != kind && buf2)
12439 PyMem_Free(buf2);
12440 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012441}
12442
12443PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012444 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012445\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012446Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012448found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012449
12450static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012451unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012452{
Victor Stinner9310abb2011-10-05 00:59:23 +020012453 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454}
12455
12456PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012457 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012458\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012459Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012460the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012461separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012462
12463static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012464unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012465{
Victor Stinner9310abb2011-10-05 00:59:23 +020012466 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012467}
12468
Alexander Belopolsky40018472011-02-26 01:02:56 +000012469PyObject *
12470PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012471{
12472 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012473
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012474 s = PyUnicode_FromObject(s);
12475 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012476 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012477 if (sep != NULL) {
12478 sep = PyUnicode_FromObject(sep);
12479 if (sep == NULL) {
12480 Py_DECREF(s);
12481 return NULL;
12482 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 }
12484
Victor Stinner9310abb2011-10-05 00:59:23 +020012485 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012486
12487 Py_DECREF(s);
12488 Py_XDECREF(sep);
12489 return result;
12490}
12491
12492PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012493 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012494\n\
12495Return a list of the words in S, using sep as the\n\
12496delimiter string, starting at the end of the string and\n\
12497working to the front. If maxsplit is given, at most maxsplit\n\
12498splits are done. If sep is not specified, any whitespace string\n\
12499is a separator.");
12500
12501static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012502unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012503{
12504 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012505 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012506
Martin v. Löwis18e16552006-02-15 17:27:45 +000012507 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012508 return NULL;
12509
12510 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012511 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012512 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012513 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012514 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012515 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012516}
12517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012518PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012519 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520\n\
12521Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012522Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012523is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524
12525static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012526unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012528 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012529 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012531 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12532 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533 return NULL;
12534
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012535 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536}
12537
12538static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012539PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540{
Walter Dörwald346737f2007-05-31 10:44:43 +000012541 if (PyUnicode_CheckExact(self)) {
12542 Py_INCREF(self);
12543 return self;
12544 } else
12545 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012546 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547}
12548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012549PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012550 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551\n\
12552Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012553and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554
12555static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012556unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558 return fixup(self, fixswapcase);
12559}
12560
Georg Brandlceee0772007-11-27 23:48:05 +000012561PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012562 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012563\n\
12564Return a translation table usable for str.translate().\n\
12565If there is only one argument, it must be a dictionary mapping Unicode\n\
12566ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012567Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012568If there are two arguments, they must be strings of equal length, and\n\
12569in the resulting dictionary, each character in x will be mapped to the\n\
12570character at the same position in y. If there is a third argument, it\n\
12571must be a string, whose characters will be mapped to None in the result.");
12572
12573static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012574unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012575{
12576 PyObject *x, *y = NULL, *z = NULL;
12577 PyObject *new = NULL, *key, *value;
12578 Py_ssize_t i = 0;
12579 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012580
Georg Brandlceee0772007-11-27 23:48:05 +000012581 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12582 return NULL;
12583 new = PyDict_New();
12584 if (!new)
12585 return NULL;
12586 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 int x_kind, y_kind, z_kind;
12588 void *x_data, *y_data, *z_data;
12589
Georg Brandlceee0772007-11-27 23:48:05 +000012590 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012591 if (!PyUnicode_Check(x)) {
12592 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12593 "be a string if there is a second argument");
12594 goto err;
12595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012596 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012597 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12598 "arguments must have equal length");
12599 goto err;
12600 }
12601 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602 x_kind = PyUnicode_KIND(x);
12603 y_kind = PyUnicode_KIND(y);
12604 x_data = PyUnicode_DATA(x);
12605 y_data = PyUnicode_DATA(y);
12606 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12607 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12608 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012609 if (!key || !value)
12610 goto err;
12611 res = PyDict_SetItem(new, key, value);
12612 Py_DECREF(key);
12613 Py_DECREF(value);
12614 if (res < 0)
12615 goto err;
12616 }
12617 /* create entries for deleting chars in z */
12618 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012619 z_kind = PyUnicode_KIND(z);
12620 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012621 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012623 if (!key)
12624 goto err;
12625 res = PyDict_SetItem(new, key, Py_None);
12626 Py_DECREF(key);
12627 if (res < 0)
12628 goto err;
12629 }
12630 }
12631 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632 int kind;
12633 void *data;
12634
Georg Brandlceee0772007-11-27 23:48:05 +000012635 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012636 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012637 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12638 "to maketrans it must be a dict");
12639 goto err;
12640 }
12641 /* copy entries into the new dict, converting string keys to int keys */
12642 while (PyDict_Next(x, &i, &key, &value)) {
12643 if (PyUnicode_Check(key)) {
12644 /* convert string keys to integer keys */
12645 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012646 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012647 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12648 "table must be of length 1");
12649 goto err;
12650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 kind = PyUnicode_KIND(key);
12652 data = PyUnicode_DATA(key);
12653 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012654 if (!newkey)
12655 goto err;
12656 res = PyDict_SetItem(new, newkey, value);
12657 Py_DECREF(newkey);
12658 if (res < 0)
12659 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012660 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012661 /* just keep integer keys */
12662 if (PyDict_SetItem(new, key, value) < 0)
12663 goto err;
12664 } else {
12665 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12666 "be strings or integers");
12667 goto err;
12668 }
12669 }
12670 }
12671 return new;
12672 err:
12673 Py_DECREF(new);
12674 return NULL;
12675}
12676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012677PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012678 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679\n\
12680Return a copy of the string S, where all characters have been mapped\n\
12681through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012682Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012683Unmapped characters are left untouched. Characters mapped to None\n\
12684are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685
12686static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690}
12691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012692PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012693 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012695Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696
12697static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012698unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700 return fixup(self, fixupper);
12701}
12702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012703PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012704 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012706Pad a numeric string S with zeros on the left, to fill a field\n\
12707of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
12709static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012710unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012712 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012713 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012714 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 int kind;
12716 void *data;
12717 Py_UCS4 chr;
12718
12719 if (PyUnicode_READY(self) == -1)
12720 return NULL;
12721
Martin v. Löwis18e16552006-02-15 17:27:45 +000012722 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723 return NULL;
12724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012726 if (PyUnicode_CheckExact(self)) {
12727 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012728 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012729 }
12730 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012731 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732 }
12733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012734 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735
12736 u = pad(self, fill, 0, '0');
12737
Walter Dörwald068325e2002-04-15 13:36:47 +000012738 if (u == NULL)
12739 return NULL;
12740
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012741 kind = PyUnicode_KIND(u);
12742 data = PyUnicode_DATA(u);
12743 chr = PyUnicode_READ(kind, data, fill);
12744
12745 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012746 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 PyUnicode_WRITE(kind, data, 0, chr);
12748 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749 }
12750
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012751 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012752 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754
12755#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012756static PyObject *
12757unicode__decimal2ascii(PyObject *self)
12758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012760}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761#endif
12762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012763PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012765\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012766Return True if S starts with the specified prefix, False otherwise.\n\
12767With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012768With optional end, stop comparing S at that position.\n\
12769prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770
12771static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012772unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012776 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012777 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012778 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012779 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780
Jesus Ceaac451502011-04-20 17:09:23 +020012781 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012783 if (PyTuple_Check(subobj)) {
12784 Py_ssize_t i;
12785 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012786 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012787 if (substring == NULL)
12788 return NULL;
12789 result = tailmatch(self, substring, start, end, -1);
12790 Py_DECREF(substring);
12791 if (result) {
12792 Py_RETURN_TRUE;
12793 }
12794 }
12795 /* nothing matched */
12796 Py_RETURN_FALSE;
12797 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012798 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012799 if (substring == NULL) {
12800 if (PyErr_ExceptionMatches(PyExc_TypeError))
12801 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12802 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012803 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012804 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012805 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012807 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808}
12809
12810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012811PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012812 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012814Return True if S ends with the specified suffix, False otherwise.\n\
12815With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012816With optional end, stop comparing S at that position.\n\
12817suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818
12819static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012820unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012821 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012823 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012824 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012825 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012826 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012827 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828
Jesus Ceaac451502011-04-20 17:09:23 +020012829 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012830 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012831 if (PyTuple_Check(subobj)) {
12832 Py_ssize_t i;
12833 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012834 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012836 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012837 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012838 result = tailmatch(self, substring, start, end, +1);
12839 Py_DECREF(substring);
12840 if (result) {
12841 Py_RETURN_TRUE;
12842 }
12843 }
12844 Py_RETURN_FALSE;
12845 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012846 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012847 if (substring == NULL) {
12848 if (PyErr_ExceptionMatches(PyExc_TypeError))
12849 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12850 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012851 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012852 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012853 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012854 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012855 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856}
12857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012859
12860PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012862\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012863Return a formatted version of S, using substitutions from args and kwargs.\n\
12864The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012865
Eric Smith27bbca62010-11-04 17:06:58 +000012866PyDoc_STRVAR(format_map__doc__,
12867 "S.format_map(mapping) -> str\n\
12868\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012869Return a formatted version of S, using substitutions from mapping.\n\
12870The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012871
Eric Smith4a7d76d2008-05-30 18:10:19 +000012872static PyObject *
12873unicode__format__(PyObject* self, PyObject* args)
12874{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012875 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012876
12877 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12878 return NULL;
12879
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012880 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012882 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012883}
12884
Eric Smith8c663262007-08-25 02:26:07 +000012885PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012886 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012887\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012888Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012889
12890static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012891unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012893 Py_ssize_t size;
12894
12895 /* If it's a compact object, account for base structure +
12896 character data. */
12897 if (PyUnicode_IS_COMPACT_ASCII(v))
12898 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12899 else if (PyUnicode_IS_COMPACT(v))
12900 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012901 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 else {
12903 /* If it is a two-block object, account for base object, and
12904 for character block if present. */
12905 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012906 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012907 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012908 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 }
12910 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012911 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012912 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012913 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012914 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012915 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012916
12917 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012918}
12919
12920PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012921 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012922
12923static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012924unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012925{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012926 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012927 if (!copy)
12928 return NULL;
12929 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012930}
12931
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932static PyMethodDef unicode_methods[] = {
12933
12934 /* Order is according to common usage: often used methods should
12935 appear first, since lookup is done sequentially. */
12936
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012937 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012938 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12939 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012940 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012941 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12942 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12943 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12944 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12945 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12946 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12947 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012948 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012949 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12950 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12951 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012952 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012953 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12954 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12955 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012956 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012957 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012958 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012959 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012960 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12961 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12962 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12963 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12964 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12965 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12966 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12967 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12968 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12969 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12970 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12971 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12972 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12973 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012974 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012975 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012976 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012977 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012978 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012979 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012980 {"maketrans", (PyCFunction) unicode_maketrans,
12981 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012982 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012983#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012984 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985#endif
12986
12987#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012988 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012989 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012990#endif
12991
Benjamin Peterson14339b62009-01-31 16:36:08 +000012992 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012993 {NULL, NULL}
12994};
12995
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012996static PyObject *
12997unicode_mod(PyObject *v, PyObject *w)
12998{
Brian Curtindfc80e32011-08-10 20:28:54 -050012999 if (!PyUnicode_Check(v))
13000 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013001 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013002}
13003
13004static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013005 0, /*nb_add*/
13006 0, /*nb_subtract*/
13007 0, /*nb_multiply*/
13008 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013009};
13010
Guido van Rossumd57fd912000-03-10 22:53:23 +000013011static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013012 (lenfunc) unicode_length, /* sq_length */
13013 PyUnicode_Concat, /* sq_concat */
13014 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13015 (ssizeargfunc) unicode_getitem, /* sq_item */
13016 0, /* sq_slice */
13017 0, /* sq_ass_item */
13018 0, /* sq_ass_slice */
13019 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013020};
13021
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013022static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013023unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013024{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013025 if (PyUnicode_READY(self) == -1)
13026 return NULL;
13027
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013028 if (PyIndex_Check(item)) {
13029 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013030 if (i == -1 && PyErr_Occurred())
13031 return NULL;
13032 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013033 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013034 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013035 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013036 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013037 PyObject *result;
13038 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013039 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013040 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013042 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013043 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013044 return NULL;
13045 }
13046
13047 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013048 return PyUnicode_New(0, 0);
13049 } else if (start == 0 && step == 1 &&
13050 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013051 PyUnicode_CheckExact(self)) {
13052 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013053 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013054 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013055 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013056 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013057 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013058 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013059 src_kind = PyUnicode_KIND(self);
13060 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013061 if (!PyUnicode_IS_ASCII(self)) {
13062 kind_limit = kind_maxchar_limit(src_kind);
13063 max_char = 0;
13064 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13065 ch = PyUnicode_READ(src_kind, src_data, cur);
13066 if (ch > max_char) {
13067 max_char = ch;
13068 if (max_char >= kind_limit)
13069 break;
13070 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013071 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013072 }
Victor Stinner55c99112011-10-13 01:17:06 +020013073 else
13074 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013075 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013076 if (result == NULL)
13077 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013078 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013079 dest_data = PyUnicode_DATA(result);
13080
13081 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013082 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13083 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013084 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013085 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013086 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013087 } else {
13088 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13089 return NULL;
13090 }
13091}
13092
13093static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013094 (lenfunc)unicode_length, /* mp_length */
13095 (binaryfunc)unicode_subscript, /* mp_subscript */
13096 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013097};
13098
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100/* Helpers for PyUnicode_Format() */
13101
13102static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013103getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013105 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 (*p_argidx)++;
13108 if (arglen < 0)
13109 return args;
13110 else
13111 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112 }
13113 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013114 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115 return NULL;
13116}
13117
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013118/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013120static PyObject *
13121formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013123 char *p;
13124 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013126
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127 x = PyFloat_AsDouble(v);
13128 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013129 return NULL;
13130
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013132 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013133
Eric Smith0923d1d2009-04-16 20:16:10 +000013134 p = PyOS_double_to_string(x, type, prec,
13135 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013136 if (p == NULL)
13137 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013138 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013139 PyMem_Free(p);
13140 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141}
13142
Tim Peters38fd5b62000-09-21 05:43:11 +000013143static PyObject*
13144formatlong(PyObject *val, int flags, int prec, int type)
13145{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013146 char *buf;
13147 int len;
13148 PyObject *str; /* temporary string object. */
13149 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013150
Benjamin Peterson14339b62009-01-31 16:36:08 +000013151 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13152 if (!str)
13153 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013154 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013155 Py_DECREF(str);
13156 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013157}
13158
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013159static Py_UCS4
13160formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013162 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013163 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013165 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013166 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 goto onError;
13168 }
13169 else {
13170 /* Integer input truncated to a character */
13171 long x;
13172 x = PyLong_AsLong(v);
13173 if (x == -1 && PyErr_Occurred())
13174 goto onError;
13175
13176 if (x < 0 || x > 0x10ffff) {
13177 PyErr_SetString(PyExc_OverflowError,
13178 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013179 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 }
13181
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013182 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013183 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013184
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013186 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013188 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189}
13190
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013191static int
13192repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13193{
13194 int r;
13195 assert(count > 0);
13196 assert(PyUnicode_Check(obj));
13197 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013199 if (repeated == NULL)
13200 return -1;
13201 r = _PyAccu_Accumulate(acc, repeated);
13202 Py_DECREF(repeated);
13203 return r;
13204 }
13205 else {
13206 do {
13207 if (_PyAccu_Accumulate(acc, obj))
13208 return -1;
13209 } while (--count);
13210 return 0;
13211 }
13212}
13213
Alexander Belopolsky40018472011-02-26 01:02:56 +000013214PyObject *
13215PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013217 void *fmt;
13218 int fmtkind;
13219 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013220 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013221 int r;
13222 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013225 PyObject *temp = NULL;
13226 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013227 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013228 _PyAccu acc;
13229 static PyObject *plus, *minus, *blank, *zero, *percent;
13230
13231 if (!plus && !(plus = get_latin1_char('+')))
13232 return NULL;
13233 if (!minus && !(minus = get_latin1_char('-')))
13234 return NULL;
13235 if (!blank && !(blank = get_latin1_char(' ')))
13236 return NULL;
13237 if (!zero && !(zero = get_latin1_char('0')))
13238 return NULL;
13239 if (!percent && !(percent = get_latin1_char('%')))
13240 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013241
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 PyErr_BadInternalCall();
13244 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013246 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013247 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013249 if (_PyAccu_Init(&acc))
13250 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013251 fmt = PyUnicode_DATA(uformat);
13252 fmtkind = PyUnicode_KIND(uformat);
13253 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13254 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013257 arglen = PyTuple_Size(args);
13258 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013259 }
13260 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013261 arglen = -1;
13262 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013263 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013264 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013265 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013266 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267
13268 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013269 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013270 PyObject *nonfmt;
13271 Py_ssize_t nonfmtpos;
13272 nonfmtpos = fmtpos++;
13273 while (fmtcnt >= 0 &&
13274 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13275 fmtpos++;
13276 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013277 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013278 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013279 if (nonfmt == NULL)
13280 goto onError;
13281 r = _PyAccu_Accumulate(&acc, nonfmt);
13282 Py_DECREF(nonfmt);
13283 if (r)
13284 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013285 }
13286 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013287 /* Got a format specifier */
13288 int flags = 0;
13289 Py_ssize_t width = -1;
13290 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013292 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013293 int isnumok;
13294 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013295 void *pbuf = NULL;
13296 Py_ssize_t pindex, len;
13297 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013299 fmtpos++;
13300 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13301 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013302 Py_ssize_t keylen;
13303 PyObject *key;
13304 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013305
Benjamin Peterson29060642009-01-31 22:14:21 +000013306 if (dict == NULL) {
13307 PyErr_SetString(PyExc_TypeError,
13308 "format requires a mapping");
13309 goto onError;
13310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013312 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013313 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 /* Skip over balanced parentheses */
13315 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013316 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013317 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013318 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013320 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013321 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013322 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013323 if (fmtcnt < 0 || pcount > 0) {
13324 PyErr_SetString(PyExc_ValueError,
13325 "incomplete format key");
13326 goto onError;
13327 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013328 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013329 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013330 if (key == NULL)
13331 goto onError;
13332 if (args_owned) {
13333 Py_DECREF(args);
13334 args_owned = 0;
13335 }
13336 args = PyObject_GetItem(dict, key);
13337 Py_DECREF(key);
13338 if (args == NULL) {
13339 goto onError;
13340 }
13341 args_owned = 1;
13342 arglen = -1;
13343 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013344 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013345 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013346 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 case '-': flags |= F_LJUST; continue;
13348 case '+': flags |= F_SIGN; continue;
13349 case ' ': flags |= F_BLANK; continue;
13350 case '#': flags |= F_ALT; continue;
13351 case '0': flags |= F_ZERO; continue;
13352 }
13353 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013354 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 if (c == '*') {
13356 v = getnextarg(args, arglen, &argidx);
13357 if (v == NULL)
13358 goto onError;
13359 if (!PyLong_Check(v)) {
13360 PyErr_SetString(PyExc_TypeError,
13361 "* wants int");
13362 goto onError;
13363 }
13364 width = PyLong_AsLong(v);
13365 if (width == -1 && PyErr_Occurred())
13366 goto onError;
13367 if (width < 0) {
13368 flags |= F_LJUST;
13369 width = -width;
13370 }
13371 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013372 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 }
13374 else if (c >= '0' && c <= '9') {
13375 width = c - '0';
13376 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 if (c < '0' || c > '9')
13379 break;
13380 if ((width*10) / 10 != width) {
13381 PyErr_SetString(PyExc_ValueError,
13382 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013383 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 }
13385 width = width*10 + (c - '0');
13386 }
13387 }
13388 if (c == '.') {
13389 prec = 0;
13390 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013391 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 if (c == '*') {
13393 v = getnextarg(args, arglen, &argidx);
13394 if (v == NULL)
13395 goto onError;
13396 if (!PyLong_Check(v)) {
13397 PyErr_SetString(PyExc_TypeError,
13398 "* wants int");
13399 goto onError;
13400 }
13401 prec = PyLong_AsLong(v);
13402 if (prec == -1 && PyErr_Occurred())
13403 goto onError;
13404 if (prec < 0)
13405 prec = 0;
13406 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013407 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 }
13409 else if (c >= '0' && c <= '9') {
13410 prec = c - '0';
13411 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013412 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 if (c < '0' || c > '9')
13414 break;
13415 if ((prec*10) / 10 != prec) {
13416 PyErr_SetString(PyExc_ValueError,
13417 "prec too big");
13418 goto onError;
13419 }
13420 prec = prec*10 + (c - '0');
13421 }
13422 }
13423 } /* prec */
13424 if (fmtcnt >= 0) {
13425 if (c == 'h' || c == 'l' || c == 'L') {
13426 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013427 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 }
13429 }
13430 if (fmtcnt < 0) {
13431 PyErr_SetString(PyExc_ValueError,
13432 "incomplete format");
13433 goto onError;
13434 }
13435 if (c != '%') {
13436 v = getnextarg(args, arglen, &argidx);
13437 if (v == NULL)
13438 goto onError;
13439 }
13440 sign = 0;
13441 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013442 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 switch (c) {
13444
13445 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013446 _PyAccu_Accumulate(&acc, percent);
13447 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013448
13449 case 's':
13450 case 'r':
13451 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013452 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013453 temp = v;
13454 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013455 }
13456 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 if (c == 's')
13458 temp = PyObject_Str(v);
13459 else if (c == 'r')
13460 temp = PyObject_Repr(v);
13461 else
13462 temp = PyObject_ASCII(v);
13463 if (temp == NULL)
13464 goto onError;
13465 if (PyUnicode_Check(temp))
13466 /* nothing to do */;
13467 else {
13468 Py_DECREF(temp);
13469 PyErr_SetString(PyExc_TypeError,
13470 "%s argument has non-string str()");
13471 goto onError;
13472 }
13473 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013474 if (PyUnicode_READY(temp) == -1) {
13475 Py_CLEAR(temp);
13476 goto onError;
13477 }
13478 pbuf = PyUnicode_DATA(temp);
13479 kind = PyUnicode_KIND(temp);
13480 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 if (prec >= 0 && len > prec)
13482 len = prec;
13483 break;
13484
13485 case 'i':
13486 case 'd':
13487 case 'u':
13488 case 'o':
13489 case 'x':
13490 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013491 isnumok = 0;
13492 if (PyNumber_Check(v)) {
13493 PyObject *iobj=NULL;
13494
13495 if (PyLong_Check(v)) {
13496 iobj = v;
13497 Py_INCREF(iobj);
13498 }
13499 else {
13500 iobj = PyNumber_Long(v);
13501 }
13502 if (iobj!=NULL) {
13503 if (PyLong_Check(iobj)) {
13504 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013505 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013506 Py_DECREF(iobj);
13507 if (!temp)
13508 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013509 if (PyUnicode_READY(temp) == -1) {
13510 Py_CLEAR(temp);
13511 goto onError;
13512 }
13513 pbuf = PyUnicode_DATA(temp);
13514 kind = PyUnicode_KIND(temp);
13515 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 sign = 1;
13517 }
13518 else {
13519 Py_DECREF(iobj);
13520 }
13521 }
13522 }
13523 if (!isnumok) {
13524 PyErr_Format(PyExc_TypeError,
13525 "%%%c format: a number is required, "
13526 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13527 goto onError;
13528 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013529 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013531 fillobj = zero;
13532 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013533 break;
13534
13535 case 'e':
13536 case 'E':
13537 case 'f':
13538 case 'F':
13539 case 'g':
13540 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013541 temp = formatfloat(v, flags, prec, c);
13542 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013544 if (PyUnicode_READY(temp) == -1) {
13545 Py_CLEAR(temp);
13546 goto onError;
13547 }
13548 pbuf = PyUnicode_DATA(temp);
13549 kind = PyUnicode_KIND(temp);
13550 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013552 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013553 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013554 fillobj = zero;
13555 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013556 break;
13557
13558 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013559 {
13560 Py_UCS4 ch = formatchar(v);
13561 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013563 temp = _PyUnicode_FromUCS4(&ch, 1);
13564 if (temp == NULL)
13565 goto onError;
13566 pbuf = PyUnicode_DATA(temp);
13567 kind = PyUnicode_KIND(temp);
13568 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013570 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013571
13572 default:
13573 PyErr_Format(PyExc_ValueError,
13574 "unsupported format character '%c' (0x%x) "
13575 "at index %zd",
13576 (31<=c && c<=126) ? (char)c : '?',
13577 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013578 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013579 goto onError;
13580 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013581 /* pbuf is initialized here. */
13582 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013584 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13585 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013587 pindex++;
13588 }
13589 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13590 signobj = plus;
13591 len--;
13592 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 }
13594 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013595 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013597 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 else
13599 sign = 0;
13600 }
13601 if (width < len)
13602 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013603 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013604 if (fill != ' ') {
13605 assert(signobj != NULL);
13606 if (_PyAccu_Accumulate(&acc, signobj))
13607 goto onError;
13608 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013609 if (width > len)
13610 width--;
13611 }
13612 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013614 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013616 second = get_latin1_char(
13617 PyUnicode_READ(kind, pbuf, pindex + 1));
13618 pindex += 2;
13619 if (second == NULL ||
13620 _PyAccu_Accumulate(&acc, zero) ||
13621 _PyAccu_Accumulate(&acc, second))
13622 goto onError;
13623 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 width -= 2;
13626 if (width < 0)
13627 width = 0;
13628 len -= 2;
13629 }
13630 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013631 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013632 if (repeat_accumulate(&acc, fillobj, width - len))
13633 goto onError;
13634 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 }
13636 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013637 if (sign) {
13638 assert(signobj != NULL);
13639 if (_PyAccu_Accumulate(&acc, signobj))
13640 goto onError;
13641 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013643 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13644 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013645 second = get_latin1_char(
13646 PyUnicode_READ(kind, pbuf, pindex + 1));
13647 pindex += 2;
13648 if (second == NULL ||
13649 _PyAccu_Accumulate(&acc, zero) ||
13650 _PyAccu_Accumulate(&acc, second))
13651 goto onError;
13652 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013653 }
13654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013655 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013656 if (temp != NULL) {
13657 assert(pbuf == PyUnicode_DATA(temp));
13658 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013659 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013660 else {
13661 const char *p = (const char *) pbuf;
13662 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013663 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013664 v = PyUnicode_FromKindAndData(kind, p, len);
13665 }
13666 if (v == NULL)
13667 goto onError;
13668 r = _PyAccu_Accumulate(&acc, v);
13669 Py_DECREF(v);
13670 if (r)
13671 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013672 if (width > len && repeat_accumulate(&acc, blank, width - len))
13673 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 if (dict && (argidx < arglen) && c != '%') {
13675 PyErr_SetString(PyExc_TypeError,
13676 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013677 goto onError;
13678 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013679 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013680 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013681 } /* until end */
13682 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 PyErr_SetString(PyExc_TypeError,
13684 "not all arguments converted during string formatting");
13685 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013686 }
13687
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013688 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013689 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013690 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013691 }
13692 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013693 Py_XDECREF(temp);
13694 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013695 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013696
Benjamin Peterson29060642009-01-31 22:14:21 +000013697 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013698 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013699 Py_XDECREF(temp);
13700 Py_XDECREF(second);
13701 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013702 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013703 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013704 }
13705 return NULL;
13706}
13707
Jeremy Hylton938ace62002-07-17 16:30:39 +000013708static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013709unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13710
Tim Peters6d6c1a32001-08-02 04:15:00 +000013711static PyObject *
13712unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13713{
Benjamin Peterson29060642009-01-31 22:14:21 +000013714 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013715 static char *kwlist[] = {"object", "encoding", "errors", 0};
13716 char *encoding = NULL;
13717 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013718
Benjamin Peterson14339b62009-01-31 16:36:08 +000013719 if (type != &PyUnicode_Type)
13720 return unicode_subtype_new(type, args, kwds);
13721 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013722 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013723 return NULL;
13724 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013725 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013726 if (encoding == NULL && errors == NULL)
13727 return PyObject_Str(x);
13728 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013729 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013730}
13731
Guido van Rossume023fe02001-08-30 03:12:59 +000013732static PyObject *
13733unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13734{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013735 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013736 Py_ssize_t length, char_size;
13737 int share_wstr, share_utf8;
13738 unsigned int kind;
13739 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013740
Benjamin Peterson14339b62009-01-31 16:36:08 +000013741 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013742
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013743 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013744 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013745 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013746 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013747 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013748 return NULL;
13749
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013750 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013751 if (self == NULL) {
13752 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013753 return NULL;
13754 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013755 kind = PyUnicode_KIND(unicode);
13756 length = PyUnicode_GET_LENGTH(unicode);
13757
13758 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013759#ifdef Py_DEBUG
13760 _PyUnicode_HASH(self) = -1;
13761#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013762 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013763#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013764 _PyUnicode_STATE(self).interned = 0;
13765 _PyUnicode_STATE(self).kind = kind;
13766 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013767 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013768 _PyUnicode_STATE(self).ready = 1;
13769 _PyUnicode_WSTR(self) = NULL;
13770 _PyUnicode_UTF8_LENGTH(self) = 0;
13771 _PyUnicode_UTF8(self) = NULL;
13772 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013773 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013774
13775 share_utf8 = 0;
13776 share_wstr = 0;
13777 if (kind == PyUnicode_1BYTE_KIND) {
13778 char_size = 1;
13779 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13780 share_utf8 = 1;
13781 }
13782 else if (kind == PyUnicode_2BYTE_KIND) {
13783 char_size = 2;
13784 if (sizeof(wchar_t) == 2)
13785 share_wstr = 1;
13786 }
13787 else {
13788 assert(kind == PyUnicode_4BYTE_KIND);
13789 char_size = 4;
13790 if (sizeof(wchar_t) == 4)
13791 share_wstr = 1;
13792 }
13793
13794 /* Ensure we won't overflow the length. */
13795 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13796 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013798 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013799 data = PyObject_MALLOC((length + 1) * char_size);
13800 if (data == NULL) {
13801 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013802 goto onError;
13803 }
13804
Victor Stinnerc3c74152011-10-02 20:39:55 +020013805 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013806 if (share_utf8) {
13807 _PyUnicode_UTF8_LENGTH(self) = length;
13808 _PyUnicode_UTF8(self) = data;
13809 }
13810 if (share_wstr) {
13811 _PyUnicode_WSTR_LENGTH(self) = length;
13812 _PyUnicode_WSTR(self) = (wchar_t *)data;
13813 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013814
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013815 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013816 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013817 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013818#ifdef Py_DEBUG
13819 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13820#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013821 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013822 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013823
13824onError:
13825 Py_DECREF(unicode);
13826 Py_DECREF(self);
13827 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013828}
13829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013830PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013831 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013832\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013833Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013834encoding defaults to the current default string encoding.\n\
13835errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013836
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013837static PyObject *unicode_iter(PyObject *seq);
13838
Guido van Rossumd57fd912000-03-10 22:53:23 +000013839PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013840 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013841 "str", /* tp_name */
13842 sizeof(PyUnicodeObject), /* tp_size */
13843 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013844 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013845 (destructor)unicode_dealloc, /* tp_dealloc */
13846 0, /* tp_print */
13847 0, /* tp_getattr */
13848 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013849 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013850 unicode_repr, /* tp_repr */
13851 &unicode_as_number, /* tp_as_number */
13852 &unicode_as_sequence, /* tp_as_sequence */
13853 &unicode_as_mapping, /* tp_as_mapping */
13854 (hashfunc) unicode_hash, /* tp_hash*/
13855 0, /* tp_call*/
13856 (reprfunc) unicode_str, /* tp_str */
13857 PyObject_GenericGetAttr, /* tp_getattro */
13858 0, /* tp_setattro */
13859 0, /* tp_as_buffer */
13860 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013861 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013862 unicode_doc, /* tp_doc */
13863 0, /* tp_traverse */
13864 0, /* tp_clear */
13865 PyUnicode_RichCompare, /* tp_richcompare */
13866 0, /* tp_weaklistoffset */
13867 unicode_iter, /* tp_iter */
13868 0, /* tp_iternext */
13869 unicode_methods, /* tp_methods */
13870 0, /* tp_members */
13871 0, /* tp_getset */
13872 &PyBaseObject_Type, /* tp_base */
13873 0, /* tp_dict */
13874 0, /* tp_descr_get */
13875 0, /* tp_descr_set */
13876 0, /* tp_dictoffset */
13877 0, /* tp_init */
13878 0, /* tp_alloc */
13879 unicode_new, /* tp_new */
13880 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881};
13882
13883/* Initialize the Unicode implementation */
13884
Victor Stinner3a50e702011-10-18 21:21:00 +020013885int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013887 int i;
13888
Thomas Wouters477c8d52006-05-27 19:21:47 +000013889 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013890 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013891 0x000A, /* LINE FEED */
13892 0x000D, /* CARRIAGE RETURN */
13893 0x001C, /* FILE SEPARATOR */
13894 0x001D, /* GROUP SEPARATOR */
13895 0x001E, /* RECORD SEPARATOR */
13896 0x0085, /* NEXT LINE */
13897 0x2028, /* LINE SEPARATOR */
13898 0x2029, /* PARAGRAPH SEPARATOR */
13899 };
13900
Fred Drakee4315f52000-05-09 19:53:39 +000013901 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013902 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013903 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013904 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013905 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013906
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013907 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013908 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013909 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013910 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013911
13912 /* initialize the linebreak bloom filter */
13913 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013914 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013915 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013916
13917 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013918
13919#ifdef HAVE_MBCS
13920 winver.dwOSVersionInfoSize = sizeof(winver);
13921 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13922 PyErr_SetFromWindowsErr(0);
13923 return -1;
13924 }
13925#endif
13926 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013927}
13928
13929/* Finalize the Unicode implementation */
13930
Christian Heimesa156e092008-02-16 07:38:31 +000013931int
13932PyUnicode_ClearFreeList(void)
13933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013934 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013935}
13936
Guido van Rossumd57fd912000-03-10 22:53:23 +000013937void
Thomas Wouters78890102000-07-22 19:25:51 +000013938_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013940 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013941
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013942 Py_XDECREF(unicode_empty);
13943 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013944
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013945 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013946 if (unicode_latin1[i]) {
13947 Py_DECREF(unicode_latin1[i]);
13948 unicode_latin1[i] = NULL;
13949 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013950 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013951 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013952 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013954
Walter Dörwald16807132007-05-25 13:52:07 +000013955void
13956PyUnicode_InternInPlace(PyObject **p)
13957{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013958 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013959 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013960#ifdef Py_DEBUG
13961 assert(s != NULL);
13962 assert(_PyUnicode_CHECK(s));
13963#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013965 return;
13966#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 /* If it's a subclass, we don't really know what putting
13968 it in the interned dict might do. */
13969 if (!PyUnicode_CheckExact(s))
13970 return;
13971 if (PyUnicode_CHECK_INTERNED(s))
13972 return;
13973 if (interned == NULL) {
13974 interned = PyDict_New();
13975 if (interned == NULL) {
13976 PyErr_Clear(); /* Don't leave an exception */
13977 return;
13978 }
13979 }
13980 /* It might be that the GetItem call fails even
13981 though the key is present in the dictionary,
13982 namely when this happens during a stack overflow. */
13983 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013984 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013985 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013986
Benjamin Peterson29060642009-01-31 22:14:21 +000013987 if (t) {
13988 Py_INCREF(t);
13989 Py_DECREF(*p);
13990 *p = t;
13991 return;
13992 }
Walter Dörwald16807132007-05-25 13:52:07 +000013993
Benjamin Peterson14339b62009-01-31 16:36:08 +000013994 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013995 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013996 PyErr_Clear();
13997 PyThreadState_GET()->recursion_critical = 0;
13998 return;
13999 }
14000 PyThreadState_GET()->recursion_critical = 0;
14001 /* The two references in interned are not counted by refcnt.
14002 The deallocator will take care of this */
14003 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014004 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014005}
14006
14007void
14008PyUnicode_InternImmortal(PyObject **p)
14009{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014010 PyUnicode_InternInPlace(p);
14011 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014012 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014013 Py_INCREF(*p);
14014 }
Walter Dörwald16807132007-05-25 13:52:07 +000014015}
14016
14017PyObject *
14018PyUnicode_InternFromString(const char *cp)
14019{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014020 PyObject *s = PyUnicode_FromString(cp);
14021 if (s == NULL)
14022 return NULL;
14023 PyUnicode_InternInPlace(&s);
14024 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014025}
14026
Alexander Belopolsky40018472011-02-26 01:02:56 +000014027void
14028_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014029{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014030 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014031 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014032 Py_ssize_t i, n;
14033 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014034
Benjamin Peterson14339b62009-01-31 16:36:08 +000014035 if (interned == NULL || !PyDict_Check(interned))
14036 return;
14037 keys = PyDict_Keys(interned);
14038 if (keys == NULL || !PyList_Check(keys)) {
14039 PyErr_Clear();
14040 return;
14041 }
Walter Dörwald16807132007-05-25 13:52:07 +000014042
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14044 detector, interned unicode strings are not forcibly deallocated;
14045 rather, we give them their stolen references back, and then clear
14046 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014047
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 n = PyList_GET_SIZE(keys);
14049 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014050 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014051 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014052 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014053 if (PyUnicode_READY(s) == -1) {
14054 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014055 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014056 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014057 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014058 case SSTATE_NOT_INTERNED:
14059 /* XXX Shouldn't happen */
14060 break;
14061 case SSTATE_INTERNED_IMMORTAL:
14062 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014063 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014064 break;
14065 case SSTATE_INTERNED_MORTAL:
14066 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014067 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014068 break;
14069 default:
14070 Py_FatalError("Inconsistent interned string state.");
14071 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014072 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014073 }
14074 fprintf(stderr, "total size of all interned strings: "
14075 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14076 "mortal/immortal\n", mortal_size, immortal_size);
14077 Py_DECREF(keys);
14078 PyDict_Clear(interned);
14079 Py_DECREF(interned);
14080 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014081}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014082
14083
14084/********************* Unicode Iterator **************************/
14085
14086typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014087 PyObject_HEAD
14088 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014089 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014090} unicodeiterobject;
14091
14092static void
14093unicodeiter_dealloc(unicodeiterobject *it)
14094{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014095 _PyObject_GC_UNTRACK(it);
14096 Py_XDECREF(it->it_seq);
14097 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014098}
14099
14100static int
14101unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14102{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014103 Py_VISIT(it->it_seq);
14104 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014105}
14106
14107static PyObject *
14108unicodeiter_next(unicodeiterobject *it)
14109{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014110 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014111
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 assert(it != NULL);
14113 seq = it->it_seq;
14114 if (seq == NULL)
14115 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014116 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014118 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14119 int kind = PyUnicode_KIND(seq);
14120 void *data = PyUnicode_DATA(seq);
14121 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14122 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014123 if (item != NULL)
14124 ++it->it_index;
14125 return item;
14126 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014127
Benjamin Peterson14339b62009-01-31 16:36:08 +000014128 Py_DECREF(seq);
14129 it->it_seq = NULL;
14130 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014131}
14132
14133static PyObject *
14134unicodeiter_len(unicodeiterobject *it)
14135{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014136 Py_ssize_t len = 0;
14137 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014138 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014139 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014140}
14141
14142PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14143
14144static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014145 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014146 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014148};
14149
14150PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014151 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14152 "str_iterator", /* tp_name */
14153 sizeof(unicodeiterobject), /* tp_basicsize */
14154 0, /* tp_itemsize */
14155 /* methods */
14156 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14157 0, /* tp_print */
14158 0, /* tp_getattr */
14159 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014160 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014161 0, /* tp_repr */
14162 0, /* tp_as_number */
14163 0, /* tp_as_sequence */
14164 0, /* tp_as_mapping */
14165 0, /* tp_hash */
14166 0, /* tp_call */
14167 0, /* tp_str */
14168 PyObject_GenericGetAttr, /* tp_getattro */
14169 0, /* tp_setattro */
14170 0, /* tp_as_buffer */
14171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14172 0, /* tp_doc */
14173 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14174 0, /* tp_clear */
14175 0, /* tp_richcompare */
14176 0, /* tp_weaklistoffset */
14177 PyObject_SelfIter, /* tp_iter */
14178 (iternextfunc)unicodeiter_next, /* tp_iternext */
14179 unicodeiter_methods, /* tp_methods */
14180 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014181};
14182
14183static PyObject *
14184unicode_iter(PyObject *seq)
14185{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014187
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 if (!PyUnicode_Check(seq)) {
14189 PyErr_BadInternalCall();
14190 return NULL;
14191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014192 if (PyUnicode_READY(seq) == -1)
14193 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014194 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14195 if (it == NULL)
14196 return NULL;
14197 it->it_index = 0;
14198 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014199 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014200 _PyObject_GC_TRACK(it);
14201 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014202}
14203
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014204
14205size_t
14206Py_UNICODE_strlen(const Py_UNICODE *u)
14207{
14208 int res = 0;
14209 while(*u++)
14210 res++;
14211 return res;
14212}
14213
14214Py_UNICODE*
14215Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14216{
14217 Py_UNICODE *u = s1;
14218 while ((*u++ = *s2++));
14219 return s1;
14220}
14221
14222Py_UNICODE*
14223Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14224{
14225 Py_UNICODE *u = s1;
14226 while ((*u++ = *s2++))
14227 if (n-- == 0)
14228 break;
14229 return s1;
14230}
14231
14232Py_UNICODE*
14233Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14234{
14235 Py_UNICODE *u1 = s1;
14236 u1 += Py_UNICODE_strlen(u1);
14237 Py_UNICODE_strcpy(u1, s2);
14238 return s1;
14239}
14240
14241int
14242Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14243{
14244 while (*s1 && *s2 && *s1 == *s2)
14245 s1++, s2++;
14246 if (*s1 && *s2)
14247 return (*s1 < *s2) ? -1 : +1;
14248 if (*s1)
14249 return 1;
14250 if (*s2)
14251 return -1;
14252 return 0;
14253}
14254
14255int
14256Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14257{
14258 register Py_UNICODE u1, u2;
14259 for (; n != 0; n--) {
14260 u1 = *s1;
14261 u2 = *s2;
14262 if (u1 != u2)
14263 return (u1 < u2) ? -1 : +1;
14264 if (u1 == '\0')
14265 return 0;
14266 s1++;
14267 s2++;
14268 }
14269 return 0;
14270}
14271
14272Py_UNICODE*
14273Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14274{
14275 const Py_UNICODE *p;
14276 for (p = s; *p; p++)
14277 if (*p == c)
14278 return (Py_UNICODE*)p;
14279 return NULL;
14280}
14281
14282Py_UNICODE*
14283Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14284{
14285 const Py_UNICODE *p;
14286 p = s + Py_UNICODE_strlen(s);
14287 while (p != s) {
14288 p--;
14289 if (*p == c)
14290 return (Py_UNICODE*)p;
14291 }
14292 return NULL;
14293}
Victor Stinner331ea922010-08-10 16:37:20 +000014294
Victor Stinner71133ff2010-09-01 23:43:53 +000014295Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014296PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014297{
Victor Stinner577db2c2011-10-11 22:12:48 +020014298 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014299 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014301 if (!PyUnicode_Check(unicode)) {
14302 PyErr_BadArgument();
14303 return NULL;
14304 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014305 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014306 if (u == NULL)
14307 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014308 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014309 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014310 PyErr_NoMemory();
14311 return NULL;
14312 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014313 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014314 size *= sizeof(Py_UNICODE);
14315 copy = PyMem_Malloc(size);
14316 if (copy == NULL) {
14317 PyErr_NoMemory();
14318 return NULL;
14319 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014320 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014321 return copy;
14322}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014323
Georg Brandl66c221e2010-10-14 07:04:07 +000014324/* A _string module, to export formatter_parser and formatter_field_name_split
14325 to the string.Formatter class implemented in Python. */
14326
14327static PyMethodDef _string_methods[] = {
14328 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14329 METH_O, PyDoc_STR("split the argument as a field name")},
14330 {"formatter_parser", (PyCFunction) formatter_parser,
14331 METH_O, PyDoc_STR("parse the argument as a format string")},
14332 {NULL, NULL}
14333};
14334
14335static struct PyModuleDef _string_module = {
14336 PyModuleDef_HEAD_INIT,
14337 "_string",
14338 PyDoc_STR("string helper module"),
14339 0,
14340 _string_methods,
14341 NULL,
14342 NULL,
14343 NULL,
14344 NULL
14345};
14346
14347PyMODINIT_FUNC
14348PyInit__string(void)
14349{
14350 return PyModule_Create(&_string_module);
14351}
14352
14353
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014354#ifdef __cplusplus
14355}
14356#endif